controlled-http-mcp-server.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. // 受控的 Streamable HTTP MCP server:只用于 adapter 回归,按工具名统计到达与执行次数。
  2. import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
  3. import type { AddressInfo } from "node:net";
  4. import type { Socket } from "node:net";
  5. export interface ControlledHttpMcpStats {
  6. arrivals: Record<string, number>;
  7. executed: Record<string, number>;
  8. initializations: number;
  9. gets: number;
  10. /** OAuth 元数据发现请求(`/.well-known/*`),用于确认是否发起了授权流程。 */
  11. discoveryRequests: number;
  12. }
  13. export type ControlledToolReply =
  14. | { kind: "result"; text?: string }
  15. | { kind: "rpc-error"; code: number; message: string }
  16. | { kind: "http"; status: number; body?: string; headers?: Record<string, string> }
  17. | { kind: "destroy" };
  18. export interface ControlledHttpMcpOptions {
  19. /** 未知 session 返回 404(有状态 server)。 */
  20. sessionCheck?: boolean;
  21. /** GET 事件流的响应:405(不支持)、404(无 GET 路由)或保持打开。 */
  22. getMode?: "405" | "404" | "hold";
  23. tools?: string[];
  24. /** 返回 undefined 时按成功结果处理;可 await 门控以模拟长调用。 */
  25. onToolCall?: (
  26. name: string,
  27. context: { sessionId?: string; arrival: number },
  28. ) => Promise<ControlledToolReply | undefined> | ControlledToolReply | undefined;
  29. /** 返回 HTTP 响应时初始化失败(例如 503 或 401),用于模拟恢复被拒绝;可 await 门控。 */
  30. onInitialize?: (
  31. count: number,
  32. ) =>
  33. | Promise<{ status: number; body?: string; headers?: Record<string, string> } | void>
  34. | { status: number; body?: string; headers?: Record<string, string> }
  35. | void;
  36. }
  37. export interface ControlledHttpMcpServer {
  38. url: string;
  39. stats: ControlledHttpMcpStats;
  40. /** 使当前全部 session 失效,下一次带旧 session 的请求返回 404。 */
  41. expireSessions(): void;
  42. close(): Promise<void>;
  43. }
  44. export async function startControlledHttpMcpServer(
  45. options: ControlledHttpMcpOptions = {},
  46. ): Promise<ControlledHttpMcpServer> {
  47. const stats: ControlledHttpMcpStats = {
  48. arrivals: {},
  49. executed: {},
  50. initializations: 0,
  51. gets: 0,
  52. discoveryRequests: 0,
  53. };
  54. const sessions = new Set<string>();
  55. const sockets = new Set<Socket>();
  56. let sequence = 0;
  57. const bump = (counts: Record<string, number>, key: string) =>
  58. (counts[key] = (counts[key] ?? 0) + 1);
  59. const tools = options.tools ?? ["ping"];
  60. const server = createServer(async (request: IncomingMessage, response: ServerResponse) => {
  61. if (request.url?.includes("/.well-known/")) {
  62. stats.discoveryRequests++;
  63. response.writeHead(404).end();
  64. return;
  65. }
  66. if (request.method === "GET") {
  67. stats.gets++;
  68. if (options.getMode === "404") {
  69. response.writeHead(404, { "content-type": "text/plain" }).end("Cannot GET /mcp");
  70. return;
  71. }
  72. if (options.getMode === "hold") {
  73. response.writeHead(200, { "content-type": "text/event-stream" });
  74. response.write(": ready\n\n");
  75. return;
  76. }
  77. response.writeHead(405).end();
  78. return;
  79. }
  80. if (request.method === "DELETE") {
  81. response.writeHead(200).end();
  82. return;
  83. }
  84. const chunks: Buffer[] = [];
  85. for await (const chunk of request) chunks.push(chunk as Buffer);
  86. const message = JSON.parse(Buffer.concat(chunks).toString());
  87. const sessionId = request.headers["mcp-session-id"] as string | undefined;
  88. const toolName: string | undefined =
  89. message.method === "tools/call" ? message.params?.name : undefined;
  90. const arrival = toolName ? bump(stats.arrivals, toolName) : 0;
  91. if (
  92. options.sessionCheck &&
  93. message.method !== "initialize" &&
  94. sessionId &&
  95. !sessions.has(sessionId)
  96. ) {
  97. response.writeHead(404, { "content-type": "application/json" }).end(
  98. JSON.stringify({
  99. jsonrpc: "2.0",
  100. id: message.id ?? null,
  101. error: { code: -32001, message: "Session not found" },
  102. }),
  103. );
  104. return;
  105. }
  106. if (message.id === undefined) {
  107. response.writeHead(202).end();
  108. return;
  109. }
  110. let replySessionId = sessionId;
  111. const reply = (result: unknown) =>
  112. response
  113. .writeHead(200, {
  114. "content-type": "application/json",
  115. ...(replySessionId ? { "mcp-session-id": replySessionId } : {}),
  116. })
  117. .end(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }));
  118. if (message.method === "initialize") {
  119. stats.initializations++;
  120. const rejected = await options.onInitialize?.(stats.initializations);
  121. if (rejected) {
  122. response.writeHead(rejected.status, rejected.headers).end(rejected.body ?? "");
  123. return;
  124. }
  125. replySessionId = `session-${++sequence}`;
  126. sessions.add(replySessionId);
  127. reply({
  128. protocolVersion: "2025-11-25",
  129. serverInfo: { name: "controlled", version: "1" },
  130. capabilities: { tools: {}, resources: { subscribe: true } },
  131. });
  132. return;
  133. }
  134. if (message.method === "tools/list") {
  135. reply({
  136. tools: tools.map((name) => ({ name, inputSchema: { type: "object", properties: {} } })),
  137. });
  138. return;
  139. }
  140. if (message.method !== "tools/call") {
  141. reply({});
  142. return;
  143. }
  144. const outcome = await options.onToolCall?.(toolName!, { sessionId, arrival });
  145. if (outcome?.kind === "destroy") {
  146. bump(stats.executed, toolName!);
  147. request.socket.destroy();
  148. return;
  149. }
  150. if (outcome?.kind === "http") {
  151. response.writeHead(outcome.status, outcome.headers).end(outcome.body ?? "");
  152. return;
  153. }
  154. bump(stats.executed, toolName!);
  155. if (outcome?.kind === "rpc-error") {
  156. response.writeHead(200, { "content-type": "application/json" }).end(
  157. JSON.stringify({
  158. jsonrpc: "2.0",
  159. id: message.id,
  160. error: { code: outcome.code, message: outcome.message },
  161. }),
  162. );
  163. return;
  164. }
  165. reply({ content: [{ type: "text", text: outcome?.text ?? `ok:${toolName}` }] });
  166. });
  167. server.on("connection", (socket) => {
  168. sockets.add(socket);
  169. socket.on("close", () => sockets.delete(socket));
  170. });
  171. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  172. return {
  173. url: `http://127.0.0.1:${(server.address() as AddressInfo).port}/mcp`,
  174. stats,
  175. expireSessions: () => sessions.clear(),
  176. close: () => {
  177. for (const socket of sockets) socket.destroy();
  178. return new Promise<void>((resolve) => server.close(() => resolve()));
  179. },
  180. };
  181. }