Skip to main content
Glama
README.md
# mcp-mechanics

A small, working MCP server built with [FastMCP](https://gofastmcp.com), deployed on Google Cloud Run, and
protected by Google sign-in. Claude (claude.ai, Cowork, Claude Code) connects to it as a custom connector.

It shows the moving parts you need for a real remote MCP server, not just a local one:

- **Google OAuth** through FastMCP's `GoogleProvider` (an OAuth proxy). Claude registers itself with
  Client ID Metadata Documents or Dynamic Client Registration, then the user signs in with Google.
- **An email allowlist** checked twice: at the OAuth callback (non-allowed users see an "Access denied"
  page and get no token) and on every `/mcp` request.
- **Persistent, encrypted OAuth state** in Firestore or Redis, so sign-ins survive restarts and
  scale-to-zero.
- **Tools:** `hello(name)` and `list_todays_menu(category)` (mock data).
- **A skill over MCP:** `skills/menu-planner/SKILL.md`, served as `skill://menu-planner/SKILL.md`.

## Why the allowlist matters

Do not rely on the Google OAuth consent screen's **Testing** mode to limit who can sign in. When an app
asks only for basic identity scopes (`openid`, `email`, `profile`), Google lets any Google account sign in,
whether or not it is a test user. Access control has to live in your server. Here it is `ALLOWED_EMAILS`.

If `ALLOWED_EMAILS` is empty, **every Google account with a verified email is allowed**. Always set it.

## Architecture

```
Claude ──HTTPS──▶ Cloud Run (FastMCP, /mcp)
                    │  ├─ /authorize, /consent, /token   OAuth proxy endpoints
                    │  └─ /auth/callback ◀── Google sign-in
                    ├─ Firestore: encrypted OAuth clients, codes, tokens
                    └─ Secret Manager: client ID/secret, JWT key, Fernet key
```

## Setup on Google Cloud

Replace the placeholders: `YOUR_PROJECT`, `YOUR_REGION`, `YOUR_BASE_URL` (for example
`https://mcp.example.com`, or the Cloud Run `run.app` URL), and `you@example.com`.

1. **Enable APIs:** Cloud Run, Cloud Build, Artifact Registry, Firestore, Secret Manager.
2. **Create a Firestore database** (`(default)`, Native mode) in `YOUR_REGION`.
3. **Create an OAuth client** in Google Auth Platform → Clients → *Web application*, with the
   authorized redirect URI `YOUR_BASE_URL/auth/callback`.
4. **Store four secrets** in Secret Manager:

   | Secret | Env var | Value |
   |---|---|---|
   | `mcp-mechanics-google-client-id` | `GOOGLE_CLIENT_ID` | OAuth client ID |
   | `mcp-mechanics-google-client-secret` | `GOOGLE_CLIENT_SECRET` | OAuth client secret |
   | `mcp-mechanics-jwt-signing-key` | `JWT_SIGNING_KEY` | a long random string |
   | `mcp-mechanics-storage-key` | `STORAGE_ENCRYPTION_KEY` | a Fernet key: `python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"` |

5. **Create a service account** `mcp-mechanics@YOUR_PROJECT.iam.gserviceaccount.com` with
   `roles/datastore.user` and `roles/secretmanager.secretAccessor` on the four secrets.

## Deploy

```sh
P=YOUR_PROJECT
gcloud run deploy mcp-mechanics --source . --region YOUR_REGION --project $P \
  --service-account mcp-mechanics@$P.iam.gserviceaccount.com --allow-unauthenticated \
  --min-instances 0 --max-instances 1 --memory 512Mi \
  --set-env-vars "^@^BASE_URL=YOUR_BASE_URL@GOOGLE_CLOUD_PROJECT=$P@ALLOWED_EMAILS=you@example.com" \
  --set-secrets "GOOGLE_CLIENT_ID=mcp-mechanics-google-client-id:latest,GOOGLE_CLIENT_SECRET=mcp-mechanics-google-client-secret:latest,JWT_SIGNING_KEY=mcp-mechanics-jwt-signing-key:latest,STORAGE_ENCRYPTION_KEY=mcp-mechanics-storage-key:latest"
```

- `--allow-unauthenticated` is required: Claude must reach the OAuth endpoints without Cloud IAM.
  The app enforces Google sign-in and the allowlist itself.
- `^@^` sets `@` as the separator, so `ALLOWED_EMAILS` can hold several comma-separated emails.
- For a custom domain, add a Cloud Run domain mapping, point a CNAME to `ghs.googlehosted.com`, then set
  `BASE_URL` to the domain and add `https://your.domain/auth/callback` to the OAuth client.

## Use Redis instead of Firestore

OAuth state (registered clients, authorization codes, tokens) goes to Firestore by default. Set
`REDIS_URL` and it goes to Redis instead. Values are encrypted with `STORAGE_ENCRYPTION_KEY` either way, and
entries expire on their own through Redis TTLs.

Use Redis with persistence (AOF or RDB). If Redis loses its data, every user has to sign in again.

### Local, with Docker Compose

```sh
cp .env.example .env        # fill in the OAuth client, keys, and ALLOWED_EMAILS
docker compose up --build   # Redis + the server on http://localhost:8000
```

Add `http://localhost:8000/auth/callback` to the OAuth client's redirect URIs, then connect a local client
such as Claude Code to `http://localhost:8000/mcp`. Claude on the web needs a public HTTPS URL.

### Cloud Run with Memorystore

Memorystore has only a private IP, so Cloud Run needs Direct VPC egress to reach it:

```sh
gcloud redis instances create mcp-mechanics --size 1 --region YOUR_REGION --project $P \
  --persistence-mode rdb
REDIS_HOST=$(gcloud redis instances describe mcp-mechanics --region YOUR_REGION --project $P --format 'value(host)')

gcloud run deploy mcp-mechanics ... \
  --network default --subnet default --vpc-egress private-ranges-only \
  --set-env-vars "^@^BASE_URL=YOUR_BASE_URL@ALLOWED_EMAILS=you@example.com@REDIS_URL=redis://$REDIS_HOST:6379/0"
```

The service account then no longer needs `roles/datastore.user`. A Memorystore instance bills every hour it
exists, unlike Firestore, which is close to free at this scale.

### Hosted Redis (Upstash, Redis Cloud, and others)

Store the `rediss://` URL, which includes the password, in Secret Manager and pass it as a secret:

```sh
--set-secrets "...,REDIS_URL=mcp-mechanics-redis-url:latest"
```

No VPC setup is needed.

## Connect from Claude

Settings → Connectors → **Add custom connector** → URL `YOUR_BASE_URL/mcp` → Connect → sign in with Google.
Leave the advanced OAuth client fields empty.

## Logs

Every token check writes one structured log line with the email and the decision:

```sh
gcloud logging read 'resource.labels.service_name="mcp-mechanics" AND jsonPayload.message:"auth "' \
  --project YOUR_PROJECT --limit 20 --format='value(timestamp,severity,jsonPayload.message)'
```

## Caveats

`server.py` wraps three private parts of FastMCP's OAuth proxy (`_token_validator.verify_token`,
`_handle_idp_callback`, `_code_store`) to enforce the allowlist. It is tested with FastMCP 4.2.6.
Check these names still exist when you upgrade FastMCP.

## License

[MIT](LICENSE)