Scoped Google Drive Access for AI Agents
Give your AI agent read/write access to Google Drive — scoped to only the files it creates or you explicitly share with it. No blanket access to your entire Drive.
Your AI agent becomes dramatically more useful when it can create documents, spreadsheets, and presentations on your behalf. But handing over full Drive access is a privacy nightmare — especially if you're running open-source tools where you control the keys.
The drive.file scope is the sweet spot: your agent can create new files and access files you deliberately share with it, but it can't browse or read anything else in your Drive. Least privilege, maximum utility.
Architecture
The setup uses two credentials with two purposes:
AI Agent (your machine)
│
├── OAuth Token (~/.your-agent/google-oauth-token.json)
│ └── Scope: drive.file (only files agent creates or you share)
│
├── Service Account (read-only fallback)
│ └── Can read shared folder contents, zero storage quota
│
└── Shared Folder ("AI Agent" on Google Drive)
└── Agent creates files here, you share existing files here
- OAuth token — your personal Google account's permission, scoped to
drive.file. This is what the agent uses to create files (docs, sheets, slides). It can only touch files it made or files you explicitly shared. - Service account — a separate Google-managed identity. You share a folder with it, and it can read that folder's contents. But service accounts have zero storage quota — they literally cannot create files. Use this as a read-only fallback.
Why Not Just Use a Service Account?
Service accounts seem simpler — no browser auth, no token refresh. But they have a fatal limitation: zero Drive storage quota. They can read files shared with them, but they can't create anything. For an agent that needs to generate documents, you need OAuth.
Scope Comparison
| Scope | What it can access |
|---|---|
drive |
Every file in your entire Google Drive |
drive.file |
Only files the app created + files you explicitly opened/shared with it |
If your agent's OAuth token ever leaks, drive.file means the attacker can only see files your agent made — not your tax returns, medical records, or anything else. This is the principle of least privilege in practice.
Step 1 — Create a Google Cloud Project
- Go to Google Cloud Console
- Create a new project (e.g., "ai-agent")
- Enable these APIs:
- Google Drive API
- Google Docs API
- Google Sheets API
- Google Slides API (optional, for presentation support)
Step 2 — Create OAuth Credentials
- Go to APIs & Services → Credentials
- Click Create Credentials → OAuth client ID
- Application type: Desktop app
- Name it something descriptive (e.g., "AI Agent Desktop")
- Download the client secret JSON — you'll need the
client_idandclient_secret
Step 3 — Configure the Consent Screen
- Go to APIs & Services → OAuth consent screen
- User type: External (unless you have a Workspace org)
- Fill in the required fields (app name, support email)
- Add the scope:
https://www.googleapis.com/auth/drive.file - Add yourself as a test user
Note: While your app is in "Testing" mode, tokens expire after 7 days. You'll need to re-auth weekly until you publish the app (which requires Google's review). This is annoying but manageable — just re-run the auth flow when your token expires.
Step 4 — Run the Auth Flow (On a Separate Device)
This is the security-conscious part. If your AI agent runs on a machine you don't want logged into your Google account (shared server, always-on box), do the auth on a different device.
First, install the required Python libraries:
pip install google-api-python-client google-auth-oauthlib
Then run this script:
#!/usr/bin/env python3
"""Generate OAuth token for Google Drive (drive.file scope)."""
from google_auth_oauthlib.flow import InstalledAppFlow
CLIENT_CONFIG = {
"installed": {
"client_id": "YOUR_CLIENT_ID.apps.googleusercontent.com",
"client_secret": "YOUR_CLIENT_SECRET",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"redirect_uris": ["urn:ietf:wg:oauth:2.0:oob"]
}
}
SCOPES = ["https://www.googleapis.com/auth/drive.file"]
flow = InstalledAppFlow.from_client_config(CLIENT_CONFIG, SCOPES)
auth_url, _ = flow.authorization_url(prompt="consent")
print(f"\nOpen this URL in a browser:\n{auth_url}\n")
code = input("Paste the authorization code here: ")
flow.fetch_token(code=code)
creds = flow.credentials
print(f"\nAccess token: {creds.token}")
print(f"Refresh token: {creds.refresh_token}")
The key trick: using urn:ietf:wg:oauth:2.0:oob as the redirect URI means Google shows you an auth code instead of redirecting to localhost. You can open the auth URL on your phone, sign in there, and paste the code back to your agent's machine. Your Google password never touches the agent's machine.
Step 5 — Store the Token
Save the credentials as JSON for your agent to use:
{
"access_token": "ya29...",
"refresh_token": "1//0e...",
"client_id": "YOUR_CLIENT_ID.apps.googleusercontent.com",
"client_secret": "YOUR_CLIENT_SECRET"
}
Store this at a known path (e.g., ~/.your-agent/google-oauth-token.json). Your agent reads this file when it needs to call Google APIs.
Set permissions to owner-only:
chmod 600 ~/.your-agent/google-oauth-token.json
Security note: This file contains your refresh token — treat it like a password. Anyone with it can create and access files as your app.
Step 7 — Use It
Here's a minimal example of creating a Google Doc in your shared folder:
import json
from pathlib import Path
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
TOKEN_PATH = Path.home() / ".your-agent" / "google-oauth-token.json"
def get_credentials():
with open(TOKEN_PATH) as f:
token_data = json.load(f)
return Credentials(
token=token_data.get("access_token") or token_data.get("token"),
refresh_token=token_data["refresh_token"],
token_uri="https://oauth2.googleapis.com/token",
client_id=token_data["client_id"],
client_secret=token_data["client_secret"],
scopes=["https://www.googleapis.com/auth/drive.file"],
)
creds = get_credentials()
drive = build("drive", "v3", credentials=creds)
docs = build("docs", "v1", credentials=creds)
# Create a new doc in your shared folder
file_metadata = {
"name": "Meeting Notes - 2026-02-25",
"mimeType": "application/vnd.google-apps.document",
"parents": ["YOUR_FOLDER_ID"]
}
file = drive.files().create(body=file_metadata, fields="id").execute()
doc_id = file["id"]
print(f"Created doc: https://docs.google.com/document/d/{doc_id}")
# Write to it
docs.documents().batchUpdate(
documentId=doc_id,
body={"requests": [{
"insertText": {
"location": {"index": 1},
"text": "Hello from your AI agent!\n"
}
}]}
).execute()
Step 8 — (Optional) Add a Service Account for Read-Only
If you also want your agent to read files you didn't create through the agent:
- In Google Cloud Console: IAM & Admin → Service Accounts → Create
- Download the JSON key file
- Save it (e.g.,
~/.your-agent/google-service-account.json) - Share your Drive folder with the service account's email address (it looks like
name@project.iam.gserviceaccount.com)
The service account can now list and read files in that folder. Use OAuth for creating, service account for reading — belt and suspenders.
Token Refresh
The access token expires after ~1 hour. The Google Python client handles refresh automatically using the refresh token — you don't need to manage this manually. Just make sure the refresh token is in your stored JSON.
The refresh token itself lasts until you revoke it — unless your app is in "Testing" mode on Google Cloud, in which case it expires after 7 days. When that happens, re-run the auth flow from Step 4.
Gotchas
- Testing mode = 7-day token expiry. Publishing your app removes this limit but requires Google review. For personal use, just re-auth weekly.
- Service accounts can't create files. They have zero storage quota. Don't waste time trying to make this work — use OAuth for file creation.
drive.filescope is per-app, not per-folder. The agent can access ANY file it created, regardless of folder. The shared folder is just for organization.- Token file is sensitive. Anyone with your refresh token can create/access files as your app. Protect it accordingly.
- Python version matters. The Google auth libraries throw
FutureWarningon Python 3.9 and below. Use 3.10+ if possible. - The
oobredirect flow is deprecated for new apps as of 2022, but still works for existing OAuth clients created before the cutoff. If creating a fresh client, you may need to usehttp://localhostredirect instead and run a brief local server during auth.
Privacy Model
Your Google Drive
├── Personal files ← Agent CANNOT see these
├── Work files ← Agent CANNOT see these
└── Shared "AI Agent" folder
├── Files you share here ← Agent CAN read (via service account)
└── Files agent creates ← Agent CAN read/write (via OAuth)
This is the same principle as giving someone a key to one room in your house instead of the master key. The agent is powerful where you need it, blind everywhere else.