Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(ok): route /mcp through the native mount (PRD-8397) (#3925)

omar-inkeep4ca35d772556
diff --git a/packages/server/src/http/admit-request-surface.test.ts b/packages/server/src/http/admit-request-surface.test.ts
index 798d2da6f..61806fadb 100644
--- a/packages/server/src/http/admit-request-surface.test.ts
+++ b/packages/server/src/http/admit-request-surface.test.ts
@@ -56,14 +56,14 @@ describe('admitRequestSurface under allowExternal consent', () => {
test('admits loopback, the bind literal, and the declared externalUrl host', () => {
for (const host of ['localhost:5173', '100.64.0.7:55222', 'laptop.tail:55222']) {
const { res, status } = fakeRes();
- expect(admitRequestSurface(req(host), res, consentPolicy, 'test')).toBe(true);
+ expect(admitRequestSurface(req(host), res, consentPolicy, 'mcp-mount')).toBe(true);
expect(status()).toBeUndefined();
}
});
test('refuses a foreign Host (rebinding shape) with a 403', () => {
const { res, status } = fakeRes();
- expect(admitRequestSurface(req('evil.example'), res, consentPolicy, 'test')).toBe(false);
+ expect(admitRequestSurface(req('evil.example'), res, consentPolicy, 'mcp-mount')).toBe(false);
expect(status()).toBe(403);
});
@@ -78,7 +78,7 @@ describe('admitRequestSurface under allowExternal consent', () => {
req('localhost', '127.0.0.1', { 'x-forwarded-for': '203.0.113.7' }),
res,
buildIngressPolicy({}),
- 'test',
+ 'mcp-mount',
),
).toBe(false);
expect(status()).toBe(403);
@@ -94,7 +94,7 @@ describe('admitRequestSurface under allowExternal consent', () => {
req('laptop.tail:55222', '100.64.0.7', { 'x-forwarded-for': '203.0.113.7' }),
res,
consentPolicy,
- 'test',
+ 'mcp-mount',
),
).toBe(true);
expect(status()).toBeUndefined();
@@ -108,7 +108,7 @@ describe('admitRequestSurface under allowExternal consent', () => {
// deliberately ungated — public bundle code.
const local = buildIngressPolicy({});
const { res, status } = fakeRes();
- expect(admitRequestSurface(req('evil.example'), res, local, 'test')).toBe(true);
+ expect(admitRequestSurface(req('evil.example'), res, local, 'mcp-mount')).toBe(true);
expect(status()).toBeUndefined();
});
});
diff --git a/packages/server/src/http/http-app.test.ts b/packages/server/src/http/http-app.test.ts
index 3d7e39b0b..5525d11cf 100644
--- a/packages/server/src/http/http-app.test.ts
+++ b/packages/server/src/http/http-app.test.ts
@@ -1,11 +1,14 @@
-import { createServer } from 'node:http';
+import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { describe, expect, test } from 'vitest';
+import { rawRequest } from '../composition-rig.test-helper.ts';
+import { buildIngressPolicy } from '../ingress-policy.ts';
import { listenOnLoopback } from '../loopback-rig-test-helpers.ts';
import {
assertSingleRouterOwnership,
type CreateHttpAppOptions,
createHttpApp,
} from './http-app.ts';
+import { createMcpDispatch } from './mcp-route.ts';
/**
* Adapter-boundary pins the composition suite cannot see: these assert
@@ -22,12 +25,22 @@ const fakeLog = {
child: () => fakeLog,
} as never;
-async function serveWith(legacyDispatch: CreateHttpAppOptions['legacyDispatch']) {
- const { requestListener } = createHttpApp({ legacyDispatch, log: fakeLog });
+async function serveWith(
+ legacyDispatch: CreateHttpAppOptions['legacyDispatch'],
+ mcpDispatch?: CreateHttpAppOptions['mcpDispatch'],
+ ingressPolicy?: CreateHttpAppOptions['ingressPolicy'],
+) {
+ const { requestListener } = createHttpApp({
+ legacyDispatch,
+ mcpDispatch,
+ ingressPolicy,
+ log: fakeLog,
+ });
const server = createServer(requestListener);
const { baseUrl } = await listenOnLoopback(server);
return {
baseUrl,
+ port: Number(new URL(baseUrl).port),
close: () =>
new Promise<void>((resolvePromise, reject) => {
server.close((err) => (err ? reject(err) : resolvePromise()));
@@ -92,6 +105,95 @@ describe('createHttpApp adapter boundary', () => {
});
});
+describe('createHttpApp native /mcp mount', () => {
+ // ONE policy object for both the dispatch closure and createHttpApp —
+ // the leg's gates and the surface prelude are two layers of one admission
+ // decision (see createMcpDispatch's docblock), and the rig models that.
+ const policy = buildIngressPolicy({});
+
+ function mcpDispatchOver(handle: (req: IncomingMessage, res: ServerResponse) => Promise<void>) {
+ return createMcpDispatch({ handle, close: async () => {} }, policy, fakeLog);
+ }
+
+ test('/mcp serves from the native route with zero legacy-dispatch involvement', async () => {
+ let legacyCalls = 0;
+ let handled = 0;
+ const dispatch = mcpDispatchOver(async (_req, res) => {
+ handled += 1;
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end('{}');
+ });
+ const rig = await serveWith(
+ (_req, res) => {
+ legacyCalls += 1;
+ res.writeHead(204);
+ res.end();
+ },
+ dispatch,
+ policy,
+ );
+ try {
+ const res = await fetch(`${rig.baseUrl}/mcp`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: '{}',
+ });
+ expect(res.status).toBe(200);
+ expect(handled).toBe(1);
+ expect(legacyCalls).toBe(0);
+ } finally {
+ await rig.close();
+ }
+ });
+
+ test('a Hono-normalized alias of /mcp falls through to the legacy dispatch', async () => {
+ // `/./mcp` normalizes to `/mcp` inside the router, but the raw URL is what
+ // the legacy dispatch always matched — the alias must keep its historical
+ // legacy-dispatch answer instead of reaching the MCP handler.
+ let handled = 0;
+ let legacyUrl: string | undefined;
+ const dispatch = mcpDispatchOver(async (_req, res) => {
+ handled += 1;
+ res.writeHead(200);
+ res.end();
+ });
+ const rig = await serveWith(
+ (req, res) => {
+ legacyUrl = req.url;
+ res.writeHead(404);
+ res.end();
+ },
+ dispatch,
+ policy,
+ );
+ try {
+ // fetch normalizes dot segments client-side; drive the raw path.
+ const res = await rawRequest(rig.port, '/./mcp', { method: 'POST' });
+ expect(res.status).toBe(404);
+ expect(handled).toBe(0);
+ expect(legacyUrl).toBe('/./mcp');
+ } finally {
+ await rig.close();
+ }
+ });
+
+ test('without an MCP handler /mcp falls through the strangler catch-all', async () => {
+ let legacyUrl: string | undefined;
+ const rig = await serveWith((req, res) => {
+ legacyUrl = req.url;
+ res.writeHead(404);
+ res.end();
+ });
+ try {
+ const res = await fetch(`${rig.baseUrl}/mcp`, { method: 'POST' });
+ expect(res.status).toBe(404);
+ expect(legacyUrl).toBe('/mcp');
+ } finally {
+ await rig.close();
+ }
+ });
+});
+
describe('assertSingleRouterOwnership', () => {
test('throws when a native path also exists in the legacy record', () => {
expect(() =>
diff --git a/packages/server/src/http/http-app.ts b/packages/server/src/http/http-app.ts
index 6c754b16e..cc71bf493 100644
--- a/packages/server/src/http/http-app.ts
+++ b/packages/server/src/http/http-app.ts
@@ -11,6 +11,7 @@ import {
} from '../ingress-policy.ts';
import type { PinoLogger } from '../logger.ts';
import { errorResponse } from './error-response.ts';
+import type { McpDispatch } from './mcp-route.ts';
/**
* The canonical HTTP application, introduced strangler-fig style: a Hono app
@@ -54,11 +55,12 @@ export interface NativeApiHandle {
/**
* The surface-wide admission prelude every request runs before dispatch —
- * shared verbatim between the legacy `mcp-mount` dispatch and natively-mounted
- * `/api/*` routes (which sit above the strangler catch-all and would otherwise
- * bypass it). Returns `false` after writing the 403 when the request is
- * refused. Both gates consult the ONE boot-built `IngressPolicy` — the same
- * object the WS upgrade path and per-route gates consume.
+ * shared verbatim between the legacy `mcp-mount` dispatch and the
+ * natively-mounted `/mcp` route and `/api/*` groups (which sit above the
+ * strangler catch-all and would otherwise bypass it). Returns `false` after
+ * writing the 403 when the request is refused. Both gates consult the ONE
+ * boot-built `IngressPolicy` — the same object the WS upgrade path and
+ * per-route gates consume.
*
* Gate 1 — tripwire: proxy-forwarding headers the policy does not tolerate
* mean a tunnel is pointed at a server that never opted into exposure.
@@ -72,15 +74,19 @@ export interface NativeApiHandle {
* failures.
*
* `handler` is the caller's tag on the `ok.api.error.count` counter for
- * rejections ('mcp-mount' for the legacy dispatch, 'native-api-surface' for
- * the native mount) — the primary triage dimension, so refusals attribute to
- * the surface that actually refused.
+ * rejections ('mcp-mount' for the legacy dispatch, 'native-mcp-surface' for
+ * the native /mcp route, 'native-api-surface' for the native /api groups) —
+ * the primary triage dimension, so refusals attribute to the surface that
+ * actually refused. The closed union keeps a typo'd tag at a future call
+ * site from silently minting an uncorrelated metric series.
*/
+export type SurfaceAdmissionCaller = 'mcp-mount' | 'native-api-surface' | 'native-mcp-surface';
+
export function admitRequestSurface(
req: IncomingMessage,
res: ServerResponse,
policy: IngressPolicy,
- handler: string,
+ handler: SurfaceAdmissionCaller,
): boolean {
if (tripsForwardedHeaderTripwire(req, policy)) {
errorResponse(
@@ -180,6 +186,15 @@ export interface CreateHttpAppOptions {
* behavior while never reaching the legacy dispatch.
*/
nativeApi?: NativeApiHandle;
+ /**
+ * The bound `/mcp` dispatch (`createMcpDispatch` in `mcp-route.ts`) for the
+ * natively-mounted `/mcp` route — injected like `nativeApi.dispatch`, so
+ * this module stays a composition layer with no MCP semantics. When
+ * omitted, `/mcp` is NOT mounted and the URL falls through the strangler
+ * catch-all like any other unclaimed path — the restartable test harness
+ * and ephemeral single-file mode take this path.
+ */
+ mcpDispatch?: McpDispatch;
/**
* The boot-built ingress policy for the surface admission gates on native
* routes (same object the mount applies to the legacy dispatch). Omitted
@@ -263,11 +278,44 @@ export function createHttpApp(opts: CreateHttpAppOptions): HttpAppHandle {
});
}
+ const ingressPolicy = opts.ingressPolicy ?? buildIngressPolicy({});
+
+ // The natively-mounted /mcp route, ABOVE the strangler catch-all. Once the
+ // raw path is confirmed to be exactly `/mcp` (below), admission ordering
+ // matches the legacy dispatch: the surface prelude first (tripwire +
+ // remote-admit pair), then the leg's own unconditional gates.
+ const mcpDispatch = opts.mcpDispatch;
+ if (mcpDispatch !== undefined) {
+ app.all('/mcp', (c) => {
+ const req = c.env.incoming;
+ const res = c.env.outgoing;
+ // Hono routes on a NORMALIZED path (dot segments resolved, non-reserved
+ // percent-escapes decoded), while the legacy dispatch matched the raw
+ // `req.url` exactly. Re-derive the raw path and decline mismatches
+ // (`/./mcp`, `/mc%70`) to the legacy dispatch, which serves them the
+ // same static-fallback/404 it always has — mirrors the native /api
+ // groups' table-decline fall-through. (An app-wide raw-path `getPath`
+ // on the Hono constructor would make this guard unnecessary, but it
+ // was considered and deferred: it also flips `/./healthz`-style
+ // aliases on the ALWAYS-mounted health routes from natively served to
+ // legacy 404s, a behavior change out of scope for a byte-parity wave.)
+ const url = req.url?.split('?')[0];
+ if (url !== '/mcp') {
+ opts.legacyDispatch(req, res);
+ return RESPONSE_ALREADY_SENT;
+ }
+ if (!admitRequestSurface(req, res, ingressPolicy, 'native-mcp-surface')) {
+ return RESPONSE_ALREADY_SENT;
+ }
+ mcpDispatch(req, res);
+ return RESPONSE_ALREADY_SENT;
+ });
+ }
+
// Natively-served /api/* routes, ABOVE the strangler catch-all. Each runs
// the surface admission gates first (the tripwire + remote-admit pair the
// legacy dispatch applies in mcp-mount's onRequest), then the shared
// /api/* pipeline — request-id, CORS, DNS-rebinding gates, dispatch span.
- const ingressPolicy = opts.ingressPolicy ?? buildIngressPolicy({});
const nativeApi = opts.nativeApi;
if (nativeApi !== undefined) {
for (const path of nativeApi.paths) {
diff --git a/packages/server/src/http/mcp-route.test.ts b/packages/server/src/http/mcp-route.test.ts
new file mode 100644
index 000000000..fc604f7ca
--- /dev/null
+++ b/packages/server/src/http/mcp-route.test.ts
@@ -0,0 +1,106 @@
+import { createServer, type Server as HttpServer } from 'node:http';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { buildIngressPolicy } from '../ingress-policy.ts';
+import { listenOnLoopback } from '../loopback-rig-test-helpers.ts';
+import type { McpHttpHandler } from '../mcp-http.ts';
+import { createMcpDispatch } from './mcp-route.ts';
+
+// The dispatch is fire-and-forget, so its `.catch()` is the ONLY error
+// surface for the leg — a rejected `handle` must terminate the response on
+// every branch (typed 500 before any write, plain end after a partial write,
+// log-only after a completed one) or the client hangs until requestTimeout.
+
+const log = {
+ error: vi.fn(),
+ warn: () => {},
+ info: () => {},
+ debug: () => {},
+ child: () => log,
+};
+
+let servers: HttpServer[] = [];
+
+afterEach(async () => {
+ const active = servers;
+ servers = [];
+ vi.mocked(log.error).mockClear();
+ await Promise.allSettled(
+ active.map((server) => new Promise<void>((resolve) => server.close(() => resolve()))),
+ );
+});
+
+async function serveDispatch(handle: McpHttpHandler['handle']): Promise<{ baseUrl: string }> {
+ const dispatch = createMcpDispatch(
+ { handle, close: async () => {} },
+ buildIngressPolicy({}),
+ log as never,
+ );
+ const server = createServer((req, res) => dispatch(req, res));
+ const { baseUrl } = await listenOnLoopback(server);
+ servers.push(server);
+ return { baseUrl };
+}
+
+describe('createMcpDispatch rejected-handle error surface', () => {
+ test('a rejection before any write emits the typed 500 problem+json', async () => {
+ const { baseUrl } = await serveDispatch(async () => {
+ throw new Error('sdk exploded before writing');
+ });
+
+ const res = await fetch(`${baseUrl}/mcp`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: '{}',
+ signal: AbortSignal.timeout(5_000),
+ });
+
+ expect(res.status).toBe(500);
+ expect(res.headers.get('content-type')).toBe('application/problem+json');
+ const body = (await res.json()) as { type?: string; status?: number };
+ expect(body.type).toBe('urn:ok:error:internal-server-error');
+ expect(body.status).toBe(500);
+ });
+
+ test('a rejection after a partial write ends the response instead of hanging', async () => {
+ const { baseUrl } = await serveDispatch(async (_req, res) => {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.write('{"partial":');
+ throw new Error('sdk exploded mid-write');
+ });
+
+ // A hang here would leave the fetch pending until the abort fires.
+ const res = await fetch(`${baseUrl}/mcp`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: '{}',
+ signal: AbortSignal.timeout(5_000),
+ });
+
+ expect(res.status).toBe(200);
+ expect(await res.text()).toBe('{"partial":');
+ });
+
+ test('a rejection after the response completed is log-only', async () => {
+ const { baseUrl } = await serveDispatch(async (_req, res) => {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end('{}');
+ throw new Error('sdk exploded post-response');
+ });
+
+ const res = await fetch(`${baseUrl}/mcp`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: '{}',
+ signal: AbortSignal.timeout(5_000),
+ });
+
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({});
+ await vi.waitFor(() => {
+ expect(log.error).toHaveBeenCalledWith(
+ expect.objectContaining({ err: expect.any(Error) }),
+ 'Unhandled MCP HTTP error',
+ );
+ });
+ });
+});
diff --git a/packages/server/src/http/mcp-route.ts b/packages/server/src/http/mcp-route.ts
new file mode 100644
index 000000000..3cedf7a33
--- /dev/null
+++ b/packages/server/src/http/mcp-route.ts
@@ -0,0 +1,106 @@
+/**
+ * The `/mcp` Streamable HTTP leg, injected into the canonical Hono app so
+ * `createHttpApp` stays a composition layer with no MCP semantics — the same
+ * principle behind `NativeApiHandle`, though a different shape. Picking a
+ * shape for a later surface: `NativeApiHandle` is for multi-path groups that
+ * need a decline concept (its `dispatch` reports whether the table claimed
+ * the URL); this leg is a bare fire-and-forget function because it has one
+ * fixed path, no fallthrough of its own, and a response lifetime the MCP SDK
+ * owns.
+ */
+
+import type { IncomingMessage, ServerResponse } from 'node:http';
+import {
+ HOST_NOT_ADMITTED_REMEDIATION,
+ type IngressPolicy,
+ isHostAdmitted,
+ isOriginAdmitted,
+ isPeerAdmitted,
+} from '../ingress-policy.ts';
+import type { PinoLogger } from '../logger.ts';
+import type { McpHttpHandler } from '../mcp-http.ts';
+import { errorResponse } from './error-response.ts';
+
+const MCP_CORS_HEADERS = {
+ 'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS',
+ 'Access-Control-Allow-Headers':
+ 'Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version',
+ // 24 h preflight cache — prevents a round-trip OPTIONS on every sequential tool call.
+ 'Access-Control-Max-Age': '86400',
+};
+
+/** The bound `/mcp` dispatch `createHttpApp` mounts behind its route claim. */
+export type McpDispatch = (req: IncomingMessage, res: ServerResponse) => void;
+
+/**
+ * Bind the `/mcp` leg: unconditional peer + Host + Origin gates, the MCP
+ * CORS headers, the OPTIONS preflight, and the raw `req`/`res` handoff to
+ * the MCP SDK transport. `policy` MUST be the same object `createHttpApp`
+ * receives as `ingressPolicy` — the surface prelude and these gates are two
+ * layers of one admission decision, and a mount that rebuilds one of them
+ * over a different policy would refuse externally-admitted `/mcp` calls
+ * while `/api` serves them. A mount that diverges here turns the
+ * tunnel-Host `/mcp` admission test in `remote-mcp.test.ts` red: the
+ * exposed prelude admits the tunnel Host while a default-policy leg's own
+ * Host gate refuses it. The handoff is fire-and-forget on purpose: a
+ * session `GET` opens the transport's standalone SSE channel
+ * (`Content-Type: text/event-stream`, held open for server-initiated
+ * notifications — `enableJsonResponse` shapes POST responses only), so the
+ * SDK owns the response lifetime and this dispatch must not await it or
+ * buffer it through an adapter.
+ */
+export function createMcpDispatch(
+ mcpHttpHandler: McpHttpHandler,
+ policy: IngressPolicy,
+ log: PinoLogger,
+): McpDispatch {
+ return (req, res) => {
+ const origin = req.headers.origin;
+ const sessionId = Array.isArray(req.headers['mcp-session-id'])
+ ? req.headers['mcp-session-id'][0]
+ : req.headers['mcp-session-id'];
+ // The policy's peer + Host gate pair.
+ if (!isPeerAdmitted(req.socket.remoteAddress, policy)) {
+ errorResponse(res, 403, 'urn:ok:error:loopback-required', 'Loopback required.', {
+ handler: 'mcp',
+ });
+ return;
+ }
+ if (!isHostAdmitted(req.headers.host, policy)) {
+ errorResponse(res, 403, 'urn:ok:error:host-not-allowed', 'Host header not allowed.', {
+ handler: 'mcp',
+ detail: HOST_NOT_ADMITTED_REMEDIATION,
+ });
+ return;
+ }
+ if (origin !== undefined && !isOriginAdmitted(origin, policy)) {
+ errorResponse(res, 403, 'urn:ok:error:invalid-origin', 'Origin not allowed.', {
+ handler: 'mcp',
+ });
+ return;
+ }
+ if (origin !== undefined) {
+ res.setHeader('Access-Control-Allow-Origin', origin);
+ res.setHeader('Vary', 'Origin');
+ }
+ for (const [header, value] of Object.entries(MCP_CORS_HEADERS)) {
+ res.setHeader(header, value);
+ }
+ if (req.method === 'OPTIONS') {
+ res.writeHead(204);
+ res.end();
+ return;
+ }
+ mcpHttpHandler.handle(req, res).catch((err) => {
+ log.error({ err, sessionId }, 'Unhandled MCP HTTP error');
+ if (!res.writableEnded && !res.headersSent) {
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Internal server error.', {
+ handler: 'mcp',
+ cause: err,
+ });
+ } else if (!res.writableEnded) {
+ res.end();
+ }
+ });
+ };
+}
diff --git a/packages/server/src/mcp-mount.ts b/packages/server/src/mcp-mount.ts
index dff15ed63..eb1bcdd6d 100644
--- a/packages/server/src/mcp-mount.ts
+++ b/packages/server/src/mcp-mount.ts
@@ -36,12 +36,12 @@ import {
type HealthProvider,
type NativeApiHandle,
} from './http/http-app.ts';
+import { createMcpDispatch } from './http/mcp-route.ts';
import {
buildIngressPolicy,
HOST_NOT_ADMITTED_REMEDIATION,
type IngressPolicy,
isHostAdmitted,
- isOriginAdmitted,
isPeerAdmitted,
tripsForwardedHeaderTripwire,
} from './ingress-policy.ts';
@@ -51,23 +51,16 @@ import type { McpHttpHandler } from './mcp-http.ts';
export type { ReadinessState } from './http/http-app.ts';
-const MCP_CORS_HEADERS = {
- 'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS',
- 'Access-Control-Allow-Headers':
- 'Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version',
- // 24 h preflight cache — prevents a round-trip OPTIONS on every sequential tool call.
- 'Access-Control-Max-Age': '86400',
-};
-
export interface MountMcpAndApiOptions {
/** HTTP server constructed with no constructor callback (the helper installs `'request'` + `'upgrade'` listeners). */
httpServer: HttpServer;
/** Hocuspocus instance whose `onRequest` extensions answer `/api/*` and whose `handleConnection` answers `/collab`. */
hocuspocus: Hocuspocus;
/**
- * MCP Streamable HTTP handler. When omitted, `/mcp` is NOT mounted — the
- * `createRestartableServer` test helper takes this path because its
- * fast-restart contract has no MCP component.
+ * MCP Streamable HTTP handler. Served natively by the Hono app
+ * (`createHttpApp`), never the legacy dispatch. When omitted, `/mcp` is
+ * NOT mounted — the `createRestartableServer` test helper takes this path
+ * because its fast-restart contract has no MCP component.
*/
mcpHttpHandler?: McpHttpHandler;
/** Logger for upgrade / request errors. */
@@ -129,9 +122,10 @@ export interface MountMcpAndApiOptions {
/**
* No-project ephemeral single-file mode (`ok <file>`). When `true`, the
* content-asset surface is gated by the same loopback + workspace-host
- * checks the `/mcp` + `/collab/keepalive` legs use. In ephemeral mode
- * `contentDir` is the opened file's parent — often a user-data dir
- * (`~/Downloads`, `~/Documents`) the user never consciously chose to serve —
+ * checks the `/mcp` (`http/mcp-route.ts`) + `/collab/keepalive`
+ * (`collaboration-host.ts`) legs use. In ephemeral mode `contentDir` is the
+ * opened file's parent — often a user-data dir (`~/Downloads`,
+ * `~/Documents`) the user never consciously chose to serve —
* so an ungated asset endpoint would let any localhost-reaching caller,
* including a DNS-rebound malicious page, read those files. Project / desktop
* modes leave this `false` (the user chose the served root) so their asset
@@ -227,60 +221,10 @@ export function mountMcpAndApi(opts: MountMcpAndApiOptions): MountMcpAndApiHandl
const onRequest = (req: IncomingMessage, res: ServerResponse): void => {
const url = req.url?.split('?')[0];
// Surface-wide admission prelude — the proxied-request tripwire plus the
- // exposure admit decision. Shared with the natively-mounted /api/*
- // routes (`admitRequestSurface` in http-app.ts), which sit above the
- // strangler catch-all and would otherwise bypass it.
+ // exposure admit decision. Shared with the natively-mounted /mcp route
+ // and /api/* groups (`admitRequestSurface` in http-app.ts), which sit
+ // above the strangler catch-all and would otherwise bypass it.
if (!admitRequestSurface(req, res, ingressPolicy, 'mcp-mount')) return;
- if (mcpHttpHandler !== undefined && url === '/mcp') {
- const origin = req.headers.origin;
- const sessionId = Array.isArray(req.headers['mcp-session-id'])
- ? req.headers['mcp-session-id'][0]
- : req.headers['mcp-session-id'];
- // The policy's peer + Host gate pair.
- if (!isPeerAdmitted(req.socket.remoteAddress, ingressPolicy)) {
- errorResponse(res, 403, 'urn:ok:error:loopback-required', 'Loopback required.', {
- handler: 'mcp',
- });
- return;
- }
- if (!isHostAdmitted(req.headers.host, ingressPolicy)) {
- errorResponse(res, 403, 'urn:ok:error:host-not-allowed', 'Host header not allowed.', {
- handler: 'mcp',
- detail: HOST_NOT_ADMITTED_REMEDIATION,
- });
- return;
- }
- if (origin !== undefined && !isOriginAdmitted(origin, ingressPolicy)) {
- errorResponse(res, 403, 'urn:ok:error:invalid-origin', 'Origin not allowed.', {
- handler: 'mcp',
- });
- return;
- }
- if (origin !== undefined) {
- res.setHeader('Access-Control-Allow-Origin', origin);
- res.setHeader('Vary', 'Origin');
- }
- for (const [header, value] of Object.entries(MCP_CORS_HEADERS)) {
- res.setHeader(header, value);
- }
- if (req.method === 'OPTIONS') {
- res.writeHead(204);
- res.end();
- return;
- }
- mcpHttpHandler.handle(req, res).catch((err) => {
- log.error({ err, sessionId }, 'Unhandled MCP HTTP error');
- if (!res.writableEnded && !res.headersSent) {
- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Internal server error.', {
- handler: 'mcp',
- cause: err,
- });
- } else if (!res.writableEnded) {
- res.end();
- }
- });
- return;
- }
if (url?.startsWith('/api/')) {
hocuspocus
// biome-ignore lint/suspicious/noExplicitAny: Hocuspocus `hooks()` has no exported payload type for onRequest
@@ -316,14 +260,18 @@ export function mountMcpAndApi(opts: MountMcpAndApiOptions): MountMcpAndApiHandl
// Static serving for non-`/mcp`, non-`/api/*` requests. Two middlewares
// may be wired (desktop mode): `contentAssetMiddleware` over the content
// dir and `reactShellMiddleware` (sirv) over the bundled SPA `dist/`.
- // Never sees `/mcp` or `/api/*` (handled above), so no shadowing risk.
+ // Never sees `/mcp` while an MCP handler is wired (the native Hono route
+ // claims it); with no handler — ephemeral single-file mode, the restartable
+ // harness — `/mcp` lands here like any other unclaimed path. Never sees
+ // `/api/*` (handled above). Either way, no shadowing risk.
//
// Both runners wrap their middleware in try/catch: sirv reaches the
// filesystem synchronously (`fs.existsSync` / `fs.statSync` in `viaLocal`),
// so under FD exhaustion (`EMFILE`/`ENFILE`) or transient FS errors those
// calls throw — without the catch the throw propagates to `http.Server`'s
// 'request' listener and the response hangs until `requestTimeout`. Mirrors
- // the `.catch()` posture on the `/mcp` and `/api/*` legs.
+ // the `.catch()` posture on the `/mcp` (`http/mcp-route.ts`) and `/api/*`
+ // legs.
const runMiddleware = (
middleware:
| ((req: IncomingMessage, res: ServerResponse, next: () => void) => void)
@@ -354,10 +302,10 @@ export function mountMcpAndApi(opts: MountMcpAndApiOptions): MountMcpAndApiHandl
};
const runContent = (onMiss: () => void): void => {
// Ephemeral single-file mode serves assets out of the opened file's
- // parent dir; mirror the `/mcp` peer + Host gate so a DNS-rebound or
- // non-admitted caller can't read that user-data dir. Origin is
- // intentionally NOT checked: no-cors `<img>` / CSS asset loads omit
- // it, and the Host-header check already rejects the rebinding
+ // parent dir; mirror the `/mcp` peer + Host gate (`http/mcp-route.ts`) so
+ // a DNS-rebound or non-admitted caller can't read that user-data dir.
+ // Origin is intentionally NOT checked: no-cors `<img>` / CSS asset loads
+ // omit it, and the Host-header check already rejects the rebinding
// content-exfil vector without that dependency. This surface gate
// refuses EVERY path in ephemeral mode (even ones that would miss and
// fall to the shell); project / desktop modes rely on the in-middleware
@@ -453,13 +401,17 @@ export function mountMcpAndApi(opts: MountMcpAndApiOptions): MountMcpAndApiHandl
socket.destroy();
};
- // The canonical Hono app owns top-level routing (health + ported /api/*
- // groups natively; every unmigrated surface falls through its catch-all
- // into `onRequest` unchanged). The WS upgrade path stays a raw listener —
- // it never routes through HTTP dispatch.
+ // The canonical Hono app owns top-level routing (health, /mcp, and ported
+ // /api/* groups natively; every unmigrated surface falls through its
+ // catch-all into `onRequest` unchanged). The WS upgrade path stays a raw
+ // listener — it never routes through HTTP dispatch.
const { requestListener } = createHttpApp({
health: opts.health,
nativeApi: opts.nativeApi,
+ mcpDispatch:
+ mcpHttpHandler !== undefined
+ ? createMcpDispatch(mcpHttpHandler, ingressPolicy, log)
+ : undefined,
ingressPolicy,
legacyDispatch: onRequest,
log,
diff --git a/packages/server/src/remote-mcp.test.ts b/packages/server/src/remote-mcp.test.ts
index e139230b0..01259d0a1 100644
--- a/packages/server/src/remote-mcp.test.ts
+++ b/packages/server/src/remote-mcp.test.ts
@@ -401,7 +401,109 @@ describe('remote enabled — trust-the-tunnel admission', () => {
});
});
+describe('session verbs through the native mount', () => {
+ // GET with a live session opens the transport's standalone SSE channel —
+ // idle (no priming bytes) but held open for server-initiated notifications;
+ // `enableJsonResponse: true` shapes POST responses only. The pin is that the
+ // response HEAD arrives as `text/event-stream` while the stream stays open:
+ // an adapter that buffered the stream to completion would never flush the
+ // head for an idle channel, so headers-before-end is the proof the router
+ // adapter does not buffer long-lived MCP streams.
+ test('GET with a live session opens the standalone SSE stream unbuffered', async () => {
+ const rig = await bootRemoteRig(null);
+ const gateHeaders = { host: `127.0.0.1:${rig.port}` };
+ const { sessionId } = await openSession(rig.port, gateHeaders);
+
+ const outcome = await new Promise<{ status: number; contentType?: string }>(
+ (resolvePromise, reject) => {
+ const req = httpRequest(
+ {
+ hostname: '127.0.0.1',
+ port: rig.port,
+ path: '/mcp',
+ method: 'GET',
+ headers: {
+ ...gateHeaders,
+ accept: 'text/event-stream',
+ 'mcp-session-id': sessionId,
+ 'mcp-protocol-version': MCP_PROTOCOL_VERSION,
+ },
+ },
+ (res) => {
+ let ended = false;
+ res.on('end', () => {
+ ended = true;
+ });
+ // Give a buffered/short-circuited response time to end; a held-open
+ // idle SSE channel must still be open when the timer fires.
+ setTimeout(() => {
+ const status = res.statusCode ?? 0;
+ const contentType = res.headers['content-type'];
+ req.destroy();
+ if (ended) {
+ reject(new Error('standalone SSE stream ended instead of staying open'));
+ return;
+ }
+ resolvePromise({ status, contentType });
+ }, 250);
+ },
+ );
+ req.on('error', reject);
+ req.setTimeout(5_000, () =>
+ req.destroy(new Error('timed out waiting for the /mcp GET response head')),
+ );
+ req.end();
+ },
+ );
+
+ expect(outcome.status).toBe(200);
+ expect(outcome.contentType).toBe('text/event-stream');
+ });
+
+ test('DELETE tears the session down — a follow-up POST on it is a 404', async () => {
+ const rig = await bootRemoteRig(null);
+ const gateHeaders = { host: `127.0.0.1:${rig.port}` };
+ const { sessionId } = await openSession(rig.port, gateHeaders);
+
+ const del = await raw(rig.port, {
+ method: 'DELETE',
+ path: '/mcp',
+ headers: {
+ ...gateHeaders,
+ 'mcp-session-id': sessionId,
+ 'mcp-protocol-version': MCP_PROTOCOL_VERSION,
+ },
+ });
+ expect(del.status).toBeLessThan(300);
+
+ const after = await raw(rig.port, {
+ method: 'POST',
+ path: '/mcp',
+ headers: {
+ ...gateHeaders,
+ accept: 'application/json, text/event-stream',
+ 'content-type': 'application/json',
+ 'mcp-session-id': sessionId,
+ 'mcp-protocol-version': MCP_PROTOCOL_VERSION,
+ },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 3, method: 'tools/list' }),
+ });
+ expect(after.status).toBe(404);
+ });
+});
+
describe('remote disabled — the forwarding-header tripwire', () => {
+ test('a proxied POST /mcp is refused with the exposure-consent hint', async () => {
+ const rig = await bootRemoteRig(null);
+ const res = await raw(rig.port, {
+ method: 'POST',
+ path: '/mcp',
+ headers: { host: `127.0.0.1:${rig.port}`, 'x-forwarded-for': '203.0.113.7' },
+ });
+ expect(res.status).toBe(403);
+ expect(res.body).toContain('OK_ALLOW_EXTERNAL');
+ });
+
test('proxied requests are refused with the exposure-consent hint', async () => {
const rig = await bootRemoteRig(null);
const res = await raw(rig.port, {
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index 4a0f5dbdb..c4771396a 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -2793,13 +2793,16 @@ export function createServer(options: ServerOptions): ServerInstance {
// etc., which the file-watcher pipeline then reflects into runtime
// behavior (e.g. flipping git auto-sync on).
//
- // The /collab WS upgrade in `mcp-mount.ts` does NOT enforce loopback or
- // host-header validation today (the keepalive sibling does). Even if it
- // did, the server's `host` option allows binding non-loopback addresses
- // (`0.0.0.0`/`::`), so config-doc admission must be gated independently
- // at the document level. Match the DNS-rebinding defense pattern used by
- // /api/* mutating routes (`api-extension.ts`) and /mcp + keepalive
- // (`mcp-mount.ts`):
+ // The /collab WS upgrade (`collaboration-host.ts`) enforces loopback +
+ // host-header validation only when the surface is exposed; unexposed it
+ // admits without those two checks, though a present-but-foreign Origin is
+ // refused in every mode (the keepalive sibling gates loopback + Host in
+ // every mode too). Even if /collab always did, the server's `host` option
+ // allows binding non-loopback addresses (`0.0.0.0`/`::`), so config-doc
+ // admission must be gated independently at the document level. Match the
+ // DNS-rebinding defense pattern used by /api/* mutating routes
+ // (`api-extension.ts`), /mcp (`http/mcp-route.ts`), and keepalive
+ // (`collaboration-host.ts`):
// - TCP peer must be loopback (when the socket is observable).
// - Host header must be a loopback shape (`localhost` / `127.x.y.z` /
// `[::1]`, with optional port) — defends against a rebinding page
@@ -2819,7 +2822,7 @@ export function createServer(options: ServerOptions): ServerInstance {
}
// `payload.request` is typed as Web `Request` by Hocuspocus but is in
// fact the Node `IncomingMessage` we hand to `handleConnection` in
- // `mcp-mount.ts` — `req as unknown as Request`. Read the runtime
+ // `collaboration-host.ts` — `req as unknown as Request`. Read the runtime
// shape via a structural cast so we can inspect the underlying
// socket and headers. Test harnesses that invoke `onAuthenticate`
// directly with a synthetic payload may omit the socket; treat