DEV Community

Tanaike for Google Developer Experts

Posted on

Harnessing Google Workspace MCP Servers with Google Apps Script

Step-by-step guide to using Google Workspace MCP servers with Google Apps Script and GASADK

Harnessing Google Workspace MCP Servers with Google Apps Script

On November 24, 2026, Google Workspace Model Context Protocol (MCP) servers reached General Availability (GA) Ref. That milestone opens official hosted MCP endpoints for Gmail, Google Drive, Docs, Sheets, Slides, Calendar, Chat, and Tasks—not only to enterprise Google Workspace domains, but also to personal Gmail accounts. Instead of maintaining self-hosted wrappers or hand-coding fragile REST schemas for every Workspace product, you can let an AI agent talk directly to Google's managed endpoints in plain language Ref.

New to scripting or Google Apps Script? You do not need to be a software engineer to follow this guide. If you already use Google Drive, Gmail, or Google Sheets every day, you can run every example in this article simply by copying and pasting the provided code into your browser—no local software installation, no paid server, and no coding from scratch required.

Here is a quick plain-English overview of the three building blocks we will connect:

  • Google Workspace MCP Servers: Official "AI adapters" hosted by Google that let an AI assistant safely read and operate on your Drive, Sheets, Gmail, and other Workspace apps using your own permissions (free up to 5,000 requests/day on the Standard Tier, no credit card required).
  • Google Apps Script (GAS): Google's free, browser-based automation platform built right into your Google Account. You edit and run scripts directly in a web tab—nothing to install on your computer.
  • GASADK Ref: An open-source library for Apps Script that connects Gemini AI to Google Workspace MCP servers in a single line (LlmAgent.createWorkspaceMcpServers()). It also includes automatic model and thinking routing powered by the Gemini Decisions API (gemini-decision-1), defaulting to modelRouting: "efficient" so simple tasks stay fast and inexpensive while complex multi-step tasks automatically upgrade to stronger models.

This hands-on guide walks you through the exact one-time setup, explains each step in plain terms alongside technical details for developers, and provides two complete, copy-pasteable scripts you can run right away.

Overall architecture of GASADK connecting Google Apps Script to official Google Workspace MCP servers

Figure 1: Overall architecture of GASADK connecting Google Apps Script to official Google Workspace MCP servers via an AI-agent OAuth 2.0 client, Gemini Decisions API dynamic routing, and Streamable HTTP endpoints.

As illustrated in Figure 1, GASADK sits inside your Apps Script runtime as the MCP host and agent orchestrator. When you invoke agent.run(prompt), GASADK first consults gemini-decision-1 to pick the optimal Gemini model and thinking level for the task. It then executes tool discovery and tool calls over Streamable HTTP against Google's remote MCP servers—passing an OAuth 2.0 bearer token obtained through an AI-agent-enabled client—and can even blend remote MCP tools with local native Apps Script tools inside the same execution loop.


Why ScriptApp.getOAuthToken() Does Not Work Here

Before touching any code, one quick security concept is worth knowing—especially if you have used Apps Script before or are wondering why we cannot skip the login setup. Think of Google's security like building keycards: Google now distinguishes between a regular app keycard (used by normal scripts) and a special AI-agent keycard required to unlock Google Workspace MCP servers.

In typical Apps Script projects, developers call Google APIs by passing ScriptApp.getOAuthToken() in the Authorization header.

That fails with Google Workspace MCP servers.

Google requires every user-delegated OAuth 2.0 client calling its remote MCP endpoints to have the Use this client for an AI-powered agent flag enabled in Google Cloud Console. According to the official configuration guide Ref, you cannot enable that flag on the default OAuth client that Apps Script creates and manages for your script. Crucially, even if you link your Apps Script project to a standard Google Cloud project and create a new AI-agent OAuth client inside that same project, ScriptApp.getOAuthToken() cannot be bound to your custom client—it always mints tokens from Apps Script's internal default client.

While some older Apps Script projects created before GA (for example, during the Developer Preview period) may still appear to accept ScriptApp.getOAuthToken() temporarily, newly created projects and personal Gmail setups following the November 24, 2026 GA rules risk receiving a generic invalid token error. To keep your automation reliable and fully compliant with Google's official Apps Script guidance, always use the OAuth2 for Apps Script library Ref backed by a dedicated Web application OAuth 2.0 client with Use this client for an AI-powered agent checked. Once that token is cached in UserProperties with a refresh token, your script reuses it cleanly across runs without touching ScriptApp.getOAuthToken().


Step-by-Step Setup

Setting up the entire stack takes about five minutes. Figure 2 outlines the four-stage setup flow from Google Cloud Personal Mode onboarding through one-time browser authorization in Apps Script.

Step-by-step OAuth 2.0 and Apps Script setup workflow

Figure 2: Four-step setup workflow covering Google Cloud Personal Mode onboarding, Apps Script library registration, minimal manifest and Script Properties configuration, and one-time OAuth 2.0 browser consent.

Step 1: Configure Google Cloud via Personal Mode Onboarding

If you are running this automation for your own Google Account (either a personal @gmail.com address or your individual Workspace account), use Google's Personal mode onboarding flow Ref. It enables the core Workspace APIs and MCP services, skips separate OAuth consent screen verification, and creates an AI-agent OAuth 2.0 Web client on a single page.

  1. Open the Personal mode onboarding page Ref and select an existing personal-mode Google Cloud project or create a new one.
  2. Enter a recognizable client Name (for example, GASADK Workspace MCP).
  3. Confirm that Application type is set to Web application and that Use this client for an AI-powered agent is checked.
  4. Under Authorized redirect URIs, click + Add URI and enter https://script.google.com/macros/d/{SCRIPT_ID}/usercallback, replacing {SCRIPT_ID} with your Apps Script project's Script ID. (Tip for first-time users: create your empty Apps Script project in Step 2 first so you can copy its Script ID from Project Settings, or add the URI later in Google Auth Platform > Clients after logAuthUrl() prints it in Step 4.)
  5. Review and accept the Google API Services User Data Policy, click Continue, and copy your Client ID and Client Secret.

Personal mode onboarding automatically enables all required APIs for you. If you instead reuse an existing Google Cloud project (or build a multi-user setup), make sure all four of the following APIs required by Sample 1 and Sample 2 are enabled—both the standard product API and its companion MCP API:

  • Google Drive API (drive.googleapis.com) and Drive MCP API (drivemcp.googleapis.com)
  • Google Sheets API (sheets.googleapis.com) and Sheets MCP API (sheetsmcp.googleapis.com)

You can enable all four in one click via the Google Cloud Console Ref or via the gcloud CLI:

gcloud services enable \
  drive.googleapis.com drivemcp.googleapis.com \
  sheets.googleapis.com sheetsmcp.googleapis.com \
  --project=YOUR_PROJECT_ID
Enter fullscreen mode Exit fullscreen mode

Building a multi-user tool for an entire team or Workspace domain? Skip Personal mode onboarding and follow the manual multi-user setup in the official guide Ref: enable the required product APIs and *mcp.googleapis.com services above, configure Google Auth Platform Branding/Audience/Data Access scopes, and create a Web application OAuth client with Use this client for an AI-powered agent selected.

Step 2: Create an Apps Script Project and Add Libraries

Open the Google Apps Script editor (script.google.com) in your browser and click New project in the top-left corner. In the left sidebar, click the + button next to Libraries, paste each Script ID below, click Look up, pick the latest version, and click Add:

  1. GASADK (version 15 or later) Ref: Script ID 1w2mwhWQd4_6rom-UBRPD8gayBoqGH_87awSBVqGI8DdaQI_pOeSuGYDu with identifier GASADK.
  2. OAuth2 for Apps Script Ref: Script ID 1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF with identifier OAuth2.

Always select the latest numbered version (version 15 or later for GASADK) so LlmAgent.createWorkspaceMcpServers() and dynamic model routing are available.

Step 3: Configure appsscript.json and Script Properties

Because all MCP calls and OAuth exchanges travel over UrlFetchApp using your dedicated OAuth2 library token, your Apps Script manifest needs only a single minimal permission scope. Click the gear icon (Project Settings) in the left sidebar, check Show "appsscript.json" manifest file in editor, switch back to the Editor (< > icon), click appsscript.json, keep the latest library version numbers inserted during Step 2, and ensure oauthScopes includes https://www.googleapis.com/auth/script.external_request:

{
  "timeZone": "Asia/Tokyo",
  "dependencies": {
    "libraries": [
      {
        "userSymbol": "GASADK",
        "version": "15",
        "libraryId": "1w2mwhWQd4_6rom-UBRPD8gayBoqGH_87awSBVqGI8DdaQI_pOeSuGYDu"
      },
      {
        "userSymbol": "OAuth2",
        "version": "43",
        "libraryId": "1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF"
      }
    ]
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "oauthScopes": ["https://www.googleapis.com/auth/script.external_request"]
}
Enter fullscreen mode Exit fullscreen mode

Next, return to Project Settings (the gear icon), scroll down to Script Properties, click Add script property, and save these three keys:

  • GEMINI_API_KEY: Your Gemini API key, which you can create for free in Google AI Studio Ref.
  • OAUTH_CLIENT_ID: The Client ID you copied in Step 1.
  • OAUTH_CLIENT_SECRET: The Client Secret you copied in Step 1.

Keeping credentials in Script Properties rather than hardcoding them in Code.gs avoids accidental leaks when sharing or versioning your project.

Step 4: Add the OAuth2 Helper and Authorize Once

Paste the OAuth2 helper block below into Code.gs. Notice two crucial parameters at the bottom of getWorkspaceMcpService_(): .setParam("access_type", "offline") and .setParam("prompt", "consent"). Web application OAuth clients default to online access, which forces you to re-authenticate every hour. Requesting offline access with explicit consent guarantees Google issues a refresh token so Apps Script refreshes expired access tokens silently.

/**
 * Builds the OAuth2 service using an AI-powered agent OAuth 2.0 client.
 * Requests offline access so a refresh token is stored (avoiding hourly sign-in).
 */
function getWorkspaceMcpService_() {
  const props = PropertiesService.getScriptProperties();
  const clientId = props.getProperty("OAUTH_CLIENT_ID");
  const clientSecret = props.getProperty("OAUTH_CLIENT_SECRET");
  if (!clientId || !clientSecret) {
    throw new Error(
      "Set OAUTH_CLIENT_ID and OAUTH_CLIENT_SECRET in Script Properties.",
    );
  }

  return OAuth2.createService("GoogleWorkspaceMCP")
    .setAuthorizationBaseUrl("https://accounts.google.com/o/oauth2/auth")
    .setTokenUrl("https://oauth2.googleapis.com/token")
    .setClientId(clientId)
    .setClientSecret(clientSecret)
    .setCallbackFunction("authCallback")
    .setPropertyStore(PropertiesService.getUserProperties())
    .setCache(CacheService.getUserCache())
    .setLock(LockService.getUserLock(), 30)
    .setScope(
      [
        "https://www.googleapis.com/auth/drive.readonly",
        "https://www.googleapis.com/auth/drive.file",
        "https://www.googleapis.com/auth/spreadsheets.readonly",
        "https://www.googleapis.com/auth/spreadsheets",
      ].join(" "),
    )
    .setParam("access_type", "offline")
    .setParam("prompt", "consent");
}

/**
 * Step A (Run once): Logs the authorization URL and redirect URI.
 * Open the logged URL in your browser and grant consent.
 */
function logAuthUrl() {
  const service = getWorkspaceMcpService_();
  console.log("Redirect URI (register this in Google Cloud Console):");
  console.log(OAuth2.getRedirectUri());

  if (!service.hasAccess()) {
    console.log("Open the following URL in your browser to authorize:");
    console.log(service.getAuthorizationUrl());
  } else {
    console.log("Already authorized! You can run Sample 1 and Sample 2.");
  }
}

/**
 * OAuth2 callback handler invoked automatically after browser consent.
 */
function authCallback(request) {
  const service = getWorkspaceMcpService_();
  const isAuthorized = service.handleCallback(request);
  return HtmlService.createHtmlOutput(
    isAuthorized
      ? "Authorization succeeded! You can close this tab and run your GASADK functions."
      : "Authorization denied. Please check your OAuth client settings and try again.",
  );
}

/**
 * Helper to retrieve a valid OAuth2 access token (auto-refreshes via refresh token).
 */
function getWorkspaceMcpAccessToken_() {
  const service = getWorkspaceMcpService_();
  if (!service.hasAccess()) {
    throw new Error(
      "Not authorized yet. Run logAuthUrl() and open the URL first.",
    );
  }
  return service.getAccessToken();
}

/**
 * Optional utility to clear stored OAuth2 tokens if you change scopes.
 */
function resetWorkspaceMcpAuth() {
  getWorkspaceMcpService_().reset();
  console.log("OAuth2 token cache cleared.");
}
Enter fullscreen mode Exit fullscreen mode

In the Apps Script editor, select logAuthUrl from the function dropdown in the top toolbar and click Run (the play button). If Google shows a standard Apps Script permission prompt the very first time, click Review permissions and allow access. In the Execution log panel at the bottom, confirm that the printed Redirect URI matches what you registered in Step 1, copy the authorization URL, open it in a new browser tab, and click Allow. When the tab displays "Authorization succeeded!", close it—you are ready to run live agents. Whenever you add more scopes later (for example, Gmail or Calendar scopes), run resetWorkspaceMcpAuth followed by logAuthUrl to re-consent.


Understanding /mcp/v1self vs /mcp/v1 and GASADK Dynamic Routing

Before running the samples, two architectural choices in GASADK deserve a brief look (if you are new to scripting, you do not need to change any of these settings—the defaults in the sample code already pick the safest, most cost-effective options for you). Figure 3 summarizes all eight GA Google Workspace MCP endpoints, their OAuth scopes, and GASADK's dynamic model routing matrix.

Google Workspace MCP GA endpoints, scopes, and GASADK dynamic model routing matrix

Figure 3: Reference matrix of all eight GA Google Workspace MCP servers, recommended OAuth scopes, endpoint modes, and GASADK dynamic model routing tiers powered by gemini-decision-1.

Choosing /mcp/v1self vs /mcp/v1

Google Workspace MCP servers protect sensitive operations—such as sending emails, modifying shared events, or accessing shared files—with server-driven human-in-the-loop approvals called MCP form elicitation Ref.

  • /mcp/v1: The primary endpoint for interactive MCP hosts (like Antigravity IDE or Claude) that render interactive form elicitation dialogs when the server requests approval.
  • /mcp/v1self: The non-interactive fallback endpoint designed for hosts that do not render form elicitation UIs—such as headless Google Apps Script executions or time-driven triggers. It exposes tools and results that operate safely on your own resources without blocking on an interactive prompt.

In Apps Script, pass { mode: "v1self", token } to LlmAgent.createWorkspaceMcpServers(). The built-in preset covers drive, gmail, docs, sheets, slides, calendar, and chat in one call. If you also want to connect the eighth GA server—Google Tasks (https://tasksmcp.googleapis.com/mcp/v1self)—simply append a standard mcpServers entry { tasks_mcp: { httpUrl: "https://tasksmcp.googleapis.com/mcp/v1self", headers: { authorization: "Bearer " + token } } } to the returned array.

Dynamic Model & Thinking Routing in GASADK

Hardcoding a single frontier model for every prompt wastes budget and risks hitting Apps Script's 6-minute execution limit. Hardcoding a lightweight model breaks down when a prompt demands multi-step reasoning. GASADK resolves this tension by integrating GeminiDecisionsRouter on top of the Gemini Decisions API (gemini-decision-1) Ref.

  • "efficient" (default): Consults gemini-decision-1 once before the tool loop begins, picking a fast, low-cost model (gemini-3.5-flash-lite, gemini-3.8-flash, or gemini-4-hydrogen) with an appropriate thinkingLevel. If the prompt signals high complexity or includes an explicit escalation phrase, it automatically steps up to frontier models (gemini-4-argon or gemini-4-carbon).
  • "quality": Prioritizes higher accuracy and deeper thinking while enforcing GAS timeout guardrails as remaining execution time narrows.
  • "fixed": Bypasses the Decisions API completely (zero routing calls) and pins your exact model and generateContentConfig.

Every generation call logs its exact selection directly to your logCallback, agent.logs, and agent.getRoutingHistory() in this format:

[ModelRouting] role=agent | mode=efficient | model=models/gemini-3.8-flash | thinking=LOW | reason=tool_use_standard (decisions=184ms)
Enter fullscreen mode Exit fullscreen mode

Routing executes once per request before any tool-calling loop starts—never mid-loop—which preserves implicit prefix caching and keeps multi-turn tool execution snappy.


Hands-On Samples

Now let's put everything to work. Figure 4 traces the execution flow of both samples: a clean read-only Drive query in Sample 1, followed by a four-step hybrid MCP + Native GAS workflow in Sample 2.

Execution flow for Sample 1 and Sample 2 with hybrid MCP and native GAS tools

Figure 4: Step-by-step execution flow for Sample 1 (Drive MCP file listing) and Sample 2 (hybrid Drive MCP, Sheets MCP, and native GAS trash_spreadsheet tool cleanup).

Sample 1: List the 5 Latest Files from Google Drive

Sample 1 connects to the official Google Drive MCP server Ref and asks the agent in plain English to retrieve your five most recently modified files along with their IDs, MIME types, and timestamps. Append this function to Code.gs and run sample1_listLatestDriveFiles.

/**
 * Connects GASADK to the official Google Drive MCP server
 * and lists the 5 most recently modified files in natural language.
 */
function sample1_listLatestDriveFiles() {
  const { LlmAgent } = GASADK;
  const properties = PropertiesService.getScriptProperties();
  const apiKey = properties.getProperty("GEMINI_API_KEY");
  if (!apiKey) throw new Error("Set GEMINI_API_KEY in Script Properties.");

  const token = getWorkspaceMcpAccessToken_();

  // One-line helper to connect to official Google Drive MCP server (/mcp/v1self)
  const mcpServers = LlmAgent.createWorkspaceMcpServers(["drive"], {
    mode: "v1self",
    token,
  });

  const agent = new LlmAgent({
    apiKey,
    name: "DriveAssistant",
    modelRouting: "efficient", // Default: Gemini Decisions API dynamic routing
    instruction: "You are a concise Google Drive assistant.",
    mcpServers,
  }).setServices({
    lock: LockService.getScriptLock(),
    properties,
  });

  const prompt =
    "List the 5 most recently modified files in my Google Drive. " +
    "If list_recent_files returns fewer than 5 files, use pagination or search_files to retrieve 5 files. " +
    "For each file, include its name, file ID, MIME type, and last modified timestamp.";

  const answer = agent.run(prompt, (logEntry) => {
    console.log(`[${logEntry.timestamp}] ${logEntry.message}`);
  });

  console.log("=== Sample 1 Result ===");
  console.log(answer);
}
Enter fullscreen mode Exit fullscreen mode

Watch the Apps Script execution log when it runs. Below is a real execution trace from Sample 1 (normalized to start at 00:00:00 with file names and IDs anonymized):

00:00:00  Notice  Execution started
00:00:01  Info    --- Executing Handshake: initialize (Client --> Server)
00:00:01  Info    --- Confirming Connections: notifications/initialized / notifications/cancelled
00:00:01  Info    --- Extracting Tool Lists (Concurrent Transmission Protocol)
00:00:02  Info    Capabilities mapped: 14 distinct operations loaded.
00:00:02  Info    [00:00:02.225] Agent run sequence initiated
00:00:02  Info    [00:00:02.227] Planning phase initiated.
00:00:02  Info    [00:00:02.888] [ModelRouting] agent=DriveAssistant | role=planner | mode=efficient | model=models/gemini-3.5-flash-lite | thinking=LOW | reason=task_complexity:standard (decisions=655ms)
00:00:03  Info    [00:00:03.993] Execution Plan Generated:
Task [1]: 'mcp_0'
00:00:03  Info    [00:00:03.997] Executing Task [1] via [mcp_0]
00:00:04  Info    Capabilities mapped: 14 distinct operations loaded.
00:00:04  Info    --- start: Call MCP servers or functions (client --> server)
00:00:04  Info    [00:00:04.271] [ModelRouting] role=mcp_orchestrator | mode=efficient | model=models/gemini-3.5-flash-lite | thinking=LOW | reason=task_complexity:standard (decisions=256ms)
00:00:05  Info    Planned Execution Pipeline:
1: [list_recent_files] -> Retrieve the 5 most recently modified files in Google Drive.
00:00:05  Info    --- start: Sequence Execution.
00:00:05  Info    --- Executing function: "list_recent_files" | Objective: "Retrieve the 5 most recently modified files in Google Drive."
00:00:05  Info    [00:00:05.205] [ModelRouting] role=mcp_executor | mode=efficient | model=models/gemini-3.8-flash | thinking=LOW | reason=task_complexity:standard (decisions=201ms)
00:00:07  Info    --- Activating Tool Service: list_recent_files
00:00:14  Info    --- Activating Tool Service: list_recent_files
00:00:24  Info    --- Executing intrinsic handler: without_function | Prompt: Retrieve the 5 most recently modified files in Google Drive.
00:00:24  Info    --- end: Sequence Execution completed.
00:00:24  Info    [00:00:24.837] Task [1] completed successfully in 20838ms.
00:00:24  Info    [00:00:24.842] Execution phase complete. Initiating final synthesis.
00:00:24  Info    [00:00:24.844] [ModelRouting] agent=DriveAssistant | role=synthesizer | mode=efficient | model=models/gemini-3.5-flash-lite | thinking=LOW | reason=task_complexity:standard [cached] (decisions=0ms)
00:00:26  Info    [00:00:26.612] Final synthesis complete.
00:00:26  Info    === Sample 1 Result ===
00:00:26  Info    Here are the 5 most recently modified files in your Google Drive:

1. **Workspace_MCP_Demo**
   - **File ID:** `1aBcDeFgHiJkLmNoPqRsTuVwXyZ00001`
   - **MIME Type:** Google Apps Script (`application/vnd.google-apps.script`)
   - **Last Modified:** 2026-11-27 00:00:00 UTC

2. **Quarterly_Budget_2026**
   - **File ID:** `1aBcDeFgHiJkLmNoPqRsTuVwXyZ00002`
   - **MIME Type:** Google Sheets (`application/vnd.google-apps.spreadsheet`)
   - **Last Modified:** 2026-11-26 23:48:19 UTC

3. **Project_Roadmap_Notes**
   - **File ID:** `1aBcDeFgHiJkLmNoPqRsTuVwXyZ00003`
   - **MIME Type:** Google Docs (`application/vnd.google-apps.document`)
   - **Last Modified:** 2026-11-26 23:42:25 UTC

4. **API_Design_Spec**
   - **File ID:** `1aBcDeFgHiJkLmNoPqRsTuVwXyZ00004`
   - **MIME Type:** Google Docs (`application/vnd.google-apps.document`)
   - **Last Modified:** 2026-11-26 23:31:44 UTC

5. **Team_Meeting_Minutes**
   - **File ID:** `1aBcDeFgHiJkLmNoPqRsTuVwXyZ00005`
   - **MIME Type:** Google Docs (`application/vnd.google-apps.document`)
   - **Last Modified:** 2026-11-26 22:16:55 UTC
00:00:27  Notice  Execution completed
Enter fullscreen mode Exit fullscreen mode

Look closely at what happened inside those 27 seconds. Figure 5 maps the exact message exchanges between Google Apps Script (GASADK), the Gemini API, and the official Google Drive MCP server from 00:00:00 to 00:00:27.

Sample 1 execution trace showing interaction flow between GASADK, Gemini API, and Google Drive MCP server

Figure 5: Live 27-second interaction workflow for Sample 1, tracing the MCP Streamable HTTP handshake, role-aware Gemini model routing, autonomous two-pass pagination against drivemcp.googleapis.com/mcp/v1self, and cached final synthesis.

  • MCP Handshake (00:00:00–00:00:02): GASADK negotiates Streamable HTTP with drivemcp.googleapis.com/mcp/v1self and discovers 14 operations automatically in under 2 seconds.
  • Role-Aware Model Routing (00:00:02–00:00:05): Under modelRouting: "efficient", gemini-decision-1 assigns models/gemini-3.5-flash-lite (LOW) to both the Planner and MCP Orchestrator, then steps up selectively to models/gemini-3.8-flash (LOW) for mcp_executor where structured tool arguments must be generated accurately.
  • Autonomous Pagination (00:00:07 & 00:00:14): When the first list_recent_files call returns fewer than five entries, the executor automatically issues a second paginated list_recent_files call until all five files are collected—zero manual pagination boilerplate.
  • Zero-Latency Decisions Cache Hit (00:00:24): The final Synthesizer reuses the cached routing decision ([cached] (decisions=0ms)) and formats the clean five-file summary in 1.8 seconds.

Sample 2: Create a Sheet, Evaluate GOOGLEFINANCE, Read Cell A1, and Clean Up

Sample 2 showcases a practical pattern that shines uniquely inside Apps Script: Hybrid MCP + Native GAS Tools.

Suppose you want an agent to fetch the live USD/JPY exchange rate by creating a temporary Google Spreadsheet, writing =GOOGLEFINANCE("CURRENCY:USDJPY") into cell A1 via the Sheets MCP server Ref, reading back the evaluated rate, and then deleting the temporary spreadsheet so your Drive stays spotless.

Here is the catch: by design, the official Drive and Sheets MCP servers omit destructive file deletion on /mcp/v1self to protect user data Ref. With GASADK, that safety boundary never blocks your workflow. You simply attach a tiny native GAS tool (trash_spreadsheet): while you could call DriveApp.getFileById(id).setTrashed(true) directly, sending a single Drive API v3 PATCH request ({ trashed: true }) via UrlFetchApp with your existing drive.file OAuth2 token keeps appsscript.json locked to script.external_request without requesting a broad Drive scope. The agent coordinates official Drive MCP, official Sheets MCP, and your custom cleanup tool in one run.

Append this function to Code.gs and run sample2_usdJpyRateWithSheetsAndCleanup:

/**
 * Demonstrates GASADK's Hybrid MCP + Native Tool workflow:
 * 1. Creates a Google Spreadsheet via Drive MCP
 * 2. Inserts =GOOGLEFINANCE("CURRENCY:USDJPY") into cell A1 via Sheets MCP
 * 3. Reads the evaluated value from cell A1 via Sheets MCP
 * 4. Cleans up (trashes) the temporary spreadsheet via a minimal Native GAS Tool
 */
function sample2_usdJpyRateWithSheetsAndCleanup() {
  const { LlmAgent } = GASADK;
  const properties = PropertiesService.getScriptProperties();
  const apiKey = properties.getProperty("GEMINI_API_KEY");
  if (!apiKey) throw new Error("Set GEMINI_API_KEY in Script Properties.");

  const token = getWorkspaceMcpAccessToken_();

  // Connect both Drive MCP and Sheets MCP servers in a single helper call
  const mcpServers = LlmAgent.createWorkspaceMcpServers(["drive", "sheets"], {
    mode: "v1self",
    token,
  });

  // Minimal Native GAS Tool for safe cleanup (Drive MCP intentionally omits file deletion)
  const trashSpreadsheetTool = {
    name: "trash_spreadsheet",
    description:
      "Moves a temporary Google Spreadsheet created during this session to the trash using its file ID.",
    parameters: {
      type: "object",
      properties: {
        fileId: {
          type: "string",
          description:
            "The Google Drive file ID (spreadsheetId) to move to trash.",
        },
      },
      required: ["fileId"],
    },
    function: (args) => {
      if (!args?.fileId || typeof args.fileId !== "string") {
        throw new Error("A valid string 'fileId' is required.");
      }
      const url = `https://www.googleapis.com/drive/v3/files/${encodeURIComponent(args.fileId)}`;
      const res = UrlFetchApp.fetch(url, {
        method: "patch",
        contentType: "application/json",
        headers: { Authorization: `Bearer ${token}` },
        payload: JSON.stringify({ trashed: true }),
        muteHttpExceptions: true,
      });
      const code = res.getResponseCode();
      if (code >= 200 && code < 300) {
        return `Successfully moved spreadsheet (${args.fileId}) to trash.`;
      }
      throw new Error(
        `Failed to trash file (${code}): ${res.getContentText()}`,
      );
    },
  };

  const agent = new LlmAgent({
    apiKey,
    name: "SheetsFinanceAssistant",
    modelRouting: "efficient",
    instruction:
      "You are a Google Workspace automation agent. Execute all requested steps in strict order. " +
      "If cell A1 temporarily shows #LOADING... or is blank after inserting a GOOGLEFINANCE formula, read cell A1 once more.",
    mcpServers,
    tools: [trashSpreadsheetTool],
  }).setServices({
    lock: LockService.getScriptLock(),
    properties,
  });

  const prompt =
    "Follow these 4 steps strictly in order:\n" +
    "1. Create a new Google Spreadsheet named 'Temp_USDJPY_Rate' (mimeType: 'application/vnd.google-apps.spreadsheet') using the Drive MCP server.\n" +
    "2. Insert the formula '=GOOGLEFINANCE(\"CURRENCY:USDJPY\")' into cell A1 of its first sheet using the Sheets MCP server (use formula/update_formulas mode, not plain text).\n" +
    "3. Read the evaluated value from cell A1 of that sheet using the Sheets MCP server.\n" +
    "4. Delete (trash) the temporary spreadsheet using the 'trash_spreadsheet' tool with its file ID.\n" +
    "Finally, report the retrieved USD/JPY exchange rate and confirm that the temporary spreadsheet was trashed.";

  const answer = agent.run(prompt, (logEntry) => {
    console.log(`[${logEntry.timestamp}] ${logEntry.message}`);
  });

  console.log("=== Sample 2 Result ===");
  console.log(answer);
}
Enter fullscreen mode Exit fullscreen mode

Notice how the drive.file scope works in your favor here: it grants write access only to files created or opened by your app, keeping the blast radius of trash_spreadsheet strictly bounded to temporary files created in the session.

Below is the live execution log from Sample 2 (normalized to 00:00:00 start with the temporary spreadsheet ID anonymized):

00:00:00  Notice  Execution started
00:00:02  Info    --- Executing Handshake: initialize (Client --> Server)
00:00:02  Info    --- Confirming Connections: notifications/initialized / notifications/cancelled
00:00:02  Info    --- Extracting Tool Lists (Concurrent Transmission Protocol)
00:00:02  Info    Capabilities mapped: 20 distinct operations loaded.
00:00:02  Info    [00:00:02.816] Agent run sequence initiated
00:00:02  Info    [00:00:02.821] Planning phase initiated.
00:00:03  Info    [00:00:03.082] [ModelRouting] agent=SheetsFinanceAssistant | role=planner | mode=efficient | model=models/gemini-4-hydrogen | thinking=LOW | reason=task_complexity:complex (decisions=245ms)
00:00:07  Info    [00:00:07.669] Execution Plan Generated:
Task [1]: 'mcp_0'
Task [2]: 'mcp_1'
Task [3]: 'tool_trash_spreadsheet'
00:00:07  Info    [00:00:07.671] Executing Task [1] via [mcp_0]
00:00:07  Info    [00:00:07.896] [ModelRouting] role=mcp_orchestrator | mode=efficient | model=models/gemini-3.5-flash-lite | thinking=LOW | reason=task_complexity:standard (decisions=215ms)
00:00:08  Info    Planned Execution Pipeline:
1: [create_file] -> Create a new Google Spreadsheet named 'Temp_USDJPY_Rate'.
00:00:08  Info    [00:00:08.924] [ModelRouting] role=mcp_executor | mode=efficient | model=models/gemini-3.8-flash | thinking=LOW | reason=task_complexity:standard (decisions=258ms)
00:00:14  Info    --- Activating Tool Service: create_file
00:00:18  Info    [00:00:18.713] Task [1] completed successfully in 11040ms.
00:00:18  Info    [00:00:18.715] Executing Task [2] via [mcp_1]
00:00:19  Info    [00:00:19.030] [ModelRouting] role=mcp_orchestrator | mode=efficient | model=models/gemini-3.5-flash-lite | thinking=LOW | reason=task_complexity:standard (decisions=297ms)
00:00:20  Info    Planned Execution Pipeline:
1: [update_formulas] -> Insert the formula '=GOOGLEFINANCE("CURRENCY:USDJPY")' into cell A1 of the first sheet in spreadsheet 1TempUsdJpySpreadsheetId00000001.
2: [get_values] -> Read the value from cell A1 of the first sheet in spreadsheet 1TempUsdJpySpreadsheetId00000001.
3: [check_process] -> Check if cell A1 shows #LOADING... or is blank, and determine if another read is needed.
4: [get_values] -> Read cell A1 once more if the previous read returned #LOADING... or was blank.
5: [without_function] -> Provide the final conversational response with the evaluated USDJPY rate from cell A1.
00:00:21  Info    [00:00:21.182] [ModelRouting] role=mcp_executor | mode=efficient | model=models/gemini-3.8-flash | thinking=LOW | reason=task_complexity:standard (decisions=228ms)
00:00:24  Info    --- Activating Tool Service: update_formulas
00:00:30  Info    [00:00:30.001] [ModelRouting] role=mcp_executor | mode=efficient | model=models/gemini-3.8-flash | thinking=LOW | reason=task_complexity:standard (decisions=275ms)
00:00:33  Info    --- Activating Tool Service: get_values
00:00:36  Info    [00:00:36.175] [ModelRouting] role=mcp_executor | mode=efficient | model=models/gemini-3.8-flash | thinking=LOW | reason=task_complexity:standard (decisions=212ms)
00:00:44  Info    --- Check Process Triggered | Task: Check if cell A1 shows #LOADING... or is blank, and determine if another read is needed. | Halting: false | Reason: Cell A1 contains the valid value '159.2425' (it is neither '#LOADING...' nor blank). Another read is not needed, so processing can proceed to the next operation.
00:00:46  Info    [00:00:46.732] [ModelRouting] role=mcp_executor | mode=efficient | model=models/gemini-3.5-flash-lite | thinking=LOW | reason=task_complexity:trivial (decisions=286ms)
00:00:47  Info    --- Executing intrinsic handler: without_function | Prompt: Read cell A1 once more if the previous read returned #LOADING... or was blank.
00:00:49  Info    [00:00:49.694] [ModelRouting] role=mcp_summarizer | mode=efficient | model=models/gemini-3.5-flash-lite | thinking=LOW | reason=task_complexity:standard [cached] (decisions=0ms)
00:00:50  Info    [00:00:50.329] Task [2] completed successfully in 31612ms.
00:00:50  Info    [00:00:50.331] Executing Task [3] via [tool_trash_spreadsheet]
00:00:50  Info    [00:00:50.562] [ModelRouting] agent=SheetsFinanceAssistant | role=executor | mode=efficient | model=models/gemini-3.8-flash | thinking=LOW | reason=task_complexity:standard (decisions=227ms)
00:00:54  Info    [00:00:54.987] Task [3] completed successfully in 4655ms.
00:00:54  Info    [00:00:54.990] [ModelRouting] agent=SheetsFinanceAssistant | role=synthesizer | mode=efficient | model=models/gemini-4-hydrogen | thinking=MEDIUM | reason=task_complexity:complex [cached] (decisions=0ms)
00:01:00  Info    [00:01:00.010] Final synthesis complete.
00:01:00  Info    === Sample 2 Result ===
00:01:00  Info    All four steps have been completed successfully:

1. **Spreadsheet Created:** A temporary Google Spreadsheet named **Temp_USDJPY_Rate** (File ID: `1TempUsdJpySpreadsheetId00000001`) was created.
2. **Formula Inserted & Evaluated:** The formula `=GOOGLEFINANCE("CURRENCY:USDJPY")` was inserted into cell `A1` of the first sheet, and the evaluated value was retrieved.
3. **USD/JPY Exchange Rate:** **159.2425**
4. **Cleanup Confirmed:** The temporary spreadsheet (`1TempUsdJpySpreadsheetId00000001`) has been moved to the trash.
00:01:00  Notice  Execution completed
Enter fullscreen mode Exit fullscreen mode

Look closely at what happened inside those 60 seconds. Figure 6 traces the complete interaction flow across Google Apps Script (GASADK), the Gemini API, both Google Workspace MCP servers (Drive and Sheets), and the native Drive API v3 cleanup call from 00:00:00 to 00:01:00.

Sample 2 execution trace showing hybrid interaction flow across GASADK, Gemini API, Drive and Sheets MCP servers, and native cleanup

Figure 6: Live 60-second hybrid interaction workflow for Sample 2, tracing the dual MCP handshake, automatic complexity escalation to gemini-4-hydrogen, cross-server spreadsheet ID propagation, check_process formula validation (159.2425), native trash_spreadsheet cleanup, and cached final synthesis.

  • Automatic Complexity Escalation (00:00:03): Unlike Sample 1's single-server query, gemini-decision-1 classifies Sample 2 as task_complexity:complex and automatically escalates the Planner to models/gemini-4-hydrogen (LOW), producing a clean 3-task DAG across mcp_0 (Drive), mcp_1 (Sheets), and tool_trash_spreadsheet (Native GAS).
  • Cross-Server Context Propagation (00:00:18–00:00:20): The spreadsheet ID returned by Drive MCP's create_file is automatically injected into Sheets MCP's update_formulas and get_values calls without any glue code.
  • Self-Checking Formula Evaluation (00:00:44–00:00:47): After get_values retrieves 159.2425, the built-in check_process gate verifies that cell A1 is neither #LOADING... nor blank. Because the value is already valid, the agent skips the redundant second get_values call via without_function on gemini-3.5-flash-lite—saving both latency and quota.
  • Deterministic Cleanup & Cached Synthesis (00:00:50–00:01:00): Task 3 executes the native trash_spreadsheet tool in 4.7 seconds, and the final Synthesizer runs on models/gemini-4-hydrogen (MEDIUM) with [cached] (decisions=0ms), finishing well inside Google Apps Script's 6-minute execution limit.

Troubleshooting & Security Best Practices

Running AI agents against live Google Workspace data demands clean operational guardrails. Keep these five points handy as you build out your own workflows:

  • invalid token errors on MCP calls: This almost always means either ScriptApp.getOAuthToken() was passed by mistake, or your Web application OAuth 2.0 client in Google Cloud Console does not have Use this client for an AI-powered agent checked Ref. Verify the client setting, run resetWorkspaceMcpAuth(), and re-authorize via logAuthUrl().
  • HTTP 403 or "API is not enabled" on Sheets/Drive MCP: If you reused an existing Google Cloud project instead of Personal mode onboarding, make sure both the standard product API (sheets.googleapis.com, drive.googleapis.com) and its companion MCP service (sheetsmcp.googleapis.com, drivemcp.googleapis.com) are enabled in that project Ref.
  • Repeated hourly sign-in prompts: Web application OAuth clients default to online tokens that expire after 60 minutes. Ensure both .setParam("access_type", "offline") and .setParam("prompt", "consent") remain set in getWorkspaceMcpService_(). If you previously authorized the client without offline access, run resetWorkspaceMcpAuth() or revoke the app in your Google Account connections before authorizing again.
  • #LOADING... when reading GOOGLEFINANCE cells: Live finance formulas evaluate asynchronously on Google's servers right after insertion. As shown in Sample 2's instruction, explicitly instructing the agent to re-read cell A1 once if it observes #LOADING... or an empty value handles the brief evaluation lag cleanly without manual Utilities.sleep() hacks.
  • Defending against indirect prompt injection: Untrusted emails, shared documents, or third-party spreadsheets can hide adversarial instructions aimed at hijacking your agent's tool calls Ref. Follow the principle of least privilege: request only the narrowest OAuth scopes your workflow requires (such as drive.readonly and drive.file rather than full drive), avoid feeding untrusted external content into write-capable agents without screening, and keep destructive actions isolated behind explicit, narrowly scoped native tools.

Summary

With Google Workspace MCP servers now open to both company Workspace accounts and personal Gmail accounts Ref, you no longer need deep programming skills to automate Google Drive, Sheets, Gmail, or Calendar. By combining Google Apps Script with GASADK Ref, you can ask an AI assistant to handle everyday Google Workspace tasks in plain language—right inside your browser, with nothing to install and no server to rent.

If you remember just four simple points from this guide, you are ready to go:

  • Set up the AI login once, then forget it: Following Steps 1 to 4 gives your script its own AI-ready login key. After approving it once in your browser, your script keeps working automatically without asking you to sign in again every hour.
  • Just describe what you want in plain words: As you saw in Sample 1, asking for your five latest Drive files is enough—the AI finds the right tool, fetches the list (even across multiple pages), and finishes in under 30 seconds.
  • Speed and cost are handled for you: You do not have to guess which AI model to pick. GASADK automatically uses a fast, low-cost model for simple lookups and switches to a stronger model only when a task has multiple steps.
  • Multi-step chores run end to end, including cleanup: As Sample 2 showed, a single run can create a temporary Google Sheet, fetch a live exchange rate with GOOGLEFINANCE, read the answer, and move the temporary file to the trash automatically—all in about a minute.

If this is your first time trying Google Apps Script, start by walking through Steps 1 to 4 and running Sample 1 once. Watching your own Google Drive files appear in the log from a plain-English request is the fastest way to see how effortless it feels. Once that works, you can easily add Gmail, Calendar, Docs, or Tasks to the same script and let a daily schedule take care of morning summaries, draft replies, or routine spreadsheet checks for you.

Top comments (0)