Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,21 @@ _Refer to the [ID Reference Guide](#-id-reference-guide) for more information ab
3. **Set Environment Variables:**
* `CREDENTIALS_PATH`: Path to the downloaded OAuth credentials JSON file (default: `credentials.json`).
* `TOKEN_PATH`: Path to store the user's refresh token after first login (default: `token.json`). Must be writable.
* *(Optional)* `OAUTH_HOST` / `OAUTH_PORT`: Address the login callback listener binds (default: `localhost` on a random free port). Wildcard addresses such as `0.0.0.0` are refused.

#### Logging in from another machine (remote server, tunnel or reverse proxy)

The default login redirects your browser to `http://localhost:<port>/`, which only works when the browser runs on the same machine as the server. If the server runs remotely, expose a fixed local port over HTTPS (a tunnel such as `cloudflared` or `ngrok`, or a reverse proxy) and set:

* `OAUTH_REDIRECT_BASE`: The public HTTPS URL that forwards to the listener, e.g. `https://my-tunnel.example.com`. Google is sent `<OAUTH_REDIRECT_BASE>/oauth2callback` as the redirect URI.
* `OAUTH_PORT`: The local port the tunnel forwards to (required with `OAUTH_REDIRECT_BASE`). The listener binds `OAUTH_HOST` (default `localhost`), so it stays private to the machine.

Then:

1. Use a **Web application** OAuth client (Desktop clients only accept localhost redirects) and add `<OAUTH_REDIRECT_BASE>/oauth2callback` under **Authorized redirect URIs**. The downloaded JSON (`"web"` or `"installed"` format) goes in `CREDENTIALS_PATH` as usual.
2. Start the server. When it needs a token it logs an authorization URL to stderr instead of opening a browser. Open it on any machine, approve, and the token is saved to `TOKEN_PATH`. The server refreshes it from then on.

To log in from a terminal before wiring the server into a client, run it directly (`uvx mcp-google-sheets@latest` with the variables set), complete the login, and stop it with Ctrl-C once `Successfully authenticated using OAuth flow` is logged.

### Method C: Direct Credential Injection (Advanced) 🔒

Expand Down Expand Up @@ -387,6 +402,9 @@ The server checks for credentials in this order:
| `CREDENTIALS_PATH` | OAuth 2.0 | Path to the OAuth 2.0 Client ID JSON file. | `credentials.json` |
| `TOKEN_PATH` | OAuth 2.0 | Path to store the generated OAuth token. | `token.json` |
| `CREDENTIALS_CONFIG` | Service Account / OAuth 2.0 | Base64 encoded JSON string of credentials content. | - |
| `OAUTH_HOST` | OAuth 2.0 | Address the login callback listener binds. | `localhost` |
| `OAUTH_PORT` | OAuth 2.0 | Port the login callback listener binds (`0` = random). | `0` |
| `OAUTH_REDIRECT_BASE` | OAuth 2.0 | Public HTTPS URL forwarding to the listener, for remote login. | - |

---

Expand Down
98 changes: 97 additions & 1 deletion src/mcp_google_sheets/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@
"""

import base64
import http.server
import ipaddress
import logging
import os
import sys
import urllib.parse
from typing import List, Dict, Any, Optional, Union
import json
from dataclasses import dataclass
Expand Down Expand Up @@ -35,6 +38,12 @@
CREDENTIALS_PATH = os.environ.get('CREDENTIALS_PATH', 'credentials.json')
SERVICE_ACCOUNT_PATH = os.environ.get('SERVICE_ACCOUNT_PATH', 'service_account.json')
DRIVE_FOLDER_ID = os.environ.get('DRIVE_FOLDER_ID', '') # Working directory in Google Drive
# Where the interactive OAuth flow listens for Google's callback. Port 0 picks a random free port.
OAUTH_HOST = os.environ.get('OAUTH_HOST', 'localhost')
OAUTH_PORT = os.environ.get('OAUTH_PORT', '0')
# Public URL that forwards to OAUTH_HOST:OAUTH_PORT (an HTTPS tunnel or reverse proxy), for when
# the consent browser runs on a different machine. Unset, Google redirects to the local listener.
OAUTH_REDIRECT_BASE = os.environ.get('OAUTH_REDIRECT_BASE', '')


def _configure_logging() -> None:
Expand Down Expand Up @@ -73,6 +82,93 @@ def _parse_enabled_tools() -> Optional[set]:

ENABLED_TOOLS = _parse_enabled_tools()


def _oauth_listener_address() -> tuple:
"""Return the (host, port) the OAuth callback listener binds, from OAUTH_HOST/OAUTH_PORT."""
try:
port = int(OAUTH_PORT)
except ValueError:
raise ValueError(f"OAUTH_PORT must be an integer, got {OAUTH_PORT!r}")
if not 0 <= port <= 65535:
raise ValueError(f"OAUTH_PORT must be between 0 and 65535, got {port}")
host = OAUTH_HOST.strip()
try:
unspecified = ipaddress.ip_address(host.strip('[]')).is_unspecified
except ValueError:
unspecified = not host # a hostname such as "localhost"
if unspecified:
# A wildcard bind would accept the OAuth callback (and its auth code) on every interface.
raise ValueError(f"OAUTH_HOST must be a specific address, not {OAUTH_HOST!r}")
return host, port


def _oauth_redirect_uri(base: str) -> str:
"""Validate OAUTH_REDIRECT_BASE and return the redirect URI to register with Google."""
parsed = urllib.parse.urlsplit(base.strip())
if parsed.scheme != 'https' or not parsed.hostname or parsed.query or parsed.fragment:
raise ValueError(
f"OAUTH_REDIRECT_BASE must be an https:// URL with no query or fragment, got {base!r}")
return f"{parsed.geturl().rstrip('/')}/oauth2callback"


def _run_oauth_flow(flow: InstalledAppFlow) -> Credentials:
"""Run the interactive OAuth consent and return the user's credentials.

Without OAUTH_REDIRECT_BASE this is google-auth-oauthlib's loopback flow on
OAUTH_HOST:OAUTH_PORT. With it, Google redirects to <base>/oauth2callback, and a listener
on OAUTH_HOST:OAUTH_PORT (which the tunnel must forward to) completes the token exchange.
"""
host, port = _oauth_listener_address()
if not OAUTH_REDIRECT_BASE:
return flow.run_local_server(host=host, port=port)

if port == 0:
raise ValueError("OAUTH_PORT must be set to the port your tunnel forwards to "
"when OAUTH_REDIRECT_BASE is set")
flow.redirect_uri = _oauth_redirect_uri(OAUTH_REDIRECT_BASE)
# prompt=consent makes Google issue a refresh token even if this client was approved before.
auth_url, _ = flow.authorization_url(access_type='offline', prompt='consent')
# Logged rather than opened: the browser is on another machine. Logging goes to stderr, so
# this doesn't corrupt the stdio MCP stream.
logger.warning("Open this URL in a browser to authorize Google Sheets access:\n%s", auth_url)

outcome: Dict[str, Any] = {}

class CallbackHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
# Match on the last path segment only: a proxy may or may not strip a base path prefix.
request = urllib.parse.urlsplit(self.path)
if not request.path.endswith('/oauth2callback'):
self.send_error(404)
return
query = urllib.parse.parse_qs(request.query)
if 'error' in query:
outcome['error'] = query['error'][0]
self.send_error(400, f"Authorization failed: {outcome['error']}")
return
try:
flow.fetch_token(authorization_response=f"{flow.redirect_uri}?{request.query}")
credentials = flow.credentials
except Exception as e: # stale tab, replayed code, or state mismatch: keep waiting
logger.error("OAuth token exchange failed: %s", e)
self.send_error(400, "Token exchange failed. Retry from the authorization URL.")
return
outcome['credentials'] = credentials
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.end_headers()
self.wfile.write(b"Google Sheets authorized. You can close this tab.")

def log_message(self, *args):
pass # BaseHTTPRequestHandler logs to stderr per request; the flow logs what matters

with http.server.HTTPServer((host, port), CallbackHandler) as callback_server:
while not outcome:
callback_server.handle_request()
if 'error' in outcome:
raise RuntimeError(f"OAuth authorization failed: {outcome['error']}")
return outcome['credentials']

@dataclass
class SpreadsheetContext:
"""Context for Google Spreadsheet service"""
Expand Down Expand Up @@ -130,7 +226,7 @@ async def spreadsheet_lifespan(server: FastMCP) -> AsyncIterator[SpreadsheetCont
if not creds:
try:
flow = InstalledAppFlow.from_client_secrets_file(CREDENTIALS_PATH, SCOPES)
creds = flow.run_local_server(port=0)
creds = _run_oauth_flow(flow)

# Save the credentials for the next run
with open(TOKEN_PATH, 'w') as token:
Expand Down
145 changes: 145 additions & 0 deletions tests/test_oauth_flow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import socket
import threading
import time
import unittest
import urllib.error
import urllib.parse
import urllib.request
from unittest.mock import MagicMock, patch

from google_auth_oauthlib.flow import InstalledAppFlow

from mcp_google_sheets import server

CLIENT_FIELDS = {
"client_id": "test-client.apps.googleusercontent.com",
"client_secret": "test-secret",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
}
BASE = "https://tunnel.example.com"


def free_port():
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]


def oauth_env(host="localhost", port="0", base=""):
return patch.multiple(server, OAUTH_HOST=host, OAUTH_PORT=port, OAUTH_REDIRECT_BASE=base)


class LoopbackFlowTests(unittest.TestCase):
def test_defaults_use_random_localhost_port(self):
flow = MagicMock()
with oauth_env():
server._run_oauth_flow(flow)
flow.run_local_server.assert_called_once_with(host="localhost", port=0)

def test_fixed_host_and_port(self):
flow = MagicMock()
with oauth_env(host="127.0.0.1", port="3500"):
server._run_oauth_flow(flow)
flow.run_local_server.assert_called_once_with(host="127.0.0.1", port=3500)


class ConfigValidationTests(unittest.TestCase):
def assert_rejected(self, **env):
flow = MagicMock()
with oauth_env(**env), self.assertRaises(ValueError):
server._run_oauth_flow(flow)
flow.run_local_server.assert_not_called()

def test_rejects_wildcard_hosts(self):
for host in ("0.0.0.0", "::", "[::]", ""):
with self.subTest(host=host):
self.assert_rejected(host=host)

def test_rejects_bad_ports(self):
for port in ("abc", "-1", "65536"):
with self.subTest(port=port):
self.assert_rejected(port=port)

def test_redirect_base_requires_fixed_port(self):
self.assert_rejected(base=BASE)

def test_redirect_base_must_be_https_without_query(self):
for base in ("http://tunnel.example.com", "tunnel.example.com", "https://", "https://t.example/?a=1"):
with self.subTest(base=base):
self.assert_rejected(port="3500", base=base)

def test_redirect_uri_trims_trailing_slash_and_keeps_path(self):
self.assertEqual(server._oauth_redirect_uri(BASE + "/"), BASE + "/oauth2callback")
self.assertEqual(server._oauth_redirect_uri(BASE + "/sheets"), BASE + "/sheets/oauth2callback")


class RedirectBaseFlowTests(unittest.TestCase):
"""Drives the real callback listener over HTTP; only the token exchange with Google is faked."""

def start_flow(self, client_type):
flow = InstalledAppFlow.from_client_config({client_type: CLIENT_FIELDS}, server.SCOPES)
self.exchanges = []

def fake_fetch_token(**kwargs):
self.exchanges.append(kwargs)
flow.oauth2session.token = {"access_token": "a", "refresh_token": "r", "token_type": "Bearer",
"expires_at": time.time() + 3600}

flow.fetch_token = fake_fetch_token
self.port = free_port()
self.result = {}
logged = []

def run():
with oauth_env(host="127.0.0.1", port=str(self.port), base=BASE), \
patch.object(server.logger, "warning", side_effect=lambda *a: logged.append(a)):
try:
self.result["creds"] = server._run_oauth_flow(flow)
except Exception as e:
self.result["error"] = e

self.thread = threading.Thread(target=run, daemon=True)
self.thread.start()
for _ in range(100): # wait for the listener to bind
try:
socket.create_connection(("127.0.0.1", self.port), timeout=0.1).close()
break
except OSError:
time.sleep(0.02)
self.assertEqual(len(logged), 1)
return urllib.parse.urlsplit(logged[0][1])

def get(self, path):
try:
return urllib.request.urlopen(f"http://127.0.0.1:{self.port}{path}", timeout=5).status
except urllib.error.HTTPError as e:
return e.code

def test_completes_consent_for_installed_and_web_clients(self):
for client_type in ("installed", "web"):
with self.subTest(client_type=client_type):
auth_url = self.start_flow(client_type)
params = urllib.parse.parse_qs(auth_url.query)
self.assertEqual(params["redirect_uri"], [BASE + "/oauth2callback"])
self.assertEqual(params["access_type"], ["offline"])
self.assertEqual(params["prompt"], ["consent"])

self.assertEqual(self.get("/favicon.ico"), 404)
self.assertEqual(self.get("/oauth2callback?code=abc&state=xyz"), 200)
self.thread.join(5)

self.assertEqual(self.exchanges, [
{"authorization_response": BASE + "/oauth2callback?code=abc&state=xyz"}])
self.assertEqual(self.result["creds"].refresh_token, "r")

def test_denied_consent_raises(self):
self.start_flow("web")
self.assertEqual(self.get("/oauth2callback?error=access_denied"), 400)
self.thread.join(5)
self.assertIsInstance(self.result["error"], RuntimeError)
self.assertEqual(self.exchanges, [])


if __name__ == "__main__":
unittest.main()