peppa/packages/testkit/src/mock-mcp-server.ts

95 lines
4.6 KiB
TypeScript

// PEP-236: a remote MCP server (Streamable HTTP) for Access Hub tests — the transport the
// gateway uses (`ConnectionFetch`), answering JSON-RPC like a real server: initialize with a
// session id, tools/list (with pages), tools/call, 401 on a wrong key, JSON or SSE answers.
import type { ConnectionFetch } from "@peppa/core";
export interface MockMcpTool {
name: string;
description?: string;
readOnly?: boolean;
inputSchema?: Record<string, unknown>;
/** The tool's answer for these arguments (text). */
run?: (args: Record<string, unknown>) => string | { error: string };
}
export interface MockMcpCall {
url: string;
method: string;
headers: Record<string, string>;
rpc: string;
tool?: string;
args?: Record<string, unknown>;
}
export class MockMcpServer {
tools: MockMcpTool[];
/** The key the server takes (null — no key needed). */
key: string | null;
/** Header with the key: authorization (Bearer) or a custom one. */
header: string;
/** Answer as an SSE stream instead of JSON. */
sse = false;
/** Tools per page of tools/list. */
pageSize = 100;
down = false;
calls: MockMcpCall[] = [];
private seq = 0;
private sessions = new Set<string>();
constructor(o: { tools: MockMcpTool[]; key?: string | null; header?: string }) {
this.tools = o.tools;
this.key = o.key === undefined ? null : o.key;
this.header = (o.header ?? "authorization").toLowerCase();
}
/** Calls of tools/call (what the server actually ran). */
toolCalls(): MockMcpCall[] {
return this.calls.filter((c) => c.rpc === "tools/call");
}
fetch: ConnectionFetch = async ({ url, method, headers, body }) => {
if (this.down) throw Object.assign(new Error("down"), {});
const msg = JSON.parse(body?.toString("utf8") ?? "{}") as { id?: number; method: string; params?: Record<string, unknown> };
const call: MockMcpCall = { url: url.toString(), method, headers, rpc: msg.method };
if (msg.method === "tools/call") {
call.tool = String(msg.params?.name ?? "");
call.args = (msg.params?.arguments ?? {}) as Record<string, unknown>;
}
this.calls.push(call);
const json = (status: number, payload: unknown, extra: { session?: string } = {}) => {
const text = JSON.stringify(payload);
return { status, contentType: this.sse ? "text/event-stream" : "application/json", body: Buffer.from(this.sse ? `event: message\ndata: ${text}\n\n` : text), truncated: false, mcpSessionId: extra.session ?? null };
};
if (this.key != null) {
const want = this.header === "authorization" ? `Bearer ${this.key}` : this.key;
if (headers[this.header] !== want) return { status: 401, contentType: "application/json", body: Buffer.from('{"error":"unauthorized"}'), truncated: false };
}
if (msg.method === "initialize") {
const session = `mock-mcp-session-${++this.seq}`;
this.sessions.add(session);
return json(200, { jsonrpc: "2.0", id: msg.id, result: { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "mock-mcp", version: "1.0.0" } } }, { session });
}
const session = headers["mcp-session-id"];
if (!session || !this.sessions.has(session)) return { status: 400, contentType: "application/json", body: Buffer.from('{"error":"no session"}'), truncated: false };
if (msg.id === undefined) return { status: 202, contentType: null, body: Buffer.alloc(0), truncated: false };
if (msg.method === "tools/list") {
const start = Number(msg.params?.cursor ?? 0);
const page = this.tools.slice(start, start + this.pageSize);
const next = start + this.pageSize < this.tools.length ? String(start + this.pageSize) : undefined;
return json(200, {
jsonrpc: "2.0",
id: msg.id,
result: { tools: page.map((t) => ({ name: t.name, description: t.description ?? "", inputSchema: t.inputSchema ?? { type: "object", properties: {} }, ...(t.readOnly ? { annotations: { readOnlyHint: true } } : {}) })), ...(next ? { nextCursor: next } : {}) },
});
}
if (msg.method === "tools/call") {
const t = this.tools.find((x) => x.name === call.tool);
if (!t) return json(200, { jsonrpc: "2.0", id: msg.id, error: { code: -32602, message: `Unknown tool ${call.tool}` } });
const out = t.run ? t.run(call.args ?? {}) : `ok ${t.name}`;
if (typeof out === "object") return json(200, { jsonrpc: "2.0", id: msg.id, result: { content: [{ type: "text", text: out.error }], isError: true } });
return json(200, { jsonrpc: "2.0", id: msg.id, result: { content: [{ type: "text", text: out }] } });
}
return json(200, { jsonrpc: "2.0", id: msg.id, error: { code: -32601, message: "Method not found" } });
};
}