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

One MCP endpoint in front of the self-hosted MCP servers. Each chat account connects once; a new backend
is added here and never requires touching the accounts again.

Endpoint: `https://mcp-gateway.yulin0629.workers.dev/mcp`, and `https://mcp-gateway.yulin0629.workers.dev/machines/mcp`
for shell on the owner's machines (see below).

## What a client sees

- **Three fixed tools.** `search_tools` (catalog and argument schemas), `call_tool` (read-only tools),
  `call_write_tool` (tools that change something). The list never changes, so clients that freeze the
  tool list at connect time still reach every backend, and the context cost stays constant.
- **Skills** (`io.modelcontextprotocol/skills`). One skill per backend, generated from its live tool list
  plus the notes in `src/backends.ts`. Clients load a skill only when they need that backend.
- **Events** (`io.modelcontextprotocol/events`). One event type, `tool_result.changed`: watch a read-only
  backend tool with fixed arguments and fire when its result changes. Delivery by poll (stateless, the
  cursor is the result hash) or webhook (signed with Standard Webhooks, checked on a Durable Object alarm).
  The whole result is compared, so a tool whose output carries live counters (Reddit scores) fires on
  almost every check. A revoked grant's webhook subscriptions run until they expire (at most 24 hours).
- **A failing backend is skipped.** Its tool list is retried once a minute (6 s limit); the other
  backends keep working and `search_tools` reports it as unavailable.
- **Both protocol eras.** MCP 2026-07-28 requests and the 2025-era `initialize` handshake on the same URL.

## Backends and profiles

`src/backends.ts` lists the backends. Each names the profiles that may reach it:

| Profile | Reaches |
|---|---|
| `personal` (default) | fxtwitter, reddit, discord, threads, facebook, agentmemory |
| `work` | azure-boards (company project data) |
| `machines` | devspace-m2, devspace-m4, devspace-mbp, devspace-oracle (shell on the owner's machines) and servers registered with `"profiles": ["machines"]`; only on `/machines/mcp` |
| `all` | every backend, the machines included |

The profile is chosen when an authorization is approved and stays with that grant.

The four `devspace-*` backends are DevSpace on the owner's machines. They run shell commands with the
owner's permissions, so a `machines` or `all` grant can run commands on all four machines. One connector per account is enough: approve it as `all`. The `all` connector also reads
untrusted web text (Reddit, X, Threads, Facebook, Discord), so what stands between that text and a shell
command is the client asking before each `call_write_tool` call (it is marked `destructiveHint: true`);
do not let a client run it without asking. A connector that should act on the owner's machines and nothing else uses
`/machines/mcp`: a grant there is always `machines`, and a grant on `/mcp` never is. The binding lives in `profilesFor()` in `src/oauth.ts` and `visible()` in
`src/backends.ts`.

Through the gateway DevSpace loses two things: its `initialize` instructions (the essentials are in each
backend's notes, which end up in its skill) and its UI panel (`_meta.ui.resourceUri`, the workspace and diff
view), because tool `_meta` and resources are not forwarded. A `tools/call` to DevSpace stops after 95 s,
before Cloudflare's 100 s origin limit; the command may still be running on the machine. Events cannot
watch DevSpace tools.

`scripts/devspace-parity.py` checks that nothing else differs. On each machine it compares DevSpace called
directly (over SSH) with DevSpace through `/machines/mcp`: the tool list (names, read-only flags, descriptions,
schemas), and one scenario of open, write, read, edit, bash, a large output, failures, an image and
show_changes. Run it after a change to the gateway or to DevSpace, from the MacBook Pro:
`python3 -I scripts/devspace-parity.py` (exit 0 = all four machines match).

`search_tools` with a query lists each tool once with `servers: [{ server, title }]`. A tool that is the same
(name, argument schema, read-only flag) on several servers is one entry naming all of them; pass exactly one
of those ids as `server`. A backend is listed only when a request needs it, so a sleeping machine delays
`search_tools` and the skills listing (up to 6 s, once a minute) but not a call to another backend.

To add a backend, register it; nothing here changes and nothing is redeployed. A server registers itself
when it starts, with the Access service token (scripts only, no `Origin`):

```bash
curl -s -X PUT https://mcp-gateway.yulin0629.workers.dev/backends/<id> \
  -H "CF-Access-Client-Id: <service token id>" -H "CF-Access-Client-Secret: <service token secret>" \
  -H 'Content-Type: application/json' \
  -d '{"url": "https://<host>/mcp", "token": "<Bearer the gateway sends>", "title": "...", "summary": "one line",
       "profiles": ["personal"], "notes": "guidance for its skill", "callTimeoutMs": 25000, "watchable": true}'
```

`url` and `token` are required; `profiles` defaults to `personal` (`all` reaches every backend anyway). The body
is at most 8 KB: a token up to 2048 characters, `title` and `summary` one line each, `notes` up to 1500 characters. The
same request again replaces the entry; `DELETE /backends/<id>` removes it (404 if it is not registered); `GET /backends` lists them without
tokens. The owner's Access session cookie (`-b <cookie jar>`) works in place of the two headers. Whoever holds
the service token can register, replace or remove a backend in any profile, so it stays on the owner's
machines; it cannot approve a grant. Every isolate reloads the list within 30 s. Registered backends and
their tokens live in the `OAuthState` Durable Object. A Worker on the same account is not reachable by its workers.dev URL from here
(Cloudflare blocks it): give it a custom domain and register that, or add it to `src/backends.ts` with a
service binding in `wrangler.jsonc`, a `wrangler secret put <TOKEN_ENV>` and a deploy. A built-in backend
whose token or URL secret is missing is reported as "not configured on the gateway" instead of failing the
gateway.

A tool call through an OAuth grant carries the chat product behind it (`claude-web`, `chatgpt-web`, `grok-web`,
`gemini-web`, from the callback the grant was issued through) in `X-AgentMemory-MCP-Client`; agentmemory adds it to the tags of a
saved lesson, and the other backends ignore it.

A backend must answer stateless MCP 2026-07-28 requests with Bearer authentication, and every tool must
carry `annotations.readOnlyHint`. A tool without `readOnlyHint: true` counts as a write: `call_tool`
refuses it and events cannot watch it.

## Authorization

Every client authenticates with an OAuth access token; there is no static token.

- OAuth: DCR + PKCE S256, state in the `OAuthState` Durable Object. Accepted callbacks: ChatGPT,
  Claude (`claude.ai` and `claude.com`), Grok, Gemini (six user-bound `oauth-redirect*.googleusercontent.com`
  callbacks in one registration, so a registration may carry up to 8). Refused registrations are logged
  (`wrangler tail`) to find a new client's callback. Client ID Metadata Documents are not advertised, because
  ChatGPT switches to them as soon as a server does and its fetch of the metadata has failed before.
- Approving a flow: `/oauth/approve` sits behind a Cloudflare Access app (paths `/oauth/approve` and
  `/backends` on the gateway's hostname; one policy lets the owner in by email code, another lets the
  registration service token in). The Worker also checks the JWT Access adds
  (`Cf-Access-Jwt-Assertion`: signature from the team's certs, issuer, audience, expiry), so a request that did
  not pass Access is refused, and it approves only for a JWT that carries the owner's login (an email), never for
  the service token. The consent page links to the approval page; after the Access login, pick a
  profile there. Or script it with an Access session cookie, sending no `Origin`:

  ```bash
  curl -s -b <Access session cookie jar> https://mcp-gateway.yulin0629.workers.dev/oauth/approve \
    --data-urlencode "flow=<flow from the consent page's /oauth/approve?flow= link>" --data-urlencode "profile=personal"
  ```

  The response is `{"redirect": "..."}`; send the browser there. A `/machines/mcp` flow needs no `profile`
  (it is always `machines`). A POST with any other `Origin` than the gateway is refused.
- A grant lasts 30 days from its last refresh, and at most a year from approval. Refresh tokens rotate; replaying
  a used one revokes the grant.
- Every grant carries `OAUTH_GENERATION`; setting a new value revokes every grant at once.

## Secrets

| Worker secret | Value |
|---|---|
| `OAUTH_GENERATION` | stamped on every grant; a new value revokes all of them |
| `ACCESS_TEAM_DOMAIN` | the Access team domain (`<team>.cloudflareaccess.com`) |
| `ACCESS_AUD` | the Application Audience (AUD) tag of the Access app in front of `/oauth/approve` |
| `FXTWITTER_TOKEN` | fxtwitter-mcp's `MCP_BEARER_TOKEN` |
| `REDDITAPIS_TOKEN`, `DISCORD_TOKEN`, `AZURE_BOARDS_TOKEN`, `THREADS_TOKEN`, `FACEBOOK_TOKEN` | the `GATEWAY_TOKEN` secret set on those Workers |
| `DEVSPACE_M2_TOKEN`, `DEVSPACE_M4_TOKEN`, `DEVSPACE_MBP_TOKEN`, `DEVSPACE_ORACLE_TOKEN` | `staticBearerToken` in `~/.devspace/auth.json` on that machine |
| `DEVSPACE_M2_URL`, `DEVSPACE_M4_URL`, `DEVSPACE_MBP_URL`, `DEVSPACE_ORACLE_URL` | that machine's DevSpace MCP endpoint (`https://<host>/mcp`) |
| `AGENTMEMORY_TOKEN` | agentmemory-mcp's Bearer |
| `AGENTMEMORY_URL` | agentmemory-mcp's endpoint |

## Development

```bash
npm ci
npm run types
npm run check
npm test
```