|
| 1 | +import type { DispatchOutput, JSONRPCMessage, JSONRPCNotification, JSONRPCRequest, RequestEnv } from '@modelcontextprotocol/core'; |
| 2 | + |
| 3 | +import type { ShttpHandlerOptions, ShttpRequestExtra } from './shttpHandler.js'; |
| 4 | +import { shttpHandler } from './shttpHandler.js'; |
| 5 | + |
| 6 | +async function* unwrap(gen: AsyncIterable<DispatchOutput>): AsyncGenerator<JSONRPCMessage, void, void> { |
| 7 | + for await (const out of gen) yield out.message; |
| 8 | +} |
| 9 | + |
| 10 | +/** |
| 11 | + * Minimal contract {@linkcode handleHttp} requires. Satisfied by `McpServer`, |
| 12 | + * `Server`, and any `Protocol` subclass. |
| 13 | + */ |
| 14 | +export interface Dispatchable { |
| 15 | + dispatch(request: JSONRPCRequest, env?: RequestEnv): AsyncIterable<DispatchOutput>; |
| 16 | + dispatchNotification(notification: JSONRPCNotification): Promise<void>; |
| 17 | +} |
| 18 | + |
| 19 | +/** |
| 20 | + * Mounts an `McpServer` (or any `Protocol`) as a web-standard |
| 21 | + * `(Request) => Response` handler. Use this to drive a server from an HTTP framework |
| 22 | + * without instantiating a transport class: |
| 23 | + * |
| 24 | + * ```ts |
| 25 | + * import { McpServer, handleHttp, SessionCompat } from '@modelcontextprotocol/server'; |
| 26 | + * import { toNodeHttpHandler } from '@modelcontextprotocol/node'; |
| 27 | + * |
| 28 | + * const mcp = new McpServer({ name: 's', version: '1.0.0' }); |
| 29 | + * mcp.tool('search', schema, handler); |
| 30 | + * |
| 31 | + * app.all('/mcp', toNodeHttpHandler(handleHttp(mcp, { session: new SessionCompat() }))); |
| 32 | + * ``` |
| 33 | + * |
| 34 | + * `mcp.connect(transport)` is not called; each HTTP request flows through |
| 35 | + * `mcp.dispatch()` directly. Supply a `SessionCompat` via `options.session` |
| 36 | + * to serve clients that send `Mcp-Session-Id` (the pre-2026-06 stateful flow). |
| 37 | + */ |
| 38 | +export function handleHttp( |
| 39 | + mcp: Dispatchable, |
| 40 | + options: ShttpHandlerOptions = {} |
| 41 | +): (req: Request, extra?: ShttpRequestExtra) => Promise<Response> { |
| 42 | + return shttpHandler( |
| 43 | + { |
| 44 | + onrequest: (req, env?: RequestEnv) => unwrap(mcp.dispatch(req, env)), |
| 45 | + onnotification: n => mcp.dispatchNotification(n) |
| 46 | + }, |
| 47 | + options |
| 48 | + ); |
| 49 | +} |
| 50 | + |
| 51 | +export { type ShttpHandlerOptions as HandleHttpOptions, type ShttpRequestExtra as HandleHttpRequestExtra } from './shttpHandler.js'; |
0 commit comments