Use protected HTTP wiring in examples and guides (#2445)

This commit is contained in:
Felix Weinberger 2026-07-06 21:03:15 +01:00 • committed by GitHub
commit 78fabea445
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
43 changed files with 339 additions and 147 deletions

View file

@ -26,10 +26,9 @@ it (HTTP-only auth, sessionful transports, framework adapters, etc.).
### `server.ts`
```ts
import { createServer } from 'node:http';
import { serve } from '@hono/node-server';
import { parseExampleArgs } from '@mcp-examples/shared';
import { toNodeHandler } from '@modelcontextprotocol/node';
import { createMcpHonoApp } from '@modelcontextprotocol/hono';
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
@ -46,12 +45,24 @@ if (transport === 'stdio') {
console.error('[server] serving over stdio');
} else {
const handler = createMcpHandler(buildServer);
createServer(toNodeHandler(handler)).listen(port, () => {
// `createMcpHonoApp()` arms localhost Host/Origin validation by default.
const app = createMcpHonoApp();
app.all('/mcp', c => handler.fetch(c.req.raw));
serve({ fetch: app.fetch, port, hostname: '127.0.0.1' }, () => {
console.error(`[server] listening on http://127.0.0.1:${port}/mcp`);
});
}
```
The HTTP leg binds loopback explicitly and mounts the handler behind
`createMcpHonoApp()`, which applies host/origin validation by default —
matching the framework factories' defaults. A story whose point is the raw
`node:http` wiring (e.g. `gateway/`, `elicitation/`) keeps
`createServer` + `toNodeHandler` but must then bind
`.listen(port, '127.0.0.1')` and compose the `localhostHostValidation()` /
`localhostOriginValidation()` guards from `@modelcontextprotocol/node` in
front of the handler. Either way, no example teaches an unguarded HTTP mount.
### `client.ts`
```ts

View file

@ -16,6 +16,8 @@ pnpm --filter @mcp-examples/<story> client -- --http http://127.0.0.1:3000/mcp
Add `-- --legacy` to the client command for the 2025-era handshake.
Every HTTP leg serves the handler behind host/origin validation — via `createMcpHonoApp()` (or another framework app factory, which arm the checks by default on localhost binds), or, for raw `node:http` stories, via the `localhostHostValidation()` / `localhostOriginValidation()` guards from `@modelcontextprotocol/node` composed in front of `toNodeHandler` on an explicit loopback bind. New stories follow the canonical skeleton — see [CONTRIBUTING.md](./CONTRIBUTING.md).
The one exception to the generic commands is the reference pair: [`cli-client/`](./cli-client/README.md) and [`todos-server/`](./todos-server/README.md) have their own entry points (`pnpm --filter @mcp-examples/cli-client start`, `pnpm --filter @mcp-examples/todos-server start:http`) — see their READMEs.
## Start here

View file

@ -7,9 +7,10 @@
"client": "tsx client.ts"
},
"dependencies": {
"@hono/node-server": "catalog:runtimeServerOnly",
"@mcp-examples/shared": "workspace:*",
"@modelcontextprotocol/client": "workspace:*",
"@modelcontextprotocol/node": "workspace:*",
"@modelcontextprotocol/hono": "workspace:*",
"@modelcontextprotocol/server": "workspace:*"
},
"devDependencies": {

View file

@ -13,10 +13,9 @@
* The fields are emitted ONLY toward 2026-era clients — a 2025-era response
* is byte-for-byte unchanged. One binary, either transport.
*/
import { createServer } from 'node:http';
import { serve } from '@hono/node-server';
import { parseExampleArgs } from '@mcp-examples/shared';
import { toNodeHandler } from '@modelcontextprotocol/node';
import { createMcpHonoApp } from '@modelcontextprotocol/hono';
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
@ -96,7 +95,11 @@ if (transport === 'stdio') {
console.error('[server] serving over stdio');
} else {
const handler = createMcpHandler(buildServer);
createServer(toNodeHandler(handler)).listen(port, () => {
// `createMcpHonoApp()` binds the endpoint behind localhost host/origin
// validation by default, matching the framework factories' defaults.
const app = createMcpHonoApp();
app.all('/mcp', c => handler.fetch(c.req.raw));
serve({ fetch: app.fetch, port, hostname: '127.0.0.1' }, () => {
console.error(`[server] listening on http://127.0.0.1:${port}/mcp`);
});
}

View file

@ -7,9 +7,10 @@
"client": "tsx client.ts"
},
"dependencies": {
"@hono/node-server": "catalog:runtimeServerOnly",
"@mcp-examples/shared": "workspace:*",
"@modelcontextprotocol/client": "workspace:*",
"@modelcontextprotocol/node": "workspace:*",
"@modelcontextprotocol/hono": "workspace:*",
"@modelcontextprotocol/server": "workspace:*",
"zod": "catalog:runtimeShared"
},

View file

@ -5,10 +5,9 @@
* One binary, either transport — selected by `--http --port <N>` (defaults to
* stdio). See `examples/CONTRIBUTING.md` for the canonical shape.
*/
import { createServer } from 'node:http';
import { serve } from '@hono/node-server';
import { parseExampleArgs } from '@mcp-examples/shared';
import { toNodeHandler } from '@modelcontextprotocol/node';
import { createMcpHonoApp } from '@modelcontextprotocol/hono';
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
import { z } from 'zod/v4';
@ -36,7 +35,10 @@ if (transport === 'stdio') {
console.error('[server] serving over stdio');
} else {
const handler = createMcpHandler(buildServer);
createServer(toNodeHandler(handler)).listen(port, () => {
// `createMcpHonoApp()` arms localhost host/origin validation by default.
const app = createMcpHonoApp();
app.all('/mcp', c => handler.fetch(c.req.raw));
serve({ fetch: app.fetch, port, hostname: '127.0.0.1' }, () => {
console.error(`[server] listening on http://127.0.0.1:${port}/mcp`);
});
}

View file

@ -7,9 +7,10 @@
"client": "tsx client.ts"
},
"dependencies": {
"@hono/node-server": "catalog:runtimeServerOnly",
"@mcp-examples/shared": "workspace:*",
"@modelcontextprotocol/client": "workspace:*",
"@modelcontextprotocol/node": "workspace:*",
"@modelcontextprotocol/hono": "workspace:*",
"@modelcontextprotocol/server": "workspace:*"
},
"devDependencies": {

View file

@ -3,10 +3,9 @@
* The first version in the list is the fallback when the client requests an
* unsupported one. One binary, either transport.
*/
import { createServer } from 'node:http';
import { serve } from '@hono/node-server';
import { parseExampleArgs } from '@mcp-examples/shared';
import { toNodeHandler } from '@modelcontextprotocol/node';
import { createMcpHonoApp } from '@modelcontextprotocol/hono';
import { createMcpHandler, McpServer, SUPPORTED_PROTOCOL_VERSIONS } from '@modelcontextprotocol/server';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
@ -33,7 +32,11 @@ if (transport === 'stdio') {
console.error('[server] serving over stdio');
} else {
const handler = createMcpHandler(buildServer);
createServer(toNodeHandler(handler)).listen(port, () => {
// `createMcpHonoApp()` binds the endpoint behind localhost host/origin
// validation by default, matching the framework factories' defaults.
const app = createMcpHonoApp();
app.all('/mcp', c => handler.fetch(c.req.raw));
serve({ fetch: app.fetch, port, hostname: '127.0.0.1' }, () => {
console.error(`[server] listening on http://127.0.0.1:${port}/mcp`);
});
}

View file

@ -7,9 +7,10 @@
"client": "tsx client.ts"
},
"dependencies": {
"@hono/node-server": "catalog:runtimeServerOnly",
"@mcp-examples/shared": "workspace:*",
"@modelcontextprotocol/client": "workspace:*",
"@modelcontextprotocol/node": "workspace:*",
"@modelcontextprotocol/hono": "workspace:*",
"@modelcontextprotocol/server": "workspace:*",
"zod": "catalog:runtimeShared"
},

View file

@ -13,10 +13,9 @@
* (`createMcpHandler(buildServer)` on its default posture — modern served per
* request, 2025-era traffic served stateless from the same factory).
*/
import { createServer } from 'node:http';
import { serve } from '@hono/node-server';
import { parseExampleArgs } from '@mcp-examples/shared';
import { toNodeHandler } from '@modelcontextprotocol/node';
import { createMcpHonoApp } from '@modelcontextprotocol/hono';
import type { CallToolResult, McpRequestContext } from '@modelcontextprotocol/server';
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
@ -49,7 +48,11 @@ if (transport === 'stdio') {
console.error('[server] serving over stdio');
} else {
const handler = createMcpHandler(buildServer);
createServer(toNodeHandler(handler)).listen(port, () => {
// `createMcpHonoApp()` binds the endpoint behind localhost host/origin
// validation by default, matching the framework factories' defaults.
const app = createMcpHonoApp();
app.all('/mcp', c => handler.fetch(c.req.raw));
serve({ fetch: app.fetch, port, hostname: '127.0.0.1' }, () => {
console.error(`[server] listening on http://127.0.0.1:${port}/mcp`);
});
}

View file

@ -23,7 +23,13 @@ import type { IncomingMessage, ServerResponse } from 'node:http';
import { createServer } from 'node:http';
import { parseExampleArgs } from '@mcp-examples/shared';
import { NodeStreamableHTTPServerTransport, toNodeHandler, toWebRequest } from '@modelcontextprotocol/node';
import {
localhostHostValidation,
localhostOriginValidation,
NodeStreamableHTTPServerTransport,
toNodeHandler,
toWebRequest
} from '@modelcontextprotocol/node';
import type {
CallToolResult,
ElicitRequestFormParams,
@ -274,7 +280,15 @@ if (transport === 'stdio') {
}
};
// Host/Origin guards for the hand-wired `node:http` server — plain
// `createServer` has no middleware chain, so compose the boolean-returning
// guards from `@modelcontextprotocol/node` in front of both arms,
// matching the framework factories' localhost defaults.
const validateHost = localhostHostValidation();
const validateOrigin = localhostOriginValidation();
createServer((req, res) => {
if (!validateHost(req, res) || !validateOrigin(req, res)) return;
void (async () => {
// `toWebRequest` reads the Node body into a web-standard `Request`,
// so the body now lives in `request`, not `req`. Ask the predicate
@ -289,7 +303,7 @@ if (transport === 'stdio') {
console.error('[server] request error:', error instanceof Error ? error.message : error);
if (!res.headersSent) res.writeHead(500).end();
});
}).listen(port, () => {
}).listen(port, '127.0.0.1', () => {
console.error(`[server] listening on http://127.0.0.1:${port}/mcp`);
});
}

View file

@ -7,9 +7,10 @@
"client": "tsx client.ts"
},
"dependencies": {
"@hono/node-server": "catalog:runtimeServerOnly",
"@mcp-examples/shared": "workspace:*",
"@modelcontextprotocol/client": "workspace:*",
"@modelcontextprotocol/node": "workspace:*",
"@modelcontextprotocol/hono": "workspace:*",
"@modelcontextprotocol/server": "workspace:*"
},
"devDependencies": {

View file

@ -6,10 +6,9 @@
* One binary, either transport — selected by `--http --port <N>` (defaults to
* stdio). See `examples/CONTRIBUTING.md` for the canonical shape.
*/
import { createServer } from 'node:http';
import { serve } from '@hono/node-server';
import { parseExampleArgs } from '@mcp-examples/shared';
import { toNodeHandler } from '@modelcontextprotocol/node';
import { createMcpHonoApp } from '@modelcontextprotocol/hono';
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
@ -31,7 +30,11 @@ if (transport === 'stdio') {
console.error('[server] serving over stdio');
} else {
const handler = createMcpHandler(buildServer);
createServer(toNodeHandler(handler)).listen(port, () => {
// `createMcpHonoApp()` arms localhost host/origin validation by default;
// bind loopback explicitly to match.
const app = createMcpHonoApp();
app.all('/mcp', c => handler.fetch(c.req.raw));
serve({ fetch: app.fetch, port, hostname: '127.0.0.1' }, () => {
console.error(`[server] listening on http://127.0.0.1:${port}/mcp`);
});
}

View file

@ -9,7 +9,7 @@
import { createServer } from 'node:http';
import { parseExampleArgs } from '@mcp-examples/shared';
import { toNodeHandler } from '@modelcontextprotocol/node';
import { localhostHostValidation, localhostOriginValidation, toNodeHandler } from '@modelcontextprotocol/node';
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
import * as z from 'zod/v4';
@ -44,6 +44,16 @@ function buildServer(): McpServer {
const { port } = parseExampleArgs();
const handler = createMcpHandler(buildServer);
createServer(toNodeHandler(handler)).listen(port, () => {
const nodeHandler = toNodeHandler(handler);
// Bind loopback explicitly and apply host/origin validation in front of the
// handler, matching the framework factories' defaults. The guards answer
// rejected requests themselves and never reach `createMcpHandler`, so the
// per-request factory count the client asserts on is unchanged.
const validateHost = localhostHostValidation();
const validateOrigin = localhostOriginValidation();
createServer((req, res) => {
if (!validateHost(req, res) || !validateOrigin(req, res)) return;
void nodeHandler(req, res);
}).listen(port, '127.0.0.1', () => {
console.error(`[server] listening on http://127.0.0.1:${port}/mcp`);
});

View file

@ -14,7 +14,7 @@
/* eslint-disable no-console */
import { createServer } from 'node:http';
import { toNodeHandler } from '@modelcontextprotocol/node';
import { localhostHostValidation, localhostOriginValidation, toNodeHandler } from '@modelcontextprotocol/node';
import type { McpServerFactory } from '@modelcontextprotocol/server';
// ---------------------------------------------------------------------------
@ -62,7 +62,13 @@ const perCaller = createMcpHandler(({ authInfo }) => {
/** Example: mounting the handler on plain `node:http`. */
function mountNode(): void {
//#region mountNode
createServer(toNodeHandler(handler)).listen(3000);
const nodeHandler = toNodeHandler(handler);
const validateHost = localhostHostValidation();
const validateOrigin = localhostOriginValidation();
createServer((req, res) => {
if (!validateHost(req, res) || !validateOrigin(req, res)) return;
void nodeHandler(req, res);
}).listen(3000, '127.0.0.1');
//#endregion mountNode
}
void mountNode;

View file

@ -7,9 +7,10 @@
"client": "tsx client.ts"
},
"dependencies": {
"@hono/node-server": "catalog:runtimeServerOnly",
"@mcp-examples/shared": "workspace:*",
"@modelcontextprotocol/client": "workspace:*",
"@modelcontextprotocol/node": "workspace:*",
"@modelcontextprotocol/hono": "workspace:*",
"@modelcontextprotocol/server": "workspace:*",
"zod": "catalog:runtimeShared"
},

View file

@ -7,10 +7,9 @@
* HTTP-only — `responseMode` shapes the HTTP response body; there is no stdio
* equivalent and a stdio leg would not exercise the option.
*/
import { createServer } from 'node:http';
import { serve } from '@hono/node-server';
import { parseExampleArgs } from '@mcp-examples/shared';
import { toNodeHandler } from '@modelcontextprotocol/node';
import { createMcpHonoApp } from '@modelcontextprotocol/hono';
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
import * as z from 'zod/v4';
@ -29,6 +28,10 @@ const { port } = parseExampleArgs();
// `responseMode: 'json'` is the point of this story — applies to the modern
// (2026-07-28) per-request HTTP path.
const handler = createMcpHandler(buildServer, { responseMode: 'json' });
createServer(toNodeHandler(handler)).listen(port, () => {
// `createMcpHonoApp()` binds the endpoint behind localhost host/origin
// validation by default, matching the framework factories' defaults.
const app = createMcpHonoApp();
app.all('/mcp', c => handler.fetch(c.req.raw));
serve({ fetch: app.fetch, port, hostname: '127.0.0.1' }, () => {
console.error(`[server] listening on http://127.0.0.1:${port}/mcp`);
});

View file

@ -7,9 +7,10 @@
"client": "tsx client.ts"
},
"dependencies": {
"@hono/node-server": "catalog:runtimeServerOnly",
"@mcp-examples/shared": "workspace:*",
"@modelcontextprotocol/client": "workspace:*",
"@modelcontextprotocol/node": "workspace:*",
"@modelcontextprotocol/hono": "workspace:*",
"@modelcontextprotocol/server": "workspace:*",
"zod": "catalog:runtimeShared"
},

View file

@ -22,10 +22,9 @@
* One binary, either transport — selected by `--http --port <N>` (defaults to
* stdio). See `examples/CONTRIBUTING.md` for the canonical shape.
*/
import { createServer } from 'node:http';
import { serve } from '@hono/node-server';
import { parseExampleArgs } from '@mcp-examples/shared';
import { toNodeHandler } from '@modelcontextprotocol/node';
import { createMcpHonoApp } from '@modelcontextprotocol/hono';
import type { CallToolResult, InputRequiredResult } from '@modelcontextprotocol/server';
import { acceptedContent, createMcpHandler, createRequestStateCodec, inputRequired, McpServer } from '@modelcontextprotocol/server';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
@ -114,7 +113,11 @@ if (transport === 'stdio') {
console.error('[server] serving over stdio');
} else {
const handler = createMcpHandler(buildServer);
createServer(toNodeHandler(handler)).listen(port, () => {
// `createMcpHonoApp()` binds the endpoint behind localhost host/origin
// validation by default, matching the framework factories' defaults.
const app = createMcpHonoApp();
app.all('/mcp', c => handler.fetch(c.req.raw));
serve({ fetch: app.fetch, port, hostname: '127.0.0.1' }, () => {
console.error(`[server] listening on http://127.0.0.1:${port}/mcp`);
});
}

View file

@ -13,7 +13,7 @@ import { InMemoryOAuthClientProvider } from './simpleOAuthClientProvider';
// Configuration
const DEFAULT_SERVER_URL = 'http://127.0.0.1:3000/mcp';
const CALLBACK_PORT = 8090; // Use different port than auth server (3001)
const CALLBACK_URL = `http://localhost:${CALLBACK_PORT}/callback`;
const CALLBACK_URL = `http://127.0.0.1:${CALLBACK_PORT}/callback`;
/** Minimal HTML escaper for any user/query-derived value interpolated into an HTML response. */
function escHtml(s: string): string {
@ -128,8 +128,10 @@ class InteractiveOAuthClient {
}
});
server.listen(CALLBACK_PORT, () => {
console.log(`OAuth callback server started on http://localhost:${CALLBACK_PORT}`);
// Bind loopback explicitly — the callback target only ever needs to be
// reachable from the local browser, matching the framework factories' defaults.
server.listen(CALLBACK_PORT, '127.0.0.1', () => {
console.log(`OAuth callback server started on ${CALLBACK_URL}`);
});
});
}

Some files were not shown because too many files have changed in this diff Show more