Skip to content

Add opt-in CORS for the MCP proxy endpoint - #7413

Draft
DevamShah wants to merge 1 commit into
stacklok:mainfrom
DevamShah:fix/4297-cors
Draft

DevamShah wants to merge 1 commit into
stacklok:mainfrom
DevamShah:fix/4297-cors

Conversation

@DevamShah

Copy link
Copy Markdown

Summary

Browser-based MCP clients (e.g. the MCP Inspector) cannot connect to the ToolHive proxy. The streamable-HTTP /mcp endpoint answers an OPTIONS preflight with 405 Method Not Allowed and sets no Access-Control-Allow-Origin, and even a handled preflight would be rejected by the pre-auth Origin guard (403) before any CORS layer ran — so the connection fails in the browser.

This adds opt-in CORS derived from the existing --allowed-origins allowlist (no new flag), wired on the thv run and thv proxy paths only.

  • New pkg/transport/middleware/cors package. CORS is placed just outside Origin validation so a genuine preflight (OPTIONS carrying Access-Control-Request-Method) from an allowed origin is answered with 204 and the modern MCP headers before the Origin guard sees it.
  • Emits Mcp-Session-Id, Mcp-Protocol-Version and Last-Event-ID in the preflight allow-headers, the standard allow-methods/credentials/max-age, and exposes WWW-Authenticate via Access-Control-Expose-Headers so a browser client can read the OAuth challenge.
  • Reconciles with CORS headers an upstream handler or reverse-proxied backend already set: actual-response headers are injected at WriteHeader time and only when Access-Control-Allow-Origin is still absent, so an upstream policy is preserved rather than double-set.
  • Only genuine preflights are short-circuited; everything else (bare OPTIONS, preflight from a disallowed origin, all actual requests) passes through. A preflight from a disallowed origin still reaches the Origin guard and gets 403.
  • Because CORS reads the same list as the Origin validator (matched via the shared origin.CanonicalizeOrigin), it can never grant an origin the validator would reject — CORS is a strict subset.

Fixes #4297

Type of change

  • New feature

Test plan

  • Unit tests (task test) — new cors package tests cover preflight short-circuit, pass-through of non-preflight/disallowed/bare-OPTIONS, actual-response decoration, upstream-CORS reconciliation, http.Flusher passthrough for SSE, Vary de-duplication, case-insensitive origin matching, and the factory. Ran with -race. origin, runner, and cmd/thv/app suites still pass.
  • Linting (task lint-fix) — golangci-lint v2.15.0 (the CI-pinned version) with the repo config: 0 issues.
  • E2E tests (task test-e2e) — not run locally.
  • Manual testing — browser Inspector repro not yet run (see reviewer checklist).

API Compatibility

  • This PR does not break the v1beta1 API.

Does this introduce a user-facing change?

Yes. On the thv run and thv proxy paths, when the effective Origin allowlist is non-empty (an explicit --allowed-origins, or a loopback-bind default):

  • Before: a CORS preflight (OPTIONS /mcp with Access-Control-Request-Method) returned 405 with no CORS headers; browser clients were blocked.
  • After: a preflight from an allowed origin returns 204 with Access-Control-Allow-* headers (including the modern MCP headers) and Access-Control-Expose-Headers: … WWW-Authenticate; actual responses from an allowed origin carry Access-Control-Allow-Origin. Disallowed origins are unaffected (still 403 at the Origin guard). No behavior change when the allowlist is empty.

The MCP Inspector on :6274 reaching a loopback proxy still requires naming the browser origin, since the loopback default only covers the proxy's own origin:

thv run --allowed-origins http://localhost:6274 my-server

Documented in docs/middleware.md (new component section 14 + the execution-order note).

Special notes for reviewers

  • Ordering: thv run wires CORS via prependCorsMiddleware in pkg/runner (called right after prependOriginMiddleware in runner.Run); thv proxy via the new appendOriginMiddlewares helper in cmd/thv/app/proxy.go. Final outer-to-inner order is body-limit → CORS → Origin → rest. The CORS middleware reaches stdio (streamable proxy), SSE/streamable-HTTP (transparent proxy) and thv proxy from these two seams, matching where Origin validation is already applied.
  • SSE: the response-writer wrapper implements http.Flusher directly (not via Unwrap) because the streamable SSE path type-asserts the writer to http.Flusher; a test pins this.
  • vmcp server's /mcp is intentionally left out of scope, matching the issue discussion.

Checklist for @DevamShah before marking ready

  • Run the ToolHive MCP proxy endpoint does not support CORS #4297 repro: thv run --allowed-origins http://localhost:6274 <server>, point the MCP Inspector (:6274) at the proxy /mcp URL, confirm the preflight returns 204 and the connection succeeds.
  • Confirm the stdio path specifically (the streamable proxy that previously returned 405), plus an SSE/streamable-HTTP container and a standalone thv proxy.
  • Decide whether Access-Control-Allow-Credentials: true is desired, or whether it should be gated/omitted for this endpoint.
  • Confirm the allow-headers / expose-headers lists match what maintainers want (the review on Handle CORS preflight for MCP proxy #6669 is the reference direction).
  • Run task test-e2e and task lint-fix in the real toolhive dev environment.
  • Consider an E2E test exercising the preflight, if maintainers want one.

🤖 Generated with Claude Code

Browser-based MCP clients such as the MCP Inspector cannot reach the
ToolHive proxy: the streamable-HTTP /mcp endpoint answers an OPTIONS
preflight with 405 and sets no Access-Control-Allow-Origin, and even a
handled preflight would be rejected by the pre-auth Origin guard before
any CORS layer ran.

Add a CORS middleware derived from the existing --allowed-origins
allowlist (no new flag). It is wired on the `thv run` and `thv proxy`
paths just outside Origin validation, so a genuine preflight (OPTIONS
carrying Access-Control-Request-Method) from an allowed origin is
answered with 204 and the modern MCP headers (Mcp-Session-Id,
Mcp-Protocol-Version, Last-Event-ID) before the Origin guard sees it.
Because CORS reads the same list as the Origin validator, it can never
grant an origin the validator would reject.

Every other request passes through unchanged; a preflight from a
disallowed origin still reaches the Origin guard and gets 403. Actual
responses are decorated with Access-Control-Allow-Origin and expose
WWW-Authenticate, set only when an upstream handler or reverse-proxied
backend has not already set them, so an upstream CORS policy is
preserved rather than double-set.

Fixes stacklok#4297

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ToolHive MCP proxy endpoint does not support CORS

1 participant