Skip to content
Merged
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
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ The substantive modules under `src/mcp_stdio/`:
- Signal handlers (`signal.signal`) are set from the main thread only — both transports now run daemon threads (`run_sse`'s SSE reader; `run()`'s modern-era listen/resource streams and stdin reader; `run()`'s OAuth proactive-refresh and cold-start daemons, on either era), so pytest tests must drive `run()` and `run_sse` from the main thread.
- **`cli.py`** — argparse-based CLI. Builds headers, resolves `MCP_BEARER_TOKEN` / `MCP_OAUTH_CLIENT_ID` env vars, runs the OAuth flow before relay if `--oauth` or `--oauth-device` is set, and dispatches to `run()` or `run_sse()` based on `--transport`.
- **`oauth.py`** — OAuth 2.1 client: RFC 9728/8414 discovery, RFC 7591 dynamic client registration, RFC 7636 PKCE, RFC 8707 resource indicators, authorization code flow with localhost callback server, RFC 8628 device authorization grant, RFC 9470 step-up authorization, token exchange and refresh.
- **`token_store.py`** — Token persistence in `~/.config/mcp-stdio/tokens.json` (0o600). Stores per-server-URL tokens with client credentials and endpoint URLs for refresh. Migrates legacy `~/.mcp-stdio/` tokens on first read.
- **`token_store.py`** — Token persistence in `~/.config/mcp-stdio/tokens.json` (0o600). Stores per-server-URL tokens with client credentials and endpoint URLs for refresh. Migrates legacy `~/.mcp-stdio/` tokens on first read. Two lock files: `_store_lock` (blocking, NOT re-entrant) around each save/delete, and `refresh_lock` (bounded 30 s wait, then unlocked with a warning) around `oauth._refresh_cached_token_ex`'s load → exchange → save so concurrent relay processes never spend the same rotating refresh token (#454); `delete_token(expected_refresh_token=...)` is compare-and-delete.
- **`server.py`** — the `mcp-stdio serve` reverse gateway (dispatched from `cli.py` when `argv[1] == "serve"`). **Dual-era** since #270 Phase 3: one endpoint answers both revisions, and `_request_era()` classifies each POST body conservatively — modern only on positive evidence (`params._meta` carries the `protocolVersion` KEY, or the method is `server/discover`); everything else falls through to the untouched legacy path.
- **Legacy path (unchanged, AC2).** One backend stdio child per MCP session (`SessionRegistry`, keyed on `Mcp-Session-Id`) over a stdlib `http.server` Streamable HTTP endpoint: session minted on `initialize`, 400 sessionless, 404 on an unknown id, DELETE to terminate, GET SSE for server-initiated messages. Pinned byte-for-byte by `tests_integration/test_serve_legacy_pin.py`, which every Phase 3 PR had to keep green **with zero diffs**.
- **Modern path (2026-07-28).** A request-plane validation ladder (`_validate_modern`; first failure wins, in python-sdk v2's order — the header rungs run BEFORE the unsupported-version rung): required `_meta` → `-32602`; `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` agreement, the last sentinel-decoded via relay's `_decode_mcp_name` → `-32020`; unsupported version → `-32022` with `data.supported`. Notifications are exempt from the ladder entirely (O9). `_dispatch_modern` then serves the request statelessly from a `ModernBackendPool` child, keyed on the **authenticated principal and NOT on a session** (one shared child under no-auth or a static token, one per OAuth user), with the gateway performing the `initialize` + `notifications/initialized` handshake the modern wire omits and caching the result. `server/discover` is synthesised locally and never forwarded (a legacy child would answer `-32601`); every modern result is stamped `resultType: "complete"`, the six cacheable ops additionally get `ttlMs` (`--cache-ttl-ms`, default 60000) / `cacheScope: "private"`, and every result carries the child's `serverInfo` under `_meta`. Client ids are remapped to a minted `mcp-stdio/serve/` id so concurrent stateless clients sharing one child cannot collide. `subscriptions/listen` is SERVED by serve itself, never forwarded: SCOPE is the listChanged trio (`_LISTEN_FILTER_METHODS`, #374) plus `resourceSubscriptions` (#381, detailed below), honor-all on the three booleans, attach-BEFORE-ack, ack as frame 1 with the honored subset at `params.notifications` and the id at `params._meta[subscriptionId]` (both nestings are load-bearing — a top-level echo is silently ignored by a compliant client). Every frame is stamped with the subscription id. `BackendProcess` fans notifications out to attached `_ListenStream`s (filtering on the reader thread, bounded 1024-deep queue per stream, ≤4 streams per pooled child → `-32603`/503 pre-ack). Endings: gateway shutdown → terminal `resultType: "complete"` frame then close (`signal_end(graceful=True)` + a bounded `drain_listeners`); child death or backlog overflow → abrupt close with NO terminal frame; NEVER a server-sent `notifications/cancelled` (the v2 client settles that as LOST). First ending wins. **#381 added the fourth field, `resourceSubscriptions`**: honoring is entirely LOCAL (child's advertised `resources.subscribe` via `_child_supports_resource_subscribe`, then sanitize + dedup + cap at `_LISTEN_MAX_RESOURCE_SUBSCRIPTIONS=256` with truncate-and-honor), so the ack ships BEFORE any `resources/subscribe` is driven — the drive runs on a background daemon thread and can never stall the ack or the pump. `notifications/resources/updated` gets its OWN routing branch (never folded into `_LISTEN_FORWARDED_METHODS`, which would make any non-empty URI list match every URI and leak across streams); matching is exact string equality, no normalization. URIs are refcounted per child in `BackendProcess._resource_refs` under a dedicated `_sub_lock` HELD ACROSS the send (order `_sub_lock` -> `_lock`, never reversed): subscribe on the first reference, unsubscribe on the last, ids from the existing `_mint_modern_id()`. `_ListenStream.torn_down` closes the async-drive-vs-sync-release race. Failure is reply-then-degrade (log once per URI per stream via `_ListenStream.subscribe_failure_logged`, #388 review, keep honored). `_UNDELIVERABLE_NOTIFICATION_FLAGS` still lists `resources.subscribe` as the DEFAULT, lifted per-child by `_synthesize_discover_result`'s `keep=` on the same predicate the ack uses. **O16 is closed by construction, zero production code**: `notifications/message` is never in any listen-forward set, serve's modern face has no other streaming channel to gate, and SEP-2577 deprecated the feature. Pool lifecycle (#376): entries carry a `holds` checkout refcount (taken by `get_or_create`, released in `_dispatch_modern`'s `finally`) which — together with `has_pending` and the PENDING check — forms the single `_reapable_locked` predicate shared by cap-eviction and the `modern-pool-reaper` idle thread (`--modern-idle-ttl`, 0 = off); `holds` is also #374's attach seam. `--modern-only` refuses legacy callers after the auth gate (GET/DELETE 405 + `Allow`, legacy `initialize` → `-32022`).
Expand Down
2 changes: 2 additions & 0 deletions WORKAROUNDS.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ Works around known issues in Claude Code's HTTP transport:
- **Each terminal re-runs the full OAuth flow** — credentials are keyed by the ephemeral localhost callback port chosen per process, so every new terminal is a cache miss that triggers a fresh browser round-trip and orphans the previous entry ([#43000](https://github.com/anthropics/claude-code/issues/43000)); mcp-stdio keys its token store by server URL in `~/.config/mcp-stdio/tokens.json`, shared across terminals and sessions.
- **Dynamic Client Registration repeated on every authenticate** — a fresh `POST /register` on each authentication orphans the previously issued `client_id` and its refresh token, contrary to the MCP authorization guidance to reuse registered credentials ([#59460](https://github.com/anthropics/claude-code/issues/59460)); mcp-stdio persists the client credentials alongside the tokens and reuses them on subsequent authentications, re-registering only when no client is cached or the stored client secret has passed its RFC 7591 `client_secret_expires_at`.
- **Rotated refresh token not persisted** — with authorization servers that issue a new refresh token on every exchange, the rotated token is not written back, so a subsequent refresh replays the already-consumed one and the session drops ([#66210](https://github.com/anthropics/claude-code/issues/66210)); mcp-stdio stores the rotated refresh token on every refresh (keeping the prior one only as an in-flight fallback).
- **Concurrent sessions replay a single-use refresh token** — several sessions sharing one stored token each refresh it on their own, so with single-use rotation the second one replays the token the first just spent and the identity provider rejects it, or revokes the whole token family ([#91641](https://github.com/anthropics/claude-code/issues/91641), [#93537](https://github.com/anthropics/claude-code/issues/93537)); mcp-stdio serializes each refresh across processes with a lock file and re-reads the store after taking it, so a process that finds a token another one just refreshed uses it instead of exchanging again, and every exchange uses the latest refresh token (#454).
- **A transient refresh failure discards the stored grant** — a network blip, a 5xx or `temporarily_unavailable` during refresh is treated like a revoked grant, throwing away a long-lived refresh token and forcing a new sign-in ([punkpeye/mcp-remote#348](https://github.com/punkpeye/mcp-remote/issues/348), [#349](https://github.com/punkpeye/mcp-remote/issues/349), [typescript-sdk#2915](https://github.com/modelcontextprotocol/typescript-sdk/issues/2915)); mcp-stdio deletes the stored token only when the authorization server's answer proves the grant dead (`invalid_grant`, `invalid_client`, other 4xx), and only if the stored refresh token is still the one that failed (#454).
- **OIDC `id_token` cannot be used as the Bearer token** — servers that validate an OIDC `id_token` at the edge (e.g. behind Google Cloud IAP) reject the opaque access token that is sent instead ([#70047](https://github.com/anthropics/claude-code/issues/70047)); mcp-stdio can present the `id_token` as the Bearer via `--oauth-use-id-token`.
- **Tokens without `expires_in` discarded early** — spec-valid long-lived tokens (e.g. GitHub, Todoist) are assigned an arbitrary client-side lifetime and dropped, after which a request is sent with no `Authorization` header at all ([#26281](https://github.com/anthropics/claude-code/issues/26281)); mcp-stdio treats a token response without `expires_in` as non-expiring and keeps sending it until the server itself returns 401.

Expand Down
Loading
Loading