示例工程 ch18-mcp

ch18-mcp/01-minimal-mcp-server/index.ts

typescript · 5.4 KB

// 01-minimal-mcp-server —— 一个 60 行的 MCP server + 客户端装配(走 PipeTransport 的 JSONL 协议)。
//
// 运行:node --experimental-strip-types index.ts
//
// 真实的 stdio 是「子进程 + 两个流」;这里用同协议的进程内 pipe 模拟:客户端写一行 JSON,
// 服务端读一行、回一行。协议的字节形状与 stdio 完全相同,只是流来自内存。
//
// server 端只实现四个方法:initialize、notifications/initialized、tools/list、tools/call。
 
import { McpClient, PipeTransport, SUPPORTED_PROTOCOL_VERSIONS, type McpPipe, type JsonRpcMessage } from "@earendil-works/pi-mcp";
 
const PROTOCOL = SUPPORTED_PROTOCOL_VERSIONS[0] ?? "2025-11-25";
const DATA: Record<string, string> = { alpha: "A", beta: "B" };
 
const SERVER_TOOLS = [
	{
		name: "lookup",
		description: "按 key 查一个值",
		inputSchema: { type: "object", properties: { key: { type: "string" } }, required: ["key"], additionalProperties: false },
	},
];
 
/** 服务端逻辑:收到一条 JSON-RPC 消息,返回一条回复(或 undefined 表示不需要回复)。 */
function handleServerMessage(message: JsonRpcMessage): JsonRpcMessage | undefined {
	if (!("method" in message)) return undefined;
	const { method, params } = message;
	const id = "id" in message ? message.id : undefined;
	if (id === undefined) return undefined; // 通知:不回复
 
	if (method === "initialize") {
		return {
			jsonrpc: "2.0",
			id,
			result: {
				protocolVersion: PROTOCOL,
				capabilities: { tools: { listChanged: false } },
				serverInfo: { name: "demo-server", version: "0.0.1" },
				instructions: "只提供只读查询。",
			},
		};
	}
	if (method === "tools/list") {
		return { jsonrpc: "2.0", id, result: { tools: SERVER_TOOLS } };
	}
	if (method === "tools/call") {
		const call = params as { name?: string; arguments?: { key?: string } };
		if (call.name !== "lookup") return { jsonrpc: "2.0", id, error: { code: -32601, message: `未知工具 ${call.name}` } };
		const value = DATA[String(call.arguments?.key ?? "")];
		if (value === undefined) {
			return { jsonrpc: "2.0", id, result: { content: [{ type: "text", text: `未找到 ${call.arguments?.key}` }], isError: true } };
		}
		return { jsonrpc: "2.0", id, result: { content: [{ type: "text", text: value }], isError: false } };
	}
	return { jsonrpc: "2.0", id, error: { code: -32601, message: `未实现的方法 ${method}` } };
}
 
/** 进程内的「子进程」:write() 收到客户端输出,handle() 把回复推回 stdout。 */
function createInProcessProgram() {
	let handlers: { onStdout(bytes: Uint8Array): void; onStderr(bytes: Uint8Array): void } | undefined;
	let buffer = "";
	let settleExit: (() => void) | undefined;
	const exited = new Promise<unknown>((resolve) => {
		settleExit = () => resolve(undefined);
	});
 
	const program: McpPipe = {
		write(data) {
			buffer += typeof data === "string" ? data : new TextDecoder().decode(data);
			let index = buffer.indexOf("\n");
			while (index >= 0) {
				const line = buffer.slice(0, index).trim();
				buffer = buffer.slice(index + 1);
				if (line) {
					const reply = handleServerMessage(JSON.parse(line) as JsonRpcMessage);
					if (reply) handlers?.onStdout(new TextEncoder().encode(`${JSON.stringify(reply)}\n`));
				}
				index = buffer.indexOf("\n");
			}
		},
		closeStdin() {
			settleExit?.();
		},
		close() {
			settleExit?.();
		},
		exited,
	};
 
	return {
		program,
		setHandlers(next: typeof handlers) {
			handlers = next;
		},
	};
}
 
const host = createInProcessProgram();
const transport = new PipeTransport({
	open: async (pipeHandlers) => {
		host.setHandlers(pipeHandlers);
		return host.program;
	},
});
 
const client = new McpClient({ name: "tutorial-client", version: "0.0.0" });
const init = await client.connect(transport);
const tools = await client.listTools();
const hit = await client.callTool("lookup", { key: "alpha" });
const miss = await client.callTool("lookup", { key: "missing" });
 
const textOf = (result: unknown) => {
	const content = (result as { content?: Array<{ type: string; text?: string }> }).content ?? [];
	return content.map((part) => (part.type === "text" ? part.text : `[${part.type}]`)).join("");
};
 
console.log("protocolVersion:", init?.protocolVersion);
console.log("serverInfo:", JSON.stringify(init?.serverInfo));
console.log("instructions:", init?.instructions);
console.log("工具列表:", tools.map((tool) => `${tool.name}(${tool.description})`).join(", "));
console.log("命中查询:", JSON.stringify(textOf(hit)));
console.log("未命中查询:", JSON.stringify(textOf(miss)));
 
const ok = (label: string, pass: boolean): void => {
	console.log(`${pass ? "✓" : "✗"} ${label}`);
	if (!pass) process.exitCode = 1;
};
 
ok("握手成功并返回协议版本", Boolean(init?.protocolVersion));
ok("服务端能力声明了 tools", Boolean((init?.capabilities as { tools?: unknown } | undefined)?.tools));
ok("instructions 被传达", init?.instructions?.includes("只读") === true);
ok("listTools 返回 1 个工具", tools.length === 1 && tools[0]?.name === "lookup");
ok("工具带 inputSchema", Boolean((tools[0] as { inputSchema?: unknown })?.inputSchema));
ok("调用命中返回 A", textOf(hit) === "A");
ok("调用未命中返回可读错误", textOf(miss).includes("未找到"));
ok("未命中结果被标记为 isError", (miss as { isError?: boolean }).isError === true);
 
await client.close();
console.log("✓ OK");