mcp-server.mjs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. // 独立 MCP 进程:控制 socket 只用于可重复地安排完成顺序,不替代 MCP 数据链路。
  2. import { createInterface } from "node:readline";
  3. import { connect } from "node:net";
  4. import { readFile } from "node:fs/promises";
  5. const [port, htmlPath, sourceArgument] = process.argv.slice(2);
  6. const source = sourceArgument === "managed-delayed" ? "managed" : sourceArgument;
  7. const control = connect(Number(port), "127.0.0.1");
  8. const sendEvent = (event) => control.write(JSON.stringify({ source, ...event }) + "\n");
  9. const respond = (id, result) =>
  10. process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result }) + "\n");
  11. const pending = new Map();
  12. const result = (key) => ({
  13. ...(key === "raw-error" ? { isError: true } : {}),
  14. content:
  15. key === "raw-error"
  16. ? [
  17. { type: "text", text: "fixture error" },
  18. { type: "image", data: "aGVsbG8=", mimeType: "image/png" },
  19. {
  20. type: "resource",
  21. resource: { uri: "fixture://error", mimeType: "text/plain", text: "details" },
  22. },
  23. ]
  24. : [{ type: "text", text: "x".repeat(40_000) }],
  25. structuredContent: { key, source },
  26. _meta: { fixture: true },
  27. });
  28. createInterface({ input: control }).on("line", (line) => {
  29. const command = JSON.parse(line);
  30. if (command.type === "disconnect") process.exit(0);
  31. if (command.type === "notify") {
  32. process.stdout.write(
  33. JSON.stringify({
  34. jsonrpc: "2.0",
  35. method: "notifications/resources/updated",
  36. params: { uri: command.uri },
  37. }) + "\n",
  38. );
  39. sendEvent({ type: "notified", uri: command.uri });
  40. }
  41. if (command.type === "release") {
  42. const call = pending.get(command.key);
  43. if (call) {
  44. pending.delete(command.key);
  45. respond(call.id, call.result);
  46. sendEvent({ type: "released", key: command.key });
  47. }
  48. }
  49. });
  50. createInterface({ input: process.stdin }).on("line", async (line) => {
  51. const message = JSON.parse(line);
  52. if (message.method === "notifications/cancelled") {
  53. const call = [...pending.entries()].find(([, value]) => value.id === message.params.requestId);
  54. if (call) sendEvent({ type: "cancelled", key: call[0] });
  55. // 故意允许控制端晚回结果,验证 Agent 不接受取消后的写入,也不会重放。
  56. return;
  57. }
  58. if (message.id === undefined) return;
  59. const { id, method, params } = message;
  60. switch (method) {
  61. case "initialize": {
  62. const initialization = {
  63. protocolVersion: "2025-11-25",
  64. capabilities: { tools: {}, resources: { subscribe: true } },
  65. serverInfo: { name: "host-e2e", version: "1" },
  66. };
  67. // 用控制闸门重现 session 先恢复、MCP 后连接,不能依赖机器启动速度碰运气。
  68. if (sourceArgument === "managed-delayed") {
  69. pending.set("initialize", { id, result: initialization });
  70. sendEvent({ type: "initialize-waiting" });
  71. } else respond(id, initialization);
  72. break;
  73. }
  74. case "tools/list":
  75. respond(id, {
  76. tools: [
  77. ...(source.startsWith("admission")
  78. ? [
  79. {
  80. name: "open_editor",
  81. description: "Open fixture editor",
  82. inputSchema: {
  83. type: "object",
  84. properties: { key: { type: "string" }, delayed: { type: "boolean" } },
  85. required: ["key"],
  86. },
  87. annotations: { readOnlyHint: true },
  88. _meta: { ui: { resourceUri: "ui://fixture", surface: "same" } },
  89. },
  90. ]
  91. : []),
  92. {
  93. name: "edit",
  94. description: "Local E2E app-only tool",
  95. inputSchema: {
  96. type: "object",
  97. properties: { key: { type: "string" }, delayed: { type: "boolean" } },
  98. required: ["key"],
  99. },
  100. annotations: { readOnlyHint: false },
  101. _meta: { ui: { visibility: ["app"] } },
  102. },
  103. ],
  104. });
  105. break;
  106. case "resources/read": {
  107. sendEvent({ type: "read", uri: params.uri });
  108. const resources = {
  109. "fixture://document.pdf": {
  110. mimeType: "application/pdf",
  111. blob: Buffer.from("%PDF-1.7\n%%EOF\n").toString("base64"),
  112. },
  113. "fixture://vector.svg": {
  114. mimeType: "image/svg+xml",
  115. text: '<svg xmlns="http://www.w3.org/2000/svg"/>',
  116. },
  117. "fixture://unsupported.bin": { mimeType: "application/x-msdownload", blob: "YQ==" },
  118. };
  119. if (resources[params.uri]) {
  120. respond(id, {
  121. contents: [
  122. { uri: params.uri, ...resources[params.uri], _meta: { private: "server-only" } },
  123. ],
  124. });
  125. break;
  126. }
  127. respond(id, {
  128. contents: [
  129. {
  130. uri: params.uri,
  131. mimeType: "text/html;profile=mcp-app",
  132. text: (await readFile(htmlPath, "utf8")).replace(
  133. "<head>",
  134. `<head>${
  135. params.uri.startsWith("ui://fixture/modes/")
  136. ? `<script>window.fixtureDisplayModes=${JSON.stringify(params.uri.slice("ui://fixture/modes/".length).split(",").filter(Boolean))}</script>`
  137. : ""
  138. }`,
  139. ),
  140. _meta: {
  141. ui: {
  142. ...(source !== "non-retained" ? { backgroundRetention: true } : {}),
  143. ...(source === "managed-permissions" ? { permissions: { geolocation: {} } } : {}),
  144. },
  145. },
  146. },
  147. ],
  148. });
  149. break;
  150. }
  151. case "resources/list":
  152. respond(id, { resources: [] });
  153. break;
  154. case "resources/templates/list":
  155. respond(id, { resourceTemplates: [] });
  156. break;
  157. case "resources/subscribe":
  158. case "resources/unsubscribe":
  159. sendEvent({ type: method, uri: params.uri });
  160. respond(id, {});
  161. break;
  162. case "tools/call": {
  163. const key = params.arguments.key;
  164. sendEvent({ type: "executed", key });
  165. if (params.arguments.delayed) pending.set(key, { id, result: result(key) });
  166. else respond(id, result(key));
  167. break;
  168. }
  169. default:
  170. respond(id, {});
  171. }
  172. });
  173. process.stdin.on("end", () => {
  174. control.end();
  175. process.exit(0);
  176. });