AI Tools8 min read

Gmail and Drive APIs for AI Agents: Scopes, Code, MCP

How an AI agent reads and sends Gmail and reads and writes Drive files: OAuth scopes, Python code from Google's docs, push notifications, quotas and MCP.

By AI Agents DirectoryLast checked
Green characters of computer code on a dark screen

An AI agent that works with Gmail and Google Drive does it through the same public APIs any other app uses: the Gmail API and the Drive API, authorised with OAuth 2.0. What has changed in 2026 is the agent-specific layer on top. Google now runs remote MCP servers for Workspace products, has an OAuth client setting for AI agents, and introduced new usage quotas for projects created from May 1, 2026. This guide covers the scopes to request, working Python code taken from Google’s own samples, how to react to new mail and file changes, and the official MCP route. Everything here is checked against developers.google.com and the Google Workspace Updates blog.

Two ways to connect an agent

Gmail API + Drive API directlyGoogle Workspace MCP servers
What you buildYour own tools that call REST endpoints or the Python clientPoint an MCP client at Google-hosted servers
Endpointsgmail.googleapis.com, www.googleapis.com/drive/v3gmailmcp.googleapis.com/mcp/v1, drivemcp.googleapis.com/mcp/v1
AuthOAuth 2.0, scopes you chooseOAuth 2.0; Google lists the scopes to add
StatusGenerally availableDeveloper preview
Best forCustom agents, background jobs, full controlAssistants such as Claude or Google Antigravity acting for one user

If you are writing your own agent framework or need behaviour the MCP tools do not expose, use the APIs. If you want an existing assistant to search mail and read files quickly, the MCP servers are less work. For other options, see our developer tools hub.

Pick the narrowest scopes

Scopes are the main safety control for an agent. Both the Gmail scope page and the Drive scope page tell developers to request the most narrowly focused scope that does the job, and Google sorts scopes into three tiers. Non-sensitive scopes need only basic OAuth verification. Sensitive scopes need additional verification. Restricted scopes need restricted-scope verification, and if you store or transmit restricted data on servers, a security assessment too.

Gmail scopes that matter for agents:

ScopeWhat it allowsTier
gmail.sendSend mail on the user’s behalfSensitive
gmail.labelsSee and edit labelsNon-sensitive
gmail.metadataLabels and headers, not the bodyRestricted
gmail.readonlyRead messages and settingsRestricted
gmail.composeManage drafts and sendRestricted
gmail.modifyRead, compose and send; no immediate permanent deleteRestricted
https://mail.google.com/Everything, including permanent deletionRestricted

Google’s note on the full-access scope is blunt: request it only if you must permanently delete threads and messages and skip the trash. For an agent, that is almost never needed.

Drive scopes:

ScopeWhat it allowsTier
drive.fileFiles the app creates, or that the user opens or shares with it via a pickerNon-sensitive
drive.appdataThe app’s own configuration data in DriveNon-sensitive
drive.metadata.readonlyMetadata of all filesRestricted
drive.readonlyView and download all filesRestricted
driveView and manage all filesRestricted

Google prefers non-sensitive Drive scopes because they grant access file by file. The Drive docs also explain that scopes live in two places: the consent screen in Cloud console sets the most an app may ever ask for, and the code asks for what each session actually needs.

A sensible default for a mail-and-files assistant is gmail.readonly plus gmail.compose (so the agent drafts and a human sends), and drive.file for Drive. These are the same Gmail scopes, plus drive.readonly, that Google lists for its own Gmail and Drive MCP servers. Security reviewers will want to see this choice explained; our security and privacy hub lists tools that help.

Set up the project

The Python quickstarts for Gmail and Drive follow the same steps for both APIs:

  1. Create a Google Cloud project and enable the Gmail API and Drive API.
  2. Configure the OAuth consent screen. Choose Internal for a test inside your Workspace organisation; an app used outside it must be External and declare its scopes.
  3. Create an OAuth client of type Desktop app and save the downloaded file as credentials.json.
  4. Install the libraries (Python 3.10.7 or later is required):
python3 -m pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

Step 3 has an agent-specific option. The quickstart says to tick Use this client for an AI-powered agent if the app takes actions on a user’s behalf, and to create separate clients if the app also has non-agent features. The Gmail quickstart warns the setting can’t be changed after the client exists, so decide up front.

Python code from Google’s samples

This is the authorisation pattern from the Gmail quickstart, with the scope list changed and the Drive service added. The first run opens a browser for consent; later runs reuse token.json.

import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

SCOPES = [
    "https://www.googleapis.com/auth/gmail.readonly",
    "https://www.googleapis.com/auth/gmail.compose",
    "https://www.googleapis.com/auth/drive.file",
]

creds = None
if os.path.exists("token.json"):
    creds = Credentials.from_authorized_user_file("token.json", SCOPES)
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
        creds = flow.run_local_server(port=0)
    with open("token.json", "w") as token:
        token.write(creds.to_json())

gmail = build("gmail", "v1", credentials=creds)
drive = build("drive", "v3", credentials=creds)

Read mail. The quickstart lists labels with gmail.users().labels().list(userId="me"). To read messages, call messages.list and then messages.get on each ID.

Send mail. The Gmail API takes an RFC 2822 MIME message encoded as base64url in the raw field. Google’s sample:

import base64
from email.message import EmailMessage

message = EmailMessage()
message.set_content("This is automated draft mail")
message["To"] = "[email protected]"
message["From"] = "[email protected]"
message["Subject"] = "Automated draft"
encoded = base64.urlsafe_b64encode(message.as_bytes()).decode()
sent = gmail.users().messages().send(userId="me", body={"raw": encoded}).execute()

Swap messages().send for drafts().create if a person should review before anything goes out. For a reply that stays in the same thread, the Subject must match and the References and In-Reply-To headers must follow RFC 2822.

List Drive files (from the Drive quickstart):

results = drive.files().list(pageSize=10, fields="nextPageToken, files(id, name)").execute()
for item in results.get("files", []):
    print(f"{item['name']} ({item['id']})")

Upload a file:

from googleapiclient.http import MediaFileUpload

media = MediaFileUpload("download.jpeg", mimetype="image/jpeg")
file = drive.files().create(body={"name": "download.jpeg"}, media_body=media, fields="id").execute()

Simple and multipart uploads are meant for files of 5 MB or less. Above that, or on unreliable networks, use a resumable upload.

Reacting to new mail and file changes

Polling burns quota. Both APIs can push events to your agent instead.

Gmail delivers notifications through Cloud Pub/Sub. You create a topic, give [email protected] permission to publish to it, then call users.watch with the topic name and optional label filters such as INBOX. The notification carries a new historyId; your agent calls history.list from its last stored ID to find what changed. Two limits to plan for: you must renew the watch at least every 7 days (Google suggests daily), and each watched user is capped at one notification per second, with extras dropped. Google also warns against handling a notification in a way that triggers another one, which can loop.

Drive uses notification channels that post to an HTTPS webhook you own, which needs a valid SSL certificate. Call files.watch for one file or changes.watch for all changes. Notifications contain no file metadata or content, so the agent must call the API afterwards to see what changed. Channels expire and there is no automatic renewal; you create a new channel before the old one lapses.

Quotas changed in 2026

Google’s tiering page says Gmail, Drive and Calendar API quotas were adjusted from May 1, 2026 for new projects. Projects that used these APIs between November 2025 and April 2026 keep their existing quotas for now. The current published limits:

Gmail APIDrive API
Per minute per project1,200,000 units1,000,000 units
Per minute per user per project6,000 units325,000 units
Daily threshold before charges80,000,000 units400,000,000 units

Gmail charges units per method. messages.send costs 100, messages.list 5, messages.get 20 (60 with full, raw or html format) and watch 100. Google says billing details for usage above the daily threshold will come later in 2026 with at least 90 days’ notice. On Drive, a 403 or 429 rate-limit response means back off exponentially and retry.

The official MCP route

Google’s Workspace MCP servers let MCP clients act on Gmail and Drive as well as Calendar, Chat, Docs, Sheets, Slides, People and Classroom, with a separate server per product. The Workspace Updates blog announced the public developer preview with a gradual rollout from May 1, 2026; the setup guide still lists membership in the Workspace Developer Preview Program as a prerequisite.

Setup means enabling both the product APIs and the matching MCP services (for example gmailmcp.googleapis.com and drivemcp.googleapis.com), configuring consent with the listed scopes, and creating a web OAuth client with the AI-agent box ticked. Google’s examples show tools such as gmail.search_threads, gmail.get_thread, gmail.create_draft, drive.search_files and drive.read_file_content. Note the Gmail MCP scopes stop at gmail.compose, so the example flow drafts mail for you to send from Gmail. For Claude, Google says a Pro, Max, Team or Enterprise plan is required, added as a custom connector. One detail worth knowing: for refresh tokens, the client must send access_type=offline, or users sign in again roughly every hour.

The servers act with the signed-in user’s own permissions and data controls, which keeps an agent no more powerful than its user. More agent tooling is collected in our productivity and automation hub and the wider AI agents hub.

Limits worth stating plainly

  • Public apps using sensitive or restricted scopes must pass Google’s OAuth verification, and an unverified app shows a warning screen.
  • Gmail’s per-user rate (6,000 units a minute) allows about 60 sends a minute per user at 100 units each, so bulk mailing is not what this API is for.
  • The MCP servers are a preview, so tool names and setup steps may change; check the setup guide before building on them.
#AI agents#Gmail API#Google Drive API#OAuth#MCP
AI

Written by AI Agents Directory

Editorial team

Facts in this guide are checked against official documentation and repositories, which are linked in the article.