/** * vapor-chamber - Model Context Protocol (MCP) server layer * * Exposes a schema command bus as an MCP server: every schema action becomes * an MCP tool, and `tools/call` requests dispatch through the bus. Zero * dependencies - the JSON-RPC 2.0 / MCP handshake is implemented inline, no * SDK required. * * Three layers, use what you need: * - `busToMcpTools(schema)` - schema -> MCP tool definitions (pure mapping) * - `createMcpHandler(bus)` - transport-agnostic JSON-RPC message handler * - `serveMcpStdio(bus)` - Node-only newline-delimited stdio transport * * @example * import { createActionFilter, createSchemaCommandBus } from 'vapor-chamber'; * import { createMcpHandler, serveMcpStdio } from 'vapor-chamber/mcp'; * * const bus = createSchemaCommandBus(schema); * bus.register('cartAdd', (cmd) => addToCart(cmd.target.id, cmd.payload.qty)); * // meta.origin='agent' is stamped by the core; nothing to install. * const cart = createActionFilter([{ prefix: { action: 'cart' } }]); * * // Wire to any transport (HTTP body, WebSocket message, test harness, ...): * const handle = createMcpHandler(bus, { actionFilter: cart }); * const reply = await handle(jsonRpcMessage); // null for notifications * * // Or run as a stdio MCP server (e.g. for Claude Desktop / claude_desktop_config.json): * const dispose = serveMcpStdio(bus, { actionFilter: cart }); */ import type { CommandResult } from './command-bus'; import type { ActionFilter } from './action-filter'; import type { ActionAnnotations, BusSchema } from './schema'; /** An MCP tool definition, as returned by the `tools/list` method. */ export type McpTool = { name: string; description?: string; /** The action's `ActionSchema.annotations`, when it declares any. */ annotations?: ActionAnnotations; inputSchema: { type: 'object'; properties: Record; required?: string[]; }; }; /** * Convert a BusSchema into MCP tool definitions (the `tools/list` shape). * * Mirrors `toAnthropicTools` (from the schema module): each action becomes one tool, with * `target` and `payload` (each when declared) as nested object properties. Field types map 1:1 to * JSON Schema types; `'any'` fields get no type constraint and are excluded * from `required` (all other fields are required). * * @example * const tools = busToMcpTools({ * cartAdd: { description: 'Add item', target: { id: 'number' }, payload: { qty: 'number' } }, * }); * // -> [{ name: 'cartAdd', description: 'Add item', inputSchema: { * // type: 'object', * // properties: { * // target: { type: 'object', properties: { id: { type: 'number' } }, required: ['id'] }, * // payload: { type: 'object', properties: { qty: { type: 'number' } }, required: ['qty'] }, * // }, * // required: ['target', 'payload'], * // } }] */ export declare function busToMcpTools(schema: BusSchema): McpTool[]; /** Minimal bus surface the MCP layer needs - any schema bus (sync or async) satisfies it. */ export type McpBus = { dispatch: (action: string, target: any, payload?: any) => CommandResult | Promise; getSchema: () => BusSchema; }; export type McpHandlerOptions = { /** * The allowlist: an {@link ActionFilter} (`createActionFilter`). Only the * schema actions it selects are listed by `tools/list` and callable through * `tools/call`. * * **Pass this.** Omitting it exposes EVERY schema action - writes included - * to an LLM-driven caller, and dev-warns to say so. An MCP client is the one * caller class this library treats as untrusted by construction, and least * privilege applies: expose reads broadly, writes narrowly. * `createActionFilter([])` selects every action explicitly and silences the * warning, which is the point: demo convenience should be a deliberate * keystroke, not a default. To expose nothing, do not mount the handler: * CloudEvents rejects an empty `any`. */ actionFilter?: ActionFilter; /** Server name reported by `initialize`. Default: `'vapor-chamber'`. */ serverName?: string; /** Server version reported by `initialize`. Default: the package version. */ serverVersion?: string; }; /** * Version reported by the MCP `initialize` handshake. * * Kept in sync with package.json by `tests/mcp.test.ts`, not by discipline, so * a handshake never advertises a stale version. */ export declare const MCP_SERVER_VERSION = "1.35.0"; /** * Create a transport-agnostic MCP message handler for a schema command bus. * * Takes one parsed JSON-RPC 2.0 message, returns the reply object - or `null` * for notifications (messages without an `id`), which MUST NOT be answered. * Wire it to any transport: stdio (see {@link serveMcpStdio}), an HTTP POST * body, a WebSocket frame, or a test harness. * * Protocol methods handled: * - `initialize` - echoes the client's `protocolVersion` when it is one the * handler speaks (`2024-11-05`, `2025-03-26`, `2025-06-18`), else answers * `'2025-06-18'`; declares `capabilities: { tools: {} }` * - `notifications/initialized` - notification, no reply * - `ping` - replies `{}` * - `tools/list` - the schema actions `actionFilter` allows, as {@link McpTool}s * - `tools/call` - dispatches `{ target, payload }` from `params.arguments` * through the bus; the CommandResult is serialized as a text content * block (`result.value` as JSON on success; `error.message` with * `isError: true` on failure - tool errors are results, not JSON-RPC errors). * A tool not listed (unknown or not allowed) is JSON-RPC error `-32602`. * - anything else with an `id` - JSON-RPC error `-32601` (method not found) * - a request with `id: null` - JSON-RPC error `-32600`, id null (MCP forbids a null id) * * Origin stamping: MCP-driven dispatches carry `meta.origin='agent'` on their * own, stamped onto the dispatch itself, so no local dispatch interleaved with * an awaiting tool call can be misattributed. Nothing to install. * * @example * const reads = createActionFilter([{ any: [{ exact: { action: 'cartGet' } }, { exact: { action: 'userGet' } }] }]); * const handle = createMcpHandler(bus, { actionFilter: reads }); * const reply = await handle({ jsonrpc: '2.0', id: 1, method: 'tools/list' }); * // -> { jsonrpc: '2.0', id: 1, result: { tools: [...] } } */ export declare function createMcpHandler(bus: McpBus, options?: McpHandlerOptions): (message: unknown) => Promise; export type McpStdioOptions = McpHandlerOptions & { /** * Cap on a single line's length (UTF-16 code units) before it is abandoned. * A client that never sends a newline would otherwise grow the read buffer * without bound - same class of input-driven memory guard as the stream * parser's `maxDepth`. On overflow the partial line is dropped, a `-32700` * is written, and input is skipped to the next newline so the stream * resynchronises instead of dying. Default: 1 MiB. Clamped to at least 1 - * see the note at the destructure. */ maxLineLength?: number; /** * Cap on concurrently-dispatched messages. Reaching it pauses `stdin` until * in-flight work drains, so a client that pipes thousands of lines cannot * open thousands of simultaneous dispatches. Deliberately NOT 1: MCP clients * legitimately issue parallel tool calls, and serialising them would make * every slow tool block every fast one. Default: 32. Clamped to at least 1 - * see the note at the destructure. */ maxInFlight?: number; }; /** * Serve the bus as an MCP server over stdio (Node only): newline-delimited * JSON-RPC 2.0 on `process.stdin` in, `process.stdout` out. This is the * transport MCP clients like Claude Desktop spawn subprocess servers with. * * Unparseable lines get a JSON-RPC `-32700` parse error; everything else is * routed through {@link createMcpHandler}. Returns its dispose function, which * detaches from stdin. * * Two input-driven limits keep a hostile or broken client from growing memory * without bound - see {@link McpStdioOptions.maxLineLength} and * {@link McpStdioOptions.maxInFlight}. * * Replies are written in COMPLETION order, not arrival order: messages are * dispatched concurrently, so a fast tool answers before a slow one issued * earlier. That is deliberate and JSON-RPC-legal - responses may arrive in any * order and `id` correlates them - and it is what keeps one slow tool call from * blocking every reply queued behind it. * * IMPORTANT: while serving, do not `console.log` to stdout - it would corrupt * the protocol stream. Log to stderr instead. * * @example * // mcp-server.ts - spawned by an MCP client * const bus = createSchemaCommandBus(schema); * registerHandlers(bus); * const dispose = serveMcpStdio(bus, { actionFilter: createActionFilter([{ prefix: { action: 'cart' } }]) }); * process.on('SIGTERM', dispose); */ export declare function serveMcpStdio(bus: McpBus, options?: McpStdioOptions): () => void; //# sourceMappingURL=mcp.d.ts.map