Tutorial
CS357: Foundations of Artificial Intelligence - Read Gmail with OpenCode or Oh My Pi
To authorize a Gmail read-only tool and verify one agent request against a test mailbox.
Contents
Let’s ask an agent to find an email we wrote for this exercise. Use a separate personal Gmail account containing only invented messages. Do not connect an Ursinus account or a mailbox you use for real correspondence. If you need to install an agent, see the OpenCode setup tutorial or its Oh My Pi instructions. Signing in to a model provider does not give the agent access to Gmail.
Choose one path. All three end with the agent reporting how many test messages match, and each puts a different piece of software between the agent and your mailbox.
- Path A: CLI. The agent composes a
gwscommand line in its shell, and Google’s Workspace CLI talks to Gmail. You can run the same command yourself first, but the CLI offers far more commands than this exercise needs. - Path B: Self-hosted MCP. You run your own small MCP server: a Python process on your computer that holds the Gmail grant and offers the agent one named tool. The agent connects to it over streamable HTTP at
http://127.0.0.1:8795/mcp, or starts it itself and talks to it over standard input and output (stdio), and never runs a Gmail command itself. It has a fixture mode that works with no Google account at all. - Path C: Hosted MCP. The agent connects straight to Google’s own Gmail MCP server at
https://gmailmcp.googleapis.com/mcp/v1. There is nothing to install, but the service is a Google Workspace Developer Preview, and Google’s server offers write tools as well as reads.
Use the CLI if you want fewer moving parts, the self-hosted server if you want to see how a server can limit both the operation and the data the agent receives, and the hosted server if your project has preview access and you want to see what a vendor-run MCP server looks like.
Run the agent and its tools in the same environment. Every path assumes that the agent and the program it talks to run in the same place: both in Windows, both on your Mac, or both inside the same WSL distribution or container. On Windows, WSL behaves like a separate Linux computer with its own 127.0.0.1. If the OpenCode desktop app runs in Windows and the Path B server runs in WSL, the agent can look for the server at 127.0.0.1:8795 and find nothing there. Pick one side and use it for every step: run the server in PowerShell if you use the desktop app, or run the opencode or omp command inside WSL if your server runs there. Path B’s stdio option removes this concern, because the agent starts the server itself, in its own environment. Environment variables follow the same rule. An agent you open from the Start menu, the Dock, or a desktop shortcut does not see variables you set in a terminal, such as GOOGLE_WORKSPACE_CLI_CONFIG_DIR in Path A or CS357_GMAIL_ACCESS_TOKEN in Path C, so start the agent from that terminal for those paths.
OpenCode 1 and OpenCode 2 specify the configuration differently. Run opencode --version to see which one you have. The standard installer gives OpenCode 1, and OpenCode 2 is a separate install. Wherever this page shows an opencode.json, it gives both forms: OpenCode 2 puts each server under mcp.servers, and OpenCode 1 puts it directly under mcp. OpenCode 2 also keeps a background service running, so after you change opencode.json, run opencode reload before you check the server. In either version, opencode mcp list in a terminal opened in the project directory shows whether each server connected.
Paths A and B use the Google Desktop app OAuth client from the shared setup below; Path C uses a Web application client, which its own steps create. Every live path asks for a fresh grant with only https://www.googleapis.com/auth/gmail.readonly. This scope permits reads across the mailbox, not just the messages your search returns. It does not allow sending mail or changing labels. Do not reuse credentials from a broader grant.
In Gmail’s web interface, send an invented message to your test account with the subject CS357 MCP DEMO. Complete Google sign-in yourself. Cancel if the screen shows the wrong account or asks for anything beyond Gmail read access. Never give the agent a token, client secret, or browser callback URL in a prompt.
Shared Setup: Google Cloud and Gmail OAuth
Complete this setup once if you plan to read a test mailbox with Path A or Path B. Path C starts from the same kind of project but needs one more API and a different client, which its own steps cover. If you only want to try the MCP fixture, skip to Path B; the fixture needs no Google project, credentials, or sign-in.
The browser console is enough for this step. If you want to check or enable the Gmail API from a terminal, use the Google Cloud CLI (gcloud). gcloud manages the Cloud project; the Google Workspace CLI (gws) reads the test mailbox. Each has its own sign-in.
Optional: install and sign in to gcloud on Ubuntu or Ubuntu under WSL. If gcloud --version already works, skip the install block. If you installed Google’s archive under ~/google-cloud-sdk and Bash cannot find gcloud, run source "$HOME/google-cloud-sdk/path.bash.inc" in this shell. For other systems, see the Google Cloud CLI install guide.
sudo apt-get update
sudo apt-get install ca-certificates curl gnupg
curl -fsSL https://packages.cloud.google.com/apt/doc/apt-key.gpg |
sudo gpg --dearmor -o /usr/share/keyrings/cloud.google.gpg
printf '%s\n' 'deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main' |
sudo tee /etc/apt/sources.list.d/google-cloud-sdk.list
sudo apt-get update
sudo apt-get install google-cloud-cli
gcloud --version
Run gcloud auth login --brief yourself and finish the Cloud CLI sign-in in your browser. Keep the terminal and the browser flow private. This signs you in to manage Cloud resources; it does not authorize gws to read Gmail.
-
Choose a Cloud project for the Gmail OAuth client. If you already have a dedicated test project you can manage, use its project ID. Otherwise, open the New Project page, give the project a display name such as
CS357 Gmail Read Test, and click Create. Note the project ID, which is different from the display name. You can also create the project withgcloudafter signing in:read -r -p 'Choose a globally unique Cloud project ID: ' PROJECT_ID gcloud projects create "$PROJECT_ID" --name='CS357 Gmail Read Test'The Cloud project will contain the Gmail API setting, consent configuration, and Desktop OAuth client.
gcloud auth loginuses its own sign-in flow and does not need the Desktop client you are about to create. If your account cannot create projects, use a dedicated test project you have permission to manage rather than changing your organization’s settings. -
Enable Gmail in that project. Select the project in the Cloud console and enable the Gmail API, or use the commands below. Enter the same project ID for every step. Run the enable command only if the check succeeds but does not list Gmail. Skip
gws auth setupfor this exercise so you do not enable unrelated APIs.read -r -p 'Test Cloud project ID: ' PROJECT_ID gcloud services list --enabled --project="$PROJECT_ID" --filter='config.name=gmail.googleapis.com' --format='value(config.name)'gcloud services enable gmail.googleapis.com --project="$PROJECT_ID" - In Google Auth Platform > Branding, configure the consent screen. Use a name you will recognize when you sign in, such as
CS357 Gmail Read Test. -
Under Audience, set who may sign in to the app:
- Check that the user type is External and the publishing status is Testing.
- Under Test users, choose Add users. Enter your test Gmail address exactly, and add any other Gmail account that will sign in for this exercise. Usually that is just the one test account. Choose Save.
While the app is in Testing, Google lets only the accounts on this list approve it, and it blocks every other account. So we leave the app in Testing. If Google later refuses your sign-in, add the address here; do not publish the app. The address must match the account you pick on Google’s sign-in screen. Do not list or sign in with an Ursinus account. A newly added address can take a few minutes to start working.
- Under Data Access, add only
https://www.googleapis.com/auth/gmail.readonly. This scope lets a tool view email and settings across the mailbox. It cannot send mail or change labels. A search filter limits one request, not the account access granted by the scope. - Under Clients, select Create Client > Desktop app, name the client, and download its JSON. You can reuse a suitable Desktop client from this dedicated test project, but authorize it afresh. The JSON identifies your app; it does not grant access to your mailbox. That happens when you review the scope and approve it in your browser.
See Google’s guides to OAuth consent, managing the app’s audience and test users, Desktop app authorization, and Gmail scopes.
Path A: CLI
This simulation replays the shared setup, then follows the CLI path. It does not sign in to Google or read a mailbox. Open the CLI terminal simulation.
-
Install the CLI. Install
gws0.22.5 for your operating system. If you use Node.js 18 or later, runnpm install -g @googleworkspace/cli@0.22.5, thengws --version. This route does not need an MCP server. The CLI still needs its own browser sign-in. Do not import a token from the MCP path.Ubuntu 22.04 WSL: if
gws --versionreportsGLIBC_2.39not found. Checkuname -mandgetconf GNU_LIBC_VERSION. Ubuntu 22.04 can reportglibc 2.35. If the error persists after reinstallinggws0.22.5 with npm, the block below is for x86_64 only, with npm running under nvm. It uses the matching musl release, which does not need the newer system glibc. Leave system glibc alone. On another architecture or version, use the official release that matches both.( set -eu test "$(uname -m)" = x86_64 prefix=$(npm prefix -g) case "$prefix" in "${NVM_DIR:-$HOME/.nvm}"/versions/node/*) ;; *) exit 1 ;; esac pkg="$(npm root -g)/@googleworkspace/cli" test "$(node -p 'require(process.argv[1]).version' "$pkg/package.json")" = 0.22.5 test "$(command -v gws)" = "$prefix/bin/gws" test -f "$pkg/bin/gws" && test ! -L "$pkg/bin/gws" work=$(mktemp -d) cd "$work" asset=google-workspace-cli-x86_64-unknown-linux-musl.tar.gz base=https://github.com/googleworkspace/cli/releases/download/v0.22.5 curl -fsSLO "$base/$asset" curl -fsSLO "$base/$asset.sha256" sha256sum --check "$asset.sha256" tar -xzf "$asset" ./gws ./gws --version install -m 0755 ./gws "$pkg/bin/gws" gws --version )This replaces the binary the npm launcher calls, not the launcher itself. Recheck
gws --versionafter changing Node versions in nvm or reinstalling the package. -
Store the client file. Create a private local directory outside your project and synced folders. Move the downloaded client JSON there as
client_secret.json. On Windows, use a new directory under%LOCALAPPDATA%and check Properties > Security. On macOS or Linux, use a new directory in your home folder with mode700and set the file mode to600. SetGOOGLE_WORKSPACE_CLI_CONFIG_DIRto the private directory path in the terminal you will use. For example:- Windows (PowerShell):
$env:GOOGLE_WORKSPACE_CLI_CONFIG_DIR = Join-Path $env:LOCALAPPDATA 'CS357-GmailReadOnly' -
macOS and Linux (including WSL): use the following commands. The example assumes you saved the Desktop client download as
~/Downloads/client_secret.json. Setclient_downloadto the actual path if it differs. Do not overwrite a client file from another exercise or project.export GOOGLE_WORKSPACE_CLI_CONFIG_DIR="$HOME/.config/cs357-gmail-readonly" client_download="$HOME/Downloads/client_secret.json" install -d -m 700 "$GOOGLE_WORKSPACE_CLI_CONFIG_DIR" (umask 077; set -C; cat "$client_download" > "$GOOGLE_WORKSPACE_CLI_CONFIG_DIR/client_secret.json")The new file has mode
600. If WSL downloaded the file to Windows, use its local path from WSL and copy it into the Linux home directory as shown. Keep the client file out of Git, synced folders, agent prompts, and screenshots.
- Windows (PowerShell):
-
Authorize the CLI. In a terminal without other
gwscredential overrides, authorize the CLI yourself:gws auth login --scopes https://www.googleapis.com/auth/gmail.readonlyUse the exact scope. Plain
gws auth logincan request write access, and--readonlycan include other Workspace services. Complete consent yourself in your browser. Do not paste tokens, authorization codes, or callback URLs into chat. If Google refuses the sign-in because the app is still in testing, check that the account you chose is on the Test users list, as in the Shared Setup Audience step. See the CLI authentication guide for the client file and local credential store.No browser on this machine?
gws0.22.5 has no mode for pasting the redirect address back in. Its documented headless route exports a long-lived credential file from a computer that has a browser, which is more than this exercise should hand around. On a headless machine or in a container, use Path B with--pasteinstead. -
Verify with one read. Run the search yourself before launching the agent.
merefers to the account that approved the grant. A successful response verifies that the test grant works;--dry-runonly previews the request. The search returns up to three matching message IDs, not message bodies. Keep its output local.Windows (PowerShell 7.3+, with native argument passing set to Standard):
$PSNativeCommandArgumentPassing = 'Standard' $params = @{userId='me'; q='subject:"CS357 MCP DEMO"'; maxResults=3} | ConvertTo-Json -Compress gws gmail users messages list --params $paramsmacOS and Linux (Bash or Zsh):
gws gmail users messages list --params '{"userId":"me","q":"subject:\"CS357 MCP DEMO\"","maxResults":3}' -
Test with a Read-Only Request. From that terminal, change to an empty working directory and launch
opencodeoromp. Paste this prompt instead of pasting the command output or any credential:Check my Gmail test inbox using the
gwsCLI. Use the shell tool to run onegws gmail users messages listrequest. SetuserIdtome,qtosubject:"CS357 MCP DEMO", andmaxResultsto3. Use quoting for the shell you are running in. Report how many IDs this page returned. Do not fetch message bodies, open credential files, follow links, run other commands, or change anything in Gmail.
Path B: Self-hosted MCP
On this path we run our own MCP server: a short Python script that holds the Gmail grant and offers the agent one tool, count_demo_messages. In live mode the tool asks Gmail for up to three IDs matching the exercise subject and returns only a count, never the IDs or message bodies. In fixture mode, which needs no Google account, it returns a fixed answer, so you can connect an agent before you sign in to anything.
The agent can reach the server in one of two ways, and each step below covers both:
- HTTP. You start the server in a terminal, and it listens at
http://127.0.0.1:8795/mcp. The agent connects to that address. You can watch the server’s output and you run the sign-in yourself, so this option is the easier one to troubleshoot. - stdio. The agent starts its own copy of the server with
--stdioand talks to it through standard input and output. There is no port and no second terminal, and the server always runs in the agent’s environment. The agent also starts the Google sign-in each time it launches.
If you are not sure which to choose, start with HTTP.
-
Save the server. In a new local directory, copy the whole box into
gmail_readonly.py.This version is written for the MCP Python SDK 2.x. If you have an older copy of this script that starts with
from mcp.server.fastmcp import FastMCP, a fresh install ofmcpnow stops it withModuleNotFoundError: No module named 'mcp.server.fastmcp', because 2.x renamedFastMCPtoMCPServerand moved the HTTP settings (host, port, and the two transport options) from the constructor torun(). The migration guide lists the changes. The tool, its checks, and what it returns are the same as before.# Targets the MCP Python SDK 2.x (mcp>=2.3,<3; see requirements.txt). # In 2.x, FastMCP became MCPServer, and the HTTP settings moved to run(): # https://py.sdk.modelcontextprotocol.io/v2/migration/#fastmcp-renamed-to-mcpserver import argparse import contextlib import getpass import logging import os import platform import sys import time from importlib import metadata from pathlib import Path import httpx from google_auth_oauthlib.flow import InstalledAppFlow from mcp.server.mcpserver import MCPServer from mcp.server.mcpserver.exceptions import ToolError SCOPE = "https://www.googleapis.com/auth/gmail.readonly" URL = "https://gmail.googleapis.com/gmail/v1/users/me/messages" QUERY = 'subject:"CS357 MCP DEMO"' PASTE_REDIRECT = "http://127.0.0.1:8796/" LOG = logging.getLogger("cs357_gmail_demo") def setup_logging(log_file: Path | None) -> None: """Write diagnostics to log_file, if one is given. Never to stdout, and never the token.""" LOG.propagate = False if log_file is None: LOG.addHandler(logging.NullHandler()) return handler = logging.FileHandler(log_file, encoding="utf-8") handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s")) LOG.addHandler(handler) LOG.setLevel(logging.INFO) def log_environment() -> None: """Record which Python and package versions are running, to catch a wrong interpreter.""" versions = [] for name in ("mcp", "httpx", "google-auth-oauthlib"): try: versions.append(f"{name} {metadata.version(name)}") except metadata.PackageNotFoundError: versions.append(f"{name} missing") # Shorten the home directory to ~ so the log does not carry the account name. python = str(Path(sys.executable)).replace(str(Path.home()), "~") in_venv = "yes" if sys.prefix != sys.base_prefix else "no" LOG.info("environment: Python %s at %s (virtual environment: %s) on %s; %s", platform.python_version(), python, in_venv, platform.platform(), ", ".join(versions)) def google_reason(response: httpx.Response) -> tuple[str, str]: """Return Google's short error code (safe to show the agent) and its full message (log only).""" try: error = response.json()["error"] reasons = ", ".join(e.get("reason", "?") for e in error.get("errors", [])) return f"{error.get('status', '')} {reasons}".strip(), error.get("message", "") except (ValueError, KeyError, TypeError, AttributeError): return "no error code", "no details in the reply" def authorize(client_json: Path, paste: bool = False) -> str: flow = InstalledAppFlow.from_client_secrets_file( str(client_json), scopes=[SCOPE], autogenerate_code_verifier=True ) if flow.client_type != "installed": raise ValueError("Use a Desktop app OAuth client.") logging.getLogger("google_auth_oauthlib.flow").setLevel(logging.WARNING) if paste: # For a machine with no browser: approve on any device, then paste the # 127.0.0.1 address the browser could not open. The code in it is useless # without the PKCE verifier and client secret this process holds. flow.redirect_uri = PASTE_REDIRECT url, _ = flow.authorization_url(access_type="online", prompt="consent") print("Open this address on any device and approve Gmail read-only access:") print(url, flush=True) reply = getpass.getpass("Paste the http://127.0.0.1:8796/ address (hidden): ").strip() if not reply.startswith(PASTE_REDIRECT + "?"): raise ValueError("That is not the loopback address.") # The redirect never left this computer, so accept http here only, as # run_local_server does for its own loopback callback. flow.fetch_token(authorization_response="https://" + reply[len("http://"):]) else: flow.run_local_server( host="127.0.0.1", port=0, timeout_seconds=180, authorization_prompt_message=None, access_type="online", prompt="consent", ) grant = flow.oauth2session.token scopes = grant.get("scope", []) if isinstance(scopes, str): scopes = scopes.split() if scopes != [SCOPE] or not grant.get("access_token"): # Scope names are not secret, and they show exactly what Google granted. raise ValueError(f"Google granted {scopes or 'no scopes'}, not only {SCOPE}.") expires_in = grant.get("expires_in", "?") expires_at = grant.get("expires_at") until = time.strftime(" (until %H:%M:%S)", time.localtime(expires_at)) if expires_at else "" LOG.info("signed in; Google granted only %s; the token expires in %s seconds%s", SCOPE, expires_in, until) return grant["access_token"] def make_server(token: str | None) -> MCPServer: server = MCPServer("CS357 Gmail demo") @server.tool() def count_demo_messages() -> dict[str, int | str]: """Count up to three matches for the fixed CS357 demo subject.""" if token is None: LOG.info("count_demo_messages called in fixture mode") return {"mode": "fixture", "matches_on_page": 1} started = time.monotonic() try: with httpx.Client(timeout=10, trust_env=False) as client: response = client.get( URL, headers={"Authorization": "Bearer " + token}, params={"q": QUERY, "maxResults": 3, "fields": "messages(id)"}, ) response.raise_for_status() messages = response.json().get("messages", []) if not isinstance(messages, list) or len(messages) > 3: raise ValueError("Unexpected Gmail response.") except httpx.HTTPStatusError as e: code, message = google_reason(e.response) status = e.response.status_code LOG.error("Gmail answered HTTP %s after %.1f s: %s: %s", status, time.monotonic() - started, code, message) # ToolError's text reaches the agent. It holds the status and Google's # error code, never anything from the mailbox. reply = f"Gmail read failed: HTTP {status} {code}. Check the test grant or restart." LOG.error("returned to the agent: %s", reply) raise ToolError(reply) from None except (httpx.HTTPError, ValueError, AttributeError) as e: cause = e.__cause__ or e.__context__ LOG.error("Gmail read failed before a usable reply after %.1f s: %s: %s (cause: %r)", time.monotonic() - started, type(e).__name__, e, cause) reply = (f"Gmail read failed before a usable reply ({type(e).__name__}). " "Check the network or restart.") LOG.error("returned to the agent: %s", reply) raise ToolError(reply) from None LOG.info("count_demo_messages called in Gmail mode: HTTP %s after %.1f s, " "%d match(es) on the first page", response.status_code, time.monotonic() - started, len(messages)) return {"mode": "gmail", "matches_on_page": len(messages)} return server @contextlib.contextmanager def stdout_to_stderr(): """Send everything written to stdout, by this process or a program it starts, to stderr.""" # Over stdio, stdout carries the MCP messages, so nothing else may write there. sys.stdout.flush() saved = os.dup(1) os.dup2(2, 1) try: yield finally: sys.stdout.flush() os.dup2(saved, 1) os.close(saved) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--client-json", type=Path) parser.add_argument("--paste", action="store_true", help="sign in from another device and paste the redirect address") parser.add_argument("--stdio", action="store_true", help="let the agent start this server and talk to it over stdin and stdout") parser.add_argument("--log-file", type=Path, help="write diagnostics (never the token or any message) to this file") args = parser.parse_args() if args.stdio and args.paste: parser.error("--paste needs a terminal to type into; use it without --stdio") setup_logging(args.log_file) log_environment() LOG.info("starting: mode=%s transport=%s", "gmail" if args.client_json else "fixture", "stdio" if args.stdio else "http://127.0.0.1:8795/mcp") token = None if args.client_json: try: with stdout_to_stderr() if args.stdio else contextlib.nullcontext(): token = authorize(args.client_json, args.paste) except Exception as e: LOG.error("sign-in failed: %s: %s", type(e).__name__, e) raise SystemExit("Google sign-in failed or the grant was not Gmail read-only.") from None server = make_server(token) if args.stdio: server.run(transport="stdio") else: server.run( transport="streamable-http", host="127.0.0.1", port=8795, stateless_http=True, json_response=True, )Save these three lines next to it as
requirements.txt. Each pin allows bug fixes but stops at the next major version, so a future 3.x release cannot break the script the way 2.x broke the old one.mcp>=2.3,<3 google-auth-oauthlib>=1.5,<2 httpx>=0.28,<1 -
Install the dependencies and check the fixture. Use Python 3.11 or later, and run these commands from the directory containing the script. They create a virtual environment in
.venv, install the three packages into it, and start the server in fixture mode, which never contacts Gmail.macOS, Linux, or WSL:
python3 -m venv .venv .venv/bin/python -m pip install -r requirements.txt .venv/bin/python gmail_readonly.pyWindows (PowerShell):
py -3 -m venv .venv .\.venv\Scripts\python.exe -m pip install -r requirements.txt .\.venv\Scripts\python.exe gmail_readonly.pyLeave this terminal open, and wait for the line
Uvicorn running on http://127.0.0.1:8795. The server does not authenticate local callers, so use it only on a trusted computer, and do not publish, forward, or tunnel the port. Run the check below even if you plan to use stdio, because it shows that the script works before an agent is involved.Check the fixture. Let’s talk to the server ourselves first, so that if something goes wrong later, we know whether the problem is the server or the agent. In a second terminal on macOS, Linux, or WSL, send the two requests an agent would send first:
initialize, then a call to the tool.H='-H Content-Type:application/json -H Accept:application/json,text/event-stream' curl -s $H -X POST http://127.0.0.1:8795/mcp -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"t","version":"1"}}}' curl -s $H -X POST http://127.0.0.1:8795/mcp -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"count_demo_messages","arguments":{}}}'The first reply should include
"serverInfo":{"name":"CS357 Gmail demo". The second should end with"isError":false,"structuredContent":{"mode":"fixture","matches_on_page":1}. Neither request sends a session header:stateless_http=Truelets each request stand on its own, andjson_response=Truesends a plain JSON reply instead of an event stream. If you are on Windows without WSL, you can skip this check and use the agent check in Step 4 instead.Optional: keep a log. Add
--log-fileand a file name to anygmail_readonly.pycommand on this page, for example--log-file gmail_demo.log. The server then records which Python and package versions it is running, when it started and in which mode, whether sign-in succeeded and when the token expires, or why sign-in failed, and each tool call with how long Gmail took to answer. When Gmail refuses a request, it records the HTTP status and the reason Google gives. It never records the token or anything from your mailbox, and it shortens your home directory to~, and it writes only to that file, so the log is safe with stdio as well. With stdio, add"--log-file", "/full/path/to/project/gmail_demo.log"to the server’s command in Step 3, with an absolute path, because the agent decides which directory the server starts in. Read the log whenever the agent reports an error from the tool, and delete it when you finish. -
Connect your coding agent. Find your agent and version below, and save its configuration in the project directory. Check the OpenCode version with
opencode --version, as the Which OpenCode? note near the top describes.- HTTP: keep the server from Step 2 running, and start the agent in a second terminal in the same directory. What the client calls a
remoteorhttpserver is an HTTP connection, even when the address is your own computer. - stdio: stop the server from Step 2 with Ctrl+C, because the agent starts its own copy. In the configuration, replace
/full/path/to/projectwith the absolute path to the directory that holdsgmail_readonly.pyand its.venv. The paths must exist where the agent runs: Windows paths for the desktop app on Windows, and WSL paths for an agent inside WSL.
OpenCode 2 (
opencode.json). For HTTP:{ "mcp": { "servers": { "gmail-demo": { "type": "remote", "url": "http://127.0.0.1:8795/mcp", "oauth": false, "codemode": false } } } }For stdio:
{ "mcp": { "servers": { "gmail-demo": { "type": "local", "command": ["/full/path/to/project/.venv/bin/python", "/full/path/to/project/gmail_readonly.py", "--stdio"], "codemode": false, "protocol": "legacy" } } } }"protocol": "legacy"tells OpenCode 2 to open the connection with the MCP handshake that the Python SDK speaks. Without it, OpenCode 2 tries a newer handshake first, and a server that is still waiting for your Google sign-in in Step 5 can be marked as failed.OpenCode 1 (
opencode.json). The server sits directly undermcp, and there is nocodemodeorprotocolsetting. For HTTP:{ "mcp": { "gmail-demo": { "type": "remote", "url": "http://127.0.0.1:8795/mcp", "oauth": false } } }For stdio:
{ "mcp": { "gmail-demo": { "type": "local", "command": ["/full/path/to/project/.venv/bin/python", "/full/path/to/project/gmail_readonly.py", "--stdio"] } } }Oh My Pi (
.omp/mcp.json). For HTTP:{ "mcpServers": { "gmail-demo": {"type": "http", "url": "http://127.0.0.1:8795/mcp"} } }For stdio, which is Oh My Pi’s default transport:
{ "mcpServers": { "gmail-demo": { "command": "/full/path/to/project/.venv/bin/python", "args": ["/full/path/to/project/gmail_readonly.py", "--stdio"] } } }stdio on Windows. Point the command at the Windows virtual environment, and double each backslash, because the file is JSON. In OpenCode, for either version:
"command": ["C:\\full\\path\\to\\project\\.venv\\Scripts\\python.exe", "C:\\full\\path\\to\\project\\gmail_readonly.py", "--stdio"],In Oh My Pi,
commandholds the first path andargsholds the rest, written the same way. - HTTP: keep the server from Step 2 running, and start the agent in a second terminal in the same directory. What the client calls a
-
Try the fixture. Start the agent from the project directory, or open that directory in the desktop app. In OpenCode 2, run
opencode reloadif its service was already running. Then check thatgmail-democonnected: use/mcpsin OpenCode oropencode mcp listin a terminal, and/mcp test gmail-demoand/toolsin Oh My Pi. Ask the agent to callcount_demo_messagesonce. Check the tool trace formode: fixtureandmatches_on_page: 1, not a result from your mailbox. -
Sign in to your test mailbox. Close the agent, and stop the fixture server with Ctrl+C if it is running. If you skipped Shared Setup, do it now. Use the Desktop OAuth client JSON from that setup; you do not need to install
gwsor rungws auth login. Put the downloaded JSON in a private local directory outside your project and outside synced folders. On Windows, check Properties > Security; on macOS/Linux, use a directory with mode700and a file with mode600. In the browser, authorize only the test mailbox and the Gmail read-only permission.- HTTP: run the
gmail_readonly.pycommand from Step 2 again, adding--client-jsonfollowed by the quoted absolute path to the download. The script opens Google’s sign-in in your browser. The server starts listening only after you approve, so wait for theUvicorn runningline, then start the agent again from the second terminal. - stdio: add two things to the configuration from Step 3, then start the agent again (in OpenCode 2, run
opencode reload). First, put"--client-json", "/full/path/to/client_secret.json"at the end ofcommandin OpenCode orargsin Oh My Pi. Second, give the server time to wait for your sign-in, because the agent otherwise gives up on a server that does not answer within 30 seconds. Add the timeout besidecommandorargs:"timeout": {"startup": 180000}in OpenCode 2, or"timeout": 180000in OpenCode 1 and Oh My Pi. OpenCode 1 ignores the OpenCode 2 form, so use the one that matches your version. The values are in milliseconds, and 180000 matches the three minutes the script waits for Google. When the agent starts, it starts the server, the server opens Google’s sign-in in your browser, and the tool appears once you approve. This happens each time the agent starts, because the token lives only in that copy of the server, and it needs a browser on the same computer.
Optional, HTTP only: sign in from another device. On a machine with no browser, such as a server you reach over SSH or a container, add
--pasteas well. The script prints a Google address instead of opening a browser. Open it on any device, sign in, and approve. Google then sends that browser tohttp://127.0.0.1:8796/?..., which fails to load, because nothing on that device is listening there; that is expected. Copy the whole address from the address bar and paste it at the script’s hidden prompt. The script checks that it is the loopback address, then trades the code in it for a token using the PKCE verifier and client secret it holds, so the code alone is useless to anyone else. Paste it only into that prompt, never into chat, and do it within a few minutes, because the code expires. The script refuses--pastetogether with--stdio, because the hidden prompt needs a terminal to type into, and with stdio the agent holds the server’s input.Two port numbers. The script uses two ports for two different things. Port
8795is where the MCP server listens over HTTP. Therun()call at the bottom of the script sets it, and your agent sends its requests tohttp://127.0.0.1:8795/mcp. Port8796is used only during--pastesign-in. It is thePASTE_REDIRECTaddress that Google sends your browser back to after you approve, and nothing listens there, which is why that page fails to load. Leave both numbers as they are in the script. If the server runs on8796instead, your agent cannot find it at8795, and the browser’s redirect after a--pastesign-in lands on the server, which logs"GET /..." 404 Not Found. The stdio option uses neither port.Either way, the script checks Google’s returned scope before it starts serving and keeps the short-lived token in memory. It does not write a token file or refresh the token, and the agent configuration never contains it.
- HTTP: run the
-
Test with a Read-Only Request. Prompt the agent:
Check my Gmail test inbox using only
gmail-demo. Callcount_demo_messagesonce. Tell me whether it ran in Gmail or fixture mode and report the count on the first page. Do not use the shell, open messages, or change anything in Gmail.Check the tool trace for one call with
mode: gmail. Compare the count with the test mailbox. The token expires about an hour after you sign in. When it does, sign in again yourself: restart the server for HTTP, or restart the agent for stdio. If the tool reports an error, the message names the HTTP status and Google’s short error code, such asHTTP 401 UNAUTHENTICATED; the list below says what each one means. If the trace saysfixture, see the list as well.
If something goes wrong on Path B:
The server does not start, or the check finds nothing.
- The server stops with
address already in use,[Errno 98], or[WinError 10048]. Another program is already listening on the port, and it is usually an earlier copy of this server that is still running in another terminal. Press Ctrl+C in that terminal, or find the program withGet-NetTCPConnection -LocalPort 8795 -State Listenin PowerShell orlsof -i :8795on macOS, Linux, or WSL, and stop it. Then start the server again. Do not change the port to get around the error. If the message names8796, the port in the script’srun()call was changed; set it back to8795, as described in Two port numbers in Step 5. - The
curlcheck in Step 2 prints nothing at all. The-soption hides connection errors, so an empty result usually means nothing is listening on port 8795. Run the first command again without-sto see the error, and read the port on the server’sUvicorn running online. If you changed the port in the script or the agent configuration, set both back to8795. "GET / HTTP/1.1" 404 Not Foundin the server terminal. Something, usually a browser, opened the bare addresshttp://127.0.0.1:8795/. That is expected: the server answers only at/mcp, and it expects MCP messages sent withPOST, not a page load, so use thecurlcheck in Step 2 instead of a browser. If theUvicorn running online shows8796instead of8795, see Two port numbers in Step 5.
The agent cannot reach the server.
- With HTTP,
gmail-demoshows as failed withECONNREFUSED. Nothing was listening at the address when the agent tried it. Check that the server terminal shows theUvicorn running on http://127.0.0.1:8795line, that the agent configuration useshttp://127.0.0.1:8795/mcpexactly, and that the server and agent run in the same environment, as the Same environment note near the top describes. With--client-json, the server starts listening only after you finish signing in. If you started the server after the agent, reconnectgmail-demofrom/mcps, or restart the agent (in OpenCode 2, runopencode reload). - With stdio,
gmail-demoshows as failed. The agent could not start the server, or the server did not answer in time. Check that each path in the configuration exists where the agent runs, and that a live sign-in has the timeout from Step 5. Then run the same command yourself in a terminal. A working server prints nothing and waits for input, so press Ctrl+C to stop it. If it prints an error instead, that error is what the agent saw. gmail-demodoes not appear at all. The agent did not read your configuration. Check that the file is in the directory you opened, that its name is exactlyopencode.jsonor.omp/mcp.json, and that its shape matches your OpenCode version. In OpenCode 2, runopencode reloadafter any change.
Sign-in does not finish.
- Google refuses the sign-in because the app is still being tested or is open only to approved testers, and the script exits with its sign-in failure message. The account you chose is not on the Test users list, you picked a different account at sign-in, or the audience is set to Internal. Add your test Gmail address exactly, as in the Shared Setup Audience step, then sign in again with that account.
- With
--paste, the browser shows a 404 page instead of failing to load. Another program on that device is listening on port 8796 and answered the redirect. The address bar still holds the address to paste, so copy it as usual.
The tool runs but the result is wrong.
- The trace says
fixtureafter you signed in. The agent is still connected to a fixture server. With HTTP, stop every running copy of the server, start it again with--client-json, then restart the agent. With stdio, check that the configuration includes--client-jsonand the path to your client file. - The tool returns an error instead of a count. The server reached Google, and Gmail did not answer with a usable reply. The error names the cause, and the log from Step 2 adds Google’s full explanation and the token’s expiry time.
HTTP 401means the token expired or was revoked, so sign in again.HTTP 403withaccessNotConfiguredmeans the Gmail API is not enabled in the Cloud project that owns your Desktop client; enable it as in the Shared Setup, wait a few minutes, and sign in again. A failure before a usable reply means the request never reached Gmail, often because the network requires a proxy or something on the computer inspects HTTPS traffic; the script deliberately ignores proxy settings, so try another network. If the log’s environment line showsvirtual environment: no, the server is running on a different Python from the one Step 2 set up, so start it with the.venvcommand from Step 2.
Path C: Hosted MCP
On this path we do not run a server at all. Google runs one at https://gmailmcp.googleapis.com/mcp/v1, and the agent connects to it over streamable HTTP with a short-lived access token in a request header. That makes it the shortest path to set up once your project has access, and the one with the most tools you did not ask for: Google’s server can draft, label, and trash mail as well as search it. In this exercise the read-only OAuth grant, not the tool menu or the prompt, is what keeps the agent from changing anything.
This simulation illustrates the setup and the read-only test. It does not sign in to Google or read a mailbox. Open the hosted MCP terminal simulation.
What has been checked, and what has not. On November 24, 2026, without any credentials, we confirmed that Google’s server answers at
/mcp/v1with a valid Google Trust Services certificate, thatinitializeandtools/listsucceed without a token, thatsearch_threadsaccepts thegmail.readonlyscope, and that a tool call without a token is refused with401. We have not run a live search of a mailbox through this path, so if a step below does not match what you see, tell me and use Path A or Path B in the meantime.
-
Confirm that you can use the preview. The Gmail MCP server is part of the Google Workspace Developer Preview Program, and Google’s Gmail MCP guide says you must be a member to use it. If you are not a member and cannot join with your test account, stop here and use Path A or Path B. Nothing below works without it.
-
Choose a Cloud project and enable two APIs. Use a dedicated test project. If you completed the Shared Setup, you can use that project; otherwise, create one as its first bullet describes. In the API Library, enable both the Gmail API (
gmail.googleapis.com) and the Gmail MCP API (gmailmcp.googleapis.com). From a terminal signed in withgcloud, the same step is:read -r -p 'Test Cloud project ID: ' PROJECT_ID gcloud services enable gmail.googleapis.com --project="$PROJECT_ID" gcloud services enable gmailmcp.googleapis.com --project="$PROJECT_ID"If the second command fails with a permission or availability error, the project probably does not have preview access yet; see Step 1.
-
Configure the consent screen. In Google Auth Platform, set up the same three pages as the Shared Setup, if this project does not have them already:
- Branding: a name you will recognize at sign-in, such as
CS357 Gmail Read Test. - Audience: External, left in Testing, with your test Gmail address added under Test users. Choose Add users, enter the address exactly, and save. The Shared Setup Audience step explains why we leave the app in Testing.
- Data Access: only
https://www.googleapis.com/auth/gmail.readonly.
Google’s guide lists three scopes for this page, adding
gmail.composeandgmail.modify, and its quick setup adds all three for you. Skip the quick setup and add only the read-only scope. A scope you never add here is one the consent screen can never grant. - Branding: a name you will recognize at sign-in, such as
-
Create a Web application client for an agent. Under Clients, choose Create Client, then:
- set Application type to Web application and give it a name, such as
CS357 Gmail MCP; - select Use this client for an AI-powered agent, which Google requires for any client that acts for a user through this server;
- under Authorized redirect URIs, add
https://developers.google.com/oauthplaygroundexactly, with no trailing slash.
Choose Create, then copy the client ID and client secret into a private note you will delete at the end of the exercise. They go into the OAuth Playground in Step 6, never into an agent configuration, a prompt, or a file in your project. Use this new Web client rather than the Desktop client from the Shared Setup: the Playground can send you back only to a redirect URI the client lists, and a Desktop client has no place to list one.
- set Application type to Web application and give it a name, such as
-
Optional: look at the server before you sign in. Let’s talk to Google’s server ourselves first, the same way we checked the fixture server on Path B. On macOS, Linux, or WSL, run:
H='-H Content-Type:application/json -H Accept:application/json,text/event-stream' curl -s $H -X POST https://gmailmcp.googleapis.com/mcp/v1 -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"t","version":"1"}}}' curl -s $H -X POST https://gmailmcp.googleapis.com/mcp/v1 -d '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}'The first reply includes
"serverInfo":{"name":"StatelessServer". The second lists every tool, with names such assearch_threads,get_message,create_draft, andtrash_thread. Why can you see write tools you have no permission to use? The list describes the server, not your grant; Google checks the grant when a tool is called. -
Get a short-lived token in the OAuth Playground. Close any agent first. Then, in a browser on any device:
- Open Google’s OAuth 2.0 Playground and choose the gear icon.
- Select Use your own OAuth credentials and enter the client ID and secret from Step 4. Leave link sharing of credentials unchecked, and set Access type to Online.
- In Step 1, clear any scopes that are already selected. In the Input your own scopes box under the list, type
https://www.googleapis.com/auth/gmail.readonlyas the only scope, and choose Authorize APIs. - Sign in with the test account. Cancel if the screen shows another account or asks for anything beyond reading your email.
- In Step 2, choose Exchange authorization code for tokens. Leave Auto-refresh the token before it expires unchecked.
- In the response on the right, check that
scopeis exactlyhttps://www.googleapis.com/auth/gmail.readonly. If it is missing or lists anything else, do not use the token; start again from Step 1 of the Playground.
Leave the Playground open. You will copy only the Access token into a hidden prompt in Step 8. Do not save it in a file, and do not use the refresh token. No browser on the machine that runs the agent? That is fine on this path. The Playground can run on your phone or another computer, and the only thing that crosses over is the access token you paste at the hidden prompt; there is no redirect address to paste back.
An Online token expires about an hour after you get it (the response shows
expires_inin seconds), and that is deliberate here. Google’s guide suggests offline access so that a long-running agent does not ask you to sign in every hour; for a one-time test, a token that stops working on its own is the safer choice. -
Configure the MCP connection. In an otherwise empty local directory, create the configuration for one agent. The configuration names an environment variable,
CS357_GMAIL_ACCESS_TOKEN, rather than containing the token, so the file holds nothing secret. Use the whole address, including/mcp/v1.OpenCode 2 (
opencode.json):{ "mcp": { "servers": { "gmail-demo": { "type": "remote", "url": "https://gmailmcp.googleapis.com/mcp/v1", "oauth": false, "codemode": false, "headers": {"Authorization": "Bearer {env:CS357_GMAIL_ACCESS_TOKEN}"} } } } }OpenCode 1 (
opencode.json):{ "mcp": { "gmail-demo": { "type": "remote", "url": "https://gmailmcp.googleapis.com/mcp/v1", "oauth": false, "headers": {"Authorization": "Bearer {env:CS357_GMAIL_ACCESS_TOKEN}"} } } }Oh My Pi (
.omp/mcp.json):{ "mcpServers": { "gmail-demo": { "type": "http", "url": "https://gmailmcp.googleapis.com/mcp/v1", "headers": {"Authorization": "Bearer ${CS357_GMAIL_ACCESS_TOKEN}"} } } }"oauth": falsetells OpenCode not to start its own sign-in, because the header already carries a token. -
Start the agent from that directory. Use a private terminal without screen recording or shell tracing. Paste the access token only when the hidden prompt appears, then clear your clipboard. If you chose Oh My Pi, replace the
opencodeline withomp. The Bash or Zsh subshell, and the PowerShellfinallyblock, remove the token from your shell when the agent exits. While the agent runs, a tool running as your user with shell access could still read its environment, so do not approve any shell call during this exercise.macOS/Linux (Bash or Zsh):
( printf 'Gmail demo access token: ' >&2 IFS= read -rs CS357_GMAIL_ACCESS_TOKEN || exit 1 printf '\n' >&2 export CS357_GMAIL_ACCESS_TOKEN opencode )Windows (PowerShell 7.3+):
try { $env:CS357_GMAIL_ACCESS_TOKEN = Read-Host 'Gmail demo access token' -MaskInput opencode } finally { Remove-Item Env:CS357_GMAIL_ACCESS_TOKEN -ErrorAction SilentlyContinue } -
Check the connection. In OpenCode, run
/mcpsand look forgmail-demo; in OpenCode 2, runopencode reloadfirst if its service was already running. In Oh My Pi, run/mcp test gmail-demo, then/tools. Either way, you should seesearch_threadsamong Google’s tools. As in Step 5, a tool name in the list is not permission to use it. -
Test with a Read-Only Request. Prompt the agent:
Check my Gmail test inbox using only the
gmail-demoMCP server. Callsearch_threadsonce withqueryset tosubject:"CS357 MCP DEMO",pageSizeset to3, andviewset toTHREAD_VIEW_IDS_ONLY. Report how many threads the first page returned. Do not open a thread or message, use the shell, or change anything in Gmail.What success looks like. The tool trace shows exactly one call, to
search_threads, with those three arguments. Its result has athreadslist of at most three entries, each with anidand little else, and the agent’s count matches the number ofCS357 MCP DEMOthreads you can see in Gmail. The search tool’s reference describes the other fields. If the agent proposes any other tool, stop the turn. -
When you finish, revoke the grant. Close the agent, close the Playground tab, and clear your clipboard. The token stops working within the hour regardless, but revoking it ends access now: remove the test app in Google Account connections. Then delete the demo configuration and the private note holding the client ID and secret. Deleting files does not revoke the Google grant; only the connections page does that.
If something goes wrong on Path C:
404 Not Foundin a browser. Openinghttps://gmailmcp.googleapis.com/by itself returns404. That does not mean the service is down: the server lives only at/mcp/v1, and it expects MCP messages sent withPOST, not a page load. Check that the configuration uses the whole address.401with no token. If a tool call comes back with401and aWWW-Authenticate: Bearer resource_metadata=...header, or the text “Request is missing required authentication credential,” the request reached Google without a token. The usual cause is an agent started from a shell whereCS357_GMAIL_ACCESS_TOKENwas not set. Close the agent and start it again with Step 8.401witherror="invalid_token". The text “Request had invalid authentication credentials” means Google received a token it would not accept, most often one that has expired after its hour. Get a new token with Step 6 and restart the agent. Do not switch the Playground to Offline to avoid this.- A permission or scope error. If Google says the request has insufficient permission or the wrong scopes, the token does not carry
gmail.readonly. Check thescopeline in the Playground response. Fix the token; do not add scopes to the consent screen or the Playground. - A preview or project-access error. If Google says the project or account cannot use the service, the preview is not enabled for you. Use Path A or Path B instead of adding scopes or switching to another account.
- An empty list. Check the subject of your test message and that you signed in to the test account. A page can also come back with no threads but a
nextPageToken; for this exercise, a single test message on the first page is enough.
For any path, check the tool trace for the requested search. Compare the result with the test mailbox and, for the CLI, your manual run. Stop the turn if the agent proposes a different operation. If the list is empty, check the subject and signed-in test account before changing the query. Do not test the grant by attempting a write. When an MCP server shows as failed, OpenCode’s own log usually says why: on Linux and WSL, look in ~/.local/share/opencode/log.
Protect the Returned Data
The OAuth scope controls what the tool can do in Gmail. It does not control where the result goes after Gmail returns it. When an agent runs a command, the output can enter its conversation history and be sent to the model provider. Asking the agent to report only a count limits its reply, not what it sees. The CLI search returns message and thread IDs. The self-hosted MCP server counts the IDs before returning the result, so the model receives neither IDs nor message metadata. When Gmail refuses a request, the model receives only the HTTP status and Google’s short error code. Google’s hosted server returns whatever its tool returns; with THREAD_VIEW_IDS_ONLY, that is thread IDs without per-thread message metadata, and the model sees them. On a real account, even IDs and search results can reveal that someone received mail matching a particular query.
If a task needs only a count, leave message bodies, subjects, senders, attachments, and links out of the tool result. For real data, filter the result locally before it reaches the model. A local model can avoid sending the result to a hosted provider, but the agent may still keep local transcripts or pass data to other tools. Do not share a transcript or screenshot that contains mailbox data or credentials.
If you later read a message, treat its content as untrusted. An email might tell the agent to open a link or upload a file. That text is part of the message, not permission to take another action. Read-only Gmail access can stop a Gmail write; it cannot stop a separate shell or browser tool from acting. Review the tool trace and stop any call outside the task.
When you finish, close the agent, remove this test app’s access in Google Account connections, and clean up the local setup. For the self-hosted server, stop it and remove the demo configuration and private client download. For the hosted server, close the Playground, clear the clipboard, and remove the demo agent configuration. For the CLI, remove the exercise’s private credential directory. Deleting a configuration or local credential file does not revoke the Google grant.