Ga naar hoofdinhoud

A Developer's Guide to Google Workspace MCP Servers and the Agent Development Kit

Learn how to build an enterprise AI assistant in Python using Google Workspace MCP Servers and the Agent Development Kit to connect LLMs to your live data.
16 jul 2026  · 10 min lezen

AI agents are incredibly powerful, but they often suffer from a fundamental flaw: they are disconnected from where our actual daily work happens, our emails, our calendars, and our documents. Without access to your live data, an LLM is just a highly articulate brainstormer.

In this tutorial, I will show you how to bridge the gap between AI models and your enterprise data by configuring the Google Workspace MCP Server, understanding the latest security controls, and building an automated assistant.

By the end, you will be able to: 

  • Understand the architecture of the Model Context Protocol (MCP) as it applies to Google Workspace.
  • Configure the necessary OAuth controls and API access in Google Cloud.
  • Test connectivity using the Gemini CLI and Google Antigravity.
  • Build an Enterprise AI Assistant in Python using the Google ADK that can read emails, check your calendar, and draft documents in a single reasoning loop.

Prerequisites

  • A Google Cloud Project with billing enabled.
  • Basic knowledge of Python and REST APIs.
  • A Google Workspace account.

What is the Google Workspace MCP Server?

The Google Workspace MCP Server is a standardized implementation of the Model Context Protocol (MCP) that allows any compatible AI client (like Claude Desktop, Gemini CLI, or custom agents) to interact securely with Google Workspace apps.

Instead of developers writing custom REST API wrappers for Gmail, Google Docs, Drive, and Calendar for every new AI project, the MCP server exposes these capabilities as standardized "tools" that the LLM natively understands.

I recommend checking out the Introduction to Model Context Protocol (MCP) course to get some hands-on experience with it. 

Normally, building a cross-app workflow means writing brittle integration code. With MCP, you just hand the tools to the LLM. The agent can read an email thread, spot a scheduling conflict by checking your calendar, and draft a summary in Google Docs all on its own.

Security and Workspace Admin Controls

When giving AI models access to corporate emails and files, enterprise data security is the biggest hurdle for AI adoption. 

The Workspace MCP Server was built from the ground up to address this concern.

It handles authentication by relying entirely on OAuth 2.0 and strict Google Cloud IAM. 

There are no generic "master keys." The agent only ever acts on behalf of the explicitly authenticated user, strictly respecting all existing Google Workspace sharing permissions and document ACLs.

Furthermore, it introduces robust Admin controls. 

Workspace Administrators can allowlist specific MCP tools, monitor API usage across the organization, and enforce Data Loss Prevention (DLP) rules to ensure agents don't accidentally leak sensitive Drive documents or emails to unauthorized external domains.

Configuring Access to the Workspace MCP Server

Before writing code, "configuration" here means setting up Google Cloud permissions to access the remote server.

Setting up the Google Cloud project

First, you must enable both the standard Workspace APIs and the dedicated MCP services in your Google Cloud Project.

  1. Navigate to the Google Cloud Console.
  2. Enable the required Workspace APIs: Gmail API, Google Drive API, Google Docs API, and Google Calendar API.
  3. Enable the MCP services: gmailmcp.googleapis.com, drivemcp.googleapis.com, and calendarmcp.googleapis.com.
  4. Go to APIs & Services > OAuth consent screen. Set up your consent screen for an Internal audience. Under Data Access > Add or Remove Scopes, manually add the following scopes for the servers you plan to use:
    • Google Calendar: https://www.googleapis.com/auth/calendar.calendarlist.readonly, https://www.googleapis.com/auth/calendar.events.freebusy, https://www.googleapis.com/auth/calendar.events.readonly
    • Google Chat: https://www.googleapis.com/auth/chat.spaces.readonly, https://www.googleapis.com/auth/chat.memberships.readonly, https://www.googleapis.com/auth/chat.messages.readonly, https://www.googleapis.com/auth/chat.users.readstate.readonly
    • Google Drive: https://www.googleapis.com/auth/drive.readonly, https://www.googleapis.com/auth/drive.file
    • Gmail: https://www.googleapis.com/auth/gmail.readonly, https://www.googleapis.com/auth/gmail.compose
    • People API: https://www.googleapis.com/auth/directory.readonly, https://www.googleapis.com/auth/userinfo.profile, https://www.googleapis.com/auth/contacts.readonly

Generating user credentials

Because Workspace data is user-specific, the remote MCP endpoint requires an Authorization: Bearer <TOKEN> header representing the human user. 

Go to APIs & Services > Credentials and create an OAuth 2.0 Client ID (Desktop Application type). 

Download the JSON credentials file. This will be used to acquire the necessary OAuth 2.0 access token via a browser login flow. 

Click Create and copy the Client ID and Client Secret. You will need these in the next step.

Testing the Connection (Gemini CLI and Antigravity)

Before writing any complex Python agent code, it is highly recommended to perform a "Hello World" test to verify your credentials and ensure the remote MCP endpoints are reachable. 

Testing the connection in a simplified environment helps isolate authentication issues from your application logic. 

While we can test the connection using both the Gemini CLI and the Google Antigravity UI, we will focus on the Gemini CLI for now.

Connecting via Gemini CLI

The fastest way to test connectivity is using the Gemini CLI. 

Because Workspace requires strict authentication, you configure the endpoint and your OAuth credentials in your ~/.gemini/settings.json file:

{
  "mcpServers": {
    "calendar": {
      "httpUrl": "https://calendarmcp.googleapis.com/mcp/v1",
      "oauth": {
        "enabled": true,
        "clientId": "<YOUR_CLIENT_ID>",
        "clientSecret": "<YOUR_CLIENT_SECRET>",
        "scopes": [
          "https://www.googleapis.com/auth/calendar.calendarlist.readonly",
          "https://www.googleapis.com/auth/calendar.events.freebusy",
          "https://www.googleapis.com/auth/calendar.events.readonly"
        ]
      }
    },
    "drive": {
      "httpUrl": "https://drivemcp.googleapis.com/mcp/v1",
      "oauth": {
        "enabled": true,
        "clientId": "<YOUR_CLIENT_ID>",
        "clientSecret": "<YOUR_CLIENT_SECRET>",
        "scopes": [
          "https://www.googleapis.com/auth/drive.readonly",
          "https://www.googleapis.com/auth/drive.file"
        ]
      }
    },
    "gmail": {
      "httpUrl": "https://gmailmcp.googleapis.com/mcp/v1",
      "oauth": {
        "enabled": true,
        "clientId": "<YOUR_CLIENT_ID>",
        "clientSecret": "<YOUR_CLIENT_SECRET>",
        "scopes": [
          "https://www.googleapis.com/auth/gmail.readonly",
          "https://www.googleapis.com/auth/gmail.compose"
        ]
      }
    }
  }
}

Once your settings file is updated, you can launch the Gemini CLI and run the /mcp list command. 

You will see your newly configured Workspace servers listed as "Ready" but showing "(OAuth not authenticated)". 

This confirms the CLI has successfully read your configuration and is aware of the remote tools. 

Running basic Workspace tests

Now that the servers are recognized, you must authenticate before you can use them. Start by running the authentication command for your Gmail endpoint:

/mcp auth gmail

This will initiate a browser-based OAuth 2.0 flow. 

The CLI will attempt to automatically open your default web browser, prompting you to log in with your Google Workspace account and grant the requested permissions. 

If your browser does not open automatically, the CLI will provide a secure URL that you can manually copy and paste. Once you complete the sign-in process, the CLI will confirm successful authentication and reload the tools for that server.

With authentication complete, you can now test the connection with a natural language prompt:

my email for any messages containing the word 'Invoice'.

The CLI will execute the tool behind the scenes, retrieve the data from your inbox, and the agent will format it into a helpful response:

Demo Project: Building a Workspace Agent With Google ADK

Let's build a Workspace Agent that connects to all five services (Calendar, Chat, Drive, Gmail, People) and handles authentication safely.

Generating Application Default Credentials (auth.py)

Before the agent can run, it needs an OAuth token to pass to the MCP endpoints. 

The Gemini CLI handles this automatically with /mcp auth, but for a Python application, we need to generate our own token and save it as Application Default Credentials (ADC).

Create a file named auth.py in your project root. Ensure you have your downloaded client_secret.json in the same directory. 

This script uses the official google-auth-oauthlib to generate an authentication URL, exchange the code for a refresh token, and write it to the standard ~/.config/gcloud/application_default_credentials.json path, where the ADK can find it.

import json
import os
from urllib.parse import urlparse, parse_qs
import google.auth
from google_auth_oauthlib.flow import InstalledAppFlow
CLIENT_SECRET_FILE = 'client_secret.json'
SCOPES = [
   "https://www.googleapis.com/auth/cloud-platform",
   "https://www.googleapis.com/auth/calendar",
   "https://www.googleapis.com/auth/chat.spaces.readonly",
   "https://www.googleapis.com/auth/chat.messages",
   "https://www.googleapis.com/auth/drive.readonly",
   "https://www.googleapis.com/auth/gmail.readonly",
   "https://www.googleapis.com/auth/gmail.compose",
   "https://www.googleapis.com/auth/directory.readonly",
   "https://www.googleapis.com/auth/contacts.readonly"
]
# Initialize the flow
flow = InstalledAppFlow.from_client_secrets_file(
   CLIENT_SECRET_FILE,
   scopes=SCOPES,
   redirect_uri='http://localhost:8085/'
)
# Generate Auth URL
auth_url, expected_state = flow.authorization_url(prompt='consent', access_type='offline')
print("Copy this link and paste it into your browser:\\n", auth_url)
redirected_url = input("\\nPaste the full localhost URL here: ").strip()
# Exchange code for tokens
parsed_url = urlparse(redirected_url)
code = parse_qs(parsed_url.query).get('code', [None])[0]
flow.fetch_token(code=code)
# Save ADC
adc_data = {
   "client_id": flow.credentials.client_id,
   "client_secret": flow.credentials.client_secret,
   "refresh_token": flow.credentials.refresh_token,
   "type": "authorized_user"
}
adc_path = os.path.expanduser("~/.config/gcloud/application_default_credentials.json")
os.makedirs(os.path.dirname(adc_path), exist_ok=True)
with open(adc_path, "w") as f:
   json.dump(adc_data, f, indent=2)
print(f"Success! ADC saved to: {adc_path}")

Run the script in your terminal: python3 auth.py

When you execute this, you will need to complete a manual authentication flow:

  1. The script will print a long Google OAuth URL starting with https://accounts.google.com/o/oauth2/auth?...
  2. Copy this entire URL from your terminal and paste it into your web browser.
  3. Select your Google Workspace account and click Allow to authorize the application.
  4. Your browser will then redirect you to a localhost page. Note: It is completely normal and expected if your browser shows a "Site can't be reached" error for this page.
  5. Copy the entire URL from your browser's address bar (it will start with http://localhost:8085/?state=...&code=...).
  6. Paste that full URL back into your terminal prompt where it says Paste the full localhost URL here: and press Enter.

The script will exchange the code for an OAuth token, save it to ~/.config/gcloud/application_default_credentials.json, and generate a .env file in your workspace_agent directory containing your Google Cloud Project settings. 

Your local environment is now fully authenticated!

Building the Agent (agent.py)

Now, create a file named agent.py. 

Because Workspace data is highly sensitive, the MCP servers require the access token we just generated to be injected into the HTTP headers for every request. 

We also need to configure the ADK environment securely.

Let's break down the code:

1. Environment and Token Caching (TokenRelay)

First, we load the user's Application Default Credentials (ADC) generated in the previous step. 

A critical part of enterprise agents is caching tokens efficiently. If we refresh the token on every single tool execution, we could hit API limits or trigger infinite refresh loops during retries. 

The TokenRelay class caches the token in-memory and only refreshes it when it's within 5 minutes of expiring.

import os
import datetime
import google.auth
from google.auth.transport.requests import Request
from google.adk.agents.llm_agent import LlmAgent
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset
from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams
# Enable graceful error handling so timeouts return as tool outputs
os.environ["ADK_ENABLE_MCP_GRACEFUL_ERROR_HANDLING"] = "1"
# Inject User ADC path globally
_adc_path = os.path.expanduser("~/.config/gcloud/application_default_credentials.json")
if not os.path.exists(_adc_path):
   raise FileNotFoundError("Please run 'python3 auth.py' first to generate credentials.")
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = _adc_path
creds, _ = google.auth.default()
class TokenRelay:
   """Manages in-memory caching of Google OAuth access tokens."""
   def __init__(self, credentials):
       self._creds = credentials
       self._cached_token = None
       self._expiry = None
   def get_token(self) -> str:
       now = datetime.datetime.now()
       if (self._cached_token is None or self._expiry is None
           or now >= (self._expiry - datetime.timedelta(minutes=5))):
           self._creds.refresh(Request())
           self._cached_token = self._creds.token
           self._expiry = now + datetime.timedelta(minutes=50)
       return self._cached_token or ""
token_relay = TokenRelay(creds)
token_relay.get_token()
def auth_header_provider(tool_context=None) -> dict[str, str]:
   return {"Authorization": f"Bearer {token_relay.get_token()}"}

2. Configuring the MCP Toolsets

With our token cache ready, we configure our 5 MCP connections. We use StreamableHTTPConnectionParams to connect to Server-Sent Events (SSE) endpoints.

What makes the McpToolset so powerful is that it dynamically interrogates the remote endpoint. It automatically fetches the available tools and JSON schemas. You don't have to hardcode any of them!

# Initialize the 5 GWS MCP servers with dynamic runtime provider
calendar_mcp = McpToolset(
   connection_params=StreamableHTTPConnectionParams(url="https://calendarmcp.googleapis.com/mcp/v1"),
   header_provider=auth_header_provider
)
chat_mcp = McpToolset(
   connection_params=StreamableHTTPConnectionParams(url="https://chatmcp.googleapis.com/mcp/v1"),
   header_provider=auth_header_provider
)
drive_mcp = McpToolset(
   connection_params=StreamableHTTPConnectionParams(url="https://drivemcp.googleapis.com/mcp/v1"),
   header_provider=auth_header_provider
)
gmail_mcp = McpToolset(
   connection_params=StreamableHTTPConnectionParams(url="https://gmailmcp.googleapis.com/mcp/v1"),
   header_provider=auth_header_provider
)
people_mcp = McpToolset(
   connection_params=StreamableHTTPConnectionParams(url="https://people.googleapis.com/mcp/v1"),
   header_provider=auth_header_provider
)

3. Initializing the Agent

Finally, we instantiate our LlmAgent. We use the gemini-2.5-flash model, dynamically inject the current date into the system prompt so the LLM understands relative time ("this week", "today"), and pass it the 5 toolsets.

current_date = datetime.datetime.now().strftime("%Y-%m-%d")
root_agent = LlmAgent(
   model="gemini-2.5-flash",
   name='gws_adk_agent',
   instruction=f"""You are a helpful assistant grounded in the user's Google Workspace data.
   Today's current date is {current_date}. Always calculate relative dates (like 'this week' or 'upcoming meetings') using this reference.
   Use the provided MCP tools to answer questions about their Calendar, Chat, Drive, Gmail, and Contacts.
   If a tool returns an error indicating a timeout, inform the user that the service took too long to respond.""",
   tools=[calendar_mcp, chat_mcp, drive_mcp, gmail_mcp, people_mcp]
)

Executing with ADK Web

Instead of writing a custom Python loop, we can test and run this agent immediately using the built-in ADK Web interface. From your terminal, launch the web server: 

adk web 

This starts a local development server. Navigate to http://localhost:8080 in your browser. 

You will see your agent loaded and ready. 

From this UI, you can chat with the agent natively and observe it seamlessly jumping between Gmail, Calendar, and Drive to fulfill your requests!

adk-web-interface

Testing the Agent in the real world

Now that the agent is running, try asking it complex, cross-functional questions that would normally require you to open three different tabs. 

For example:

Prompt 1: Check my calendar for tomorrow and summarize the topics of my meetings. Are there any relevant documents in my Drive for them?

agent-response

What's happening under the hood:

  1. The agent understands it first needs calendar data, so it executes the list_events tool, dynamically calculating tomorrow's date based on the system prompt.
  2. It parses the JSON response to find the meeting titles.
  3. Recognizing it needs related documents, it extracts keywords from those meeting titles and seamlessly passes them into a second tool call: search_files.
  4. Finally, it synthesizes the outputs from both the Calendar and Drive MCP servers into a single, highly readable briefing.

Instead of writing custom API wrappers and integration logic, you just asked a question, and the LLM figured out the multi-step orchestration.

Prompt 2: Find all emails sent by [Insert Email]  in the last 7 days.

tool-execution

What's happening under the hood:

  1. The agent takes your natural language request and automatically translates it into the exact query syntax required by the Gmail API.
  2. It calls the search_threads tool, passing in the dynamically generated query string.
  3. It retrieves the recent threads, extracts the relevant metadata, and presents the subjects and dates back to you neatly formatted.

Other Prompts to Try

The possibilities are endless when you have all your enterprise data connected to a reasoning engine. 

Try some of these other prompts in your local environment:

  • "Find the last email I received from my manager. Did they ask me to do anything?"
  • "Find the project kickoff slide deck in my Drive, read the contents, and tell me what the Q3 goals are."
  • "Are there any scheduling conflicts on my calendar for next week?"

What's Next? Unlocking Enterprise Automation

By combining Google's Agent Development Kit with the standardized Workspace MCP servers, you've just built an enterprise-grade assistant in less than a hundred lines of code. 

But this is just the beginning.

Here is what this architecture opens up for developers and businesses:

  1. Multi-agent systems: Instead of one massive agent, you could use ADK to build a fleet of specialized sub-agents. One agent specifically manages your calendar and resolves scheduling conflicts, while another strictly monitors a shared team inbox and categorizes incoming requests.
  1. Custom enterprise tools: Because MCP is a standard, you aren't limited to just Workspace. You can easily add additional MCP tools to your agent—like a Postgres MCP server to query your company's sales database, or a Jira MCP server to automatically create tickets based on Chat messages.
  1. Automated workflows: You can take this agent out of the ADK Web UI and deploy it headlessly. Imagine a scheduled CRON job that wakes up your agent every morning at 8 AM, analyzes your inbox and calendar, and sends you a summarized briefing via Google Chat.

Conclusion

The Google Workspace MCP Server eliminates the "glue code" required to connect AI to enterprise productivity apps. By providing a secure, fully managed remote endpoint, it empowers developers to build deeply integrated agentic workflows that respect user permissions and enterprise security standards out of the box.

Best Practice Reminder: Always use the principle of least privilege. 

When assigning OAuth scopes to your AI agents, never grant write access (e.g., https://www.googleapis.com/auth/drive.file) if the agent only needs to read data.

Ready to Build?

Continue your learning journey with our guided DataCamp courses:


Aryan Irani's photo
Author
Aryan Irani
Twitter

I write and create on the internet. Google Developer Expert for Google Workspace, Computer Science graduate from NMIMS, and passionate builder in the automation and Generative AI space.

Onderwerpen

Top DataCamp Courses

Cursus

Praktische AI met Google Gemini en NotebookLM

2 Hr
7.8K
Leer Gemini en NotebookLM kennen om dingen automatisch te doen, productiever te werken en slimmer te werken in het AI-ecosysteem van Google.
Bekijk detailsRight Arrow
Begin met de cursus
Meer zienRight Arrow
Gerelateerd

blog

Top 10 MCP Servers & Clients for AI Workflow Automation in 2026

Discover the most popular MCP servers and clients to automate your workflow using natural language.
Abid Ali Awan's photo

Abid Ali Awan

6 min

Tutorial

Google MCP Servers Tutorial: Deploying Agentic AI on GCP

Explore the architecture of Google’s managed MCP servers and learn how to turn LLMs into proactive operators for BigQuery, Maps, GCE, and Kubernetes.
Aryan Irani's photo

Aryan Irani

Tutorial

Google ADK Tutorial: Building an MCP Server Logistics Agent

Learn how to build a smart logistics agent using Google ADK and MCP servers. Connect BigQuery and Google Maps to automate workflows without custom API code.
Aryan Irani's photo

Aryan Irani

Tutorial

Google Workspace Studio Tutorial: Build an AI Agent Using Natural Language

Learn how Google Workspace Studio lets you create AI agents to automate workflows in Gmail, Drive, and Sheets with an easy, hands-on beginner tutorial.
Aryan Irani's photo

Aryan Irani

Tutorial

Codex CLI MCP Tutorial: Building a Portfolio Dashboard Agent

Break your AI coding agent out of its sandbox. Discover how to use Codex CLI and MCP to connect LLMs to live data, external tools, and multi-agent workflows.
Nikhil Adithyan's photo

Nikhil Adithyan

Tutorial

Microsoft Copilot Studio: A Guide to Building Enterprise AI Agents

Learn how to build and deploy powerful AI agents in Microsoft Copilot Studio. Answer questions using RAG, SharePoint integration, LLM reasoning, and tool calls.
Josep Ferrer's photo

Josep Ferrer

Meer zienMeer zien