dev-official-mcp-server.mjs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. #!/usr/bin/env node
  2. /*
  3. * 本地自测用的 fake 官方 Server MCP(Streamable HTTP)。
  4. *
  5. * 用途:验证运行中的 ZCode 实际发出的官方 MCP 身份头是否正确——包括当前登录身份的 JWT、
  6. * 选中 Coding Plan 的 key、Bigmodel-Target-Type,以及 Team 场景的 organization/project。
  7. * 同时跟踪协议生命周期(initialize / initialized / tools/list / tools/call),把每一步是否
  8. * 成功、失败原因、以及工具调用的入参与结果都打印出来。
  9. *
  10. * 用法:
  11. * node scripts/dev-official-mcp-server.mjs [--port 3999]
  12. * [--mode ok|401|403|redirect|tool-quota|tool-plan-required]
  13. * [--fail-on all|initialize|tools/call]
  14. * [--mcp-path /api/v1/mcp/server/image_search]
  15. *
  16. * 路由形态刻意与 zcode-server 对齐(`POST /api/v1/mcp/server/:mcp_group`,gin):非匹配路径回
  17. * 404、路径带尾斜杠回 307。这样把线上那两个易错点(漏 group 段、多写尾斜杠)在本地就能复现。
  18. *
  19. * 只监听 127.0.0.1,不属于任何发布产物。
  20. */
  21. import { createServer } from "node:http";
  22. import { parseArgs } from "node:util";
  23. const { values } = parseArgs({
  24. options: {
  25. port: { default: "3999", short: "p", type: "string" },
  26. // 与线上真实端点同形:/api/v1/mcp/server/:mcp_group。image_search 是服务端目前唯一注册的
  27. // group(zcode-server internal/domain/servermcp/service.go 的 MCPGroupTools)。
  28. "mcp-path": { default: "/api/v1/mcp/server/image_search", type: "string" },
  29. // 故障注入:验证 spec §6.3.3 的失败分类。
  30. // ok 正常
  31. // 401 凭证被拒 -> official_auth_rejected(可观察"至多重试一次")
  32. // 403 套餐/权限不足 -> official_auth_forbidden(不重试)
  33. // redirect 302 -> official_auth_redirect_blocked(不跟随)
  34. // tool-quota HTTP 200,但 tools/call 返回业务级"额度耗尽"(isError + error_code)
  35. // tool-plan-required 同上,但 error_code=coding_plan_required(无可用 Coding Plan)
  36. mode: { default: "ok", type: "string" },
  37. // 作用范围:all(默认)| initialize | tools/call
  38. // initialize → 模拟"连接时就发现没额度"
  39. // tools/call → 模拟"连上了,调用时额度耗尽"
  40. "fail-on": { default: "all", type: "string" },
  41. // 在 tools/call 前人为延迟 N 毫秒,用来复现"上游网关慢导致客户端超时"。
  42. // 设成大于 .mcp.json 的 timeoutMs 即可稳定触发客户端超时。
  43. "delay-ms": { default: "0", type: "string" },
  44. },
  45. });
  46. const port = Number(values.port);
  47. const control = {
  48. delayMs: Number(values["delay-ms"]),
  49. failOn: String(values["fail-on"]),
  50. mode: String(values.mode),
  51. };
  52. // 归一化:去掉尾斜杠后作为 canonical 路径,尾斜杠请求由服务端回 307(与 gin 行为一致)。
  53. const MCP_PATH = String(values["mcp-path"]).replace(/\/+$/, "") || "/";
  54. const VALID_MODES = new Set(["ok", "401", "403", "redirect", "tool-quota", "tool-plan-required"]);
  55. const VALID_FAIL_ON = new Set(["all", "initialize", "tools/call"]);
  56. if (!VALID_MODES.has(control.mode) || !VALID_FAIL_ON.has(control.failOn)) {
  57. console.error(
  58. `无效参数:mode=${control.mode} fail-on=${control.failOn}\n` +
  59. `mode ∈ {${[...VALID_MODES].join(", ")}},fail-on ∈ {${[...VALID_FAIL_ON].join(", ")}}`,
  60. );
  61. process.exit(1);
  62. }
  63. const DEFAULT_PROTOCOL_VERSION = "2025-06-18";
  64. const TOOL_NAME = "dev_echo_identity";
  65. const PLUGIN_NAME = "dev-official-mcp";
  66. const MCP_KEY = "dev-search";
  67. const QUALIFIED_TOOL_NAME = `mcp__plugin_${PLUGIN_NAME}_${MCP_KEY}__${TOOL_NAME}`;
  68. // 业务级失败的结果文本,与线上逐字段同形:zcode-server 的 ToolError.Error() 渲染成一行 JSON,
  69. // 客户端只认 error_code 并据此在输入框上方提示(quota-banner spec §4);形状不一致会让本地
  70. // 看到的提示与线上不是一回事。
  71. const IN_BAND_TOOL_FAILURES = {
  72. "tool-quota": {
  73. error_code: "quota_exceeded",
  74. message: "daily quota exceeded for bucket search_image (5/5), retry tomorrow or upgrade your coding plan",
  75. },
  76. "tool-plan-required": {
  77. error_code: "coding_plan_required",
  78. message: "a coding plan is required to use MCP tools, please purchase or configure a coding plan and retry",
  79. },
  80. };
  81. const IDENTITY_HEADERS = [
  82. "authorization",
  83. "x-bigmodel-authorization",
  84. "bigmodel-target-type",
  85. "bigmodel-organization",
  86. "bigmodel-project",
  87. // 已废弃的旧凭证通道。仍列在这里是为了让"客户端还在发它"这件事在自测时立刻可见——
  88. // 两个头同时发会让服务端额外校验 API key 归属,一把过期 key 就能让整个请求 403。
  89. "x-coding-plan-api-key",
  90. ];
  91. /**
  92. * 只有两个 JWT 与旧的 Coding Plan key 是秘密,必须脱敏(首尾 4 位 + 长度)。
  93. * Bigmodel-Target-Type / Organization / Project 是身份标识而非凭证,原样打印——
  94. * 它们正是自测时最需要核对的字段(PERSONAL vs TEAM、org/project 是否成对)。
  95. */
  96. const SECRET_HEADERS = new Set([
  97. "authorization",
  98. "x-coding-plan-api-key",
  99. "x-bigmodel-authorization",
  100. ]);
  101. function formatHeader(name, value) {
  102. if (typeof value !== "string" || value.length === 0) return "(empty)";
  103. if (!SECRET_HEADERS.has(name)) return value;
  104. const prefix = value.startsWith("Bearer ") ? "Bearer " : "";
  105. const bare = prefix ? value.slice(prefix.length) : value;
  106. if (bare.length <= 8) return `${prefix}<len=${bare.length}>`;
  107. return `${prefix}${bare.slice(0, 4)}…${bare.slice(-4)} <len=${bare.length}>`;
  108. }
  109. /** 协议生命周期状态,用于每次请求后打印一行总览。 */
  110. const state = {
  111. identityHeadersSeen: false,
  112. initialize: false,
  113. initialized: false,
  114. negotiatedVersion: undefined,
  115. sessionId: undefined,
  116. toolCallFail: 0,
  117. toolCallOk: 0,
  118. toolsListed: 0,
  119. };
  120. function statusLine() {
  121. const mark = (ok) => (ok ? "✓" : "✗");
  122. return (
  123. ` ★ initialize ${mark(state.initialize)} | initialized ${mark(state.initialized)} | ` +
  124. `tools/list ${state.toolsListed > 0 ? `✓(${state.toolsListed})` : "✗"} | ` +
  125. `tools/call ok=${state.toolCallOk} fail=${state.toolCallFail} | ` +
  126. `身份头 ${mark(state.identityHeadersSeen)}`
  127. );
  128. }
  129. /** 当前请求是否应被注入 HTTP 层故障。两个 tool-* 模式走业务错误,不在此处。 */
  130. function shouldFail(rpcMethod, httpMethod) {
  131. if (control.mode === "ok" || IN_BAND_TOOL_FAILURES[control.mode]) return false;
  132. if (httpMethod === "GET") return false; // GET 探测始终回 405,不参与故障注入
  133. if (control.failOn === "all") return true;
  134. return control.failOn === rpcMethod;
  135. }
  136. let requestCount = 0;
  137. function sendJsonRpc(response, id, payload, extraHeaders = {}) {
  138. response.writeHead(200, { "content-type": "application/json", ...extraHeaders });
  139. response.end(JSON.stringify({ id: id ?? null, jsonrpc: "2.0", ...payload }));
  140. }
  141. function sleep(ms) {
  142. return new Promise((resolve) => setTimeout(resolve, ms));
  143. }
  144. const server = createServer((request, response) => {
  145. const chunks = [];
  146. request.on("data", (chunk) => chunks.push(chunk));
  147. request.on("end", async () => {
  148. requestCount += 1;
  149. const raw = Buffer.concat(chunks).toString("utf8");
  150. let message = {};
  151. let parseError;
  152. try {
  153. message = raw ? JSON.parse(raw) : {};
  154. } catch (error) {
  155. parseError = error instanceof Error ? error.message : String(error);
  156. }
  157. const rpcMethod = parseError ? "(unparsable body)" : message.method;
  158. const present = IDENTITY_HEADERS.filter((name) => request.headers[name] !== undefined);
  159. // 旧通道缺失是**预期**的,不算缺头;反过来它出现时会作为 ✓ 打印出来,一眼能看到回退。
  160. const missing = IDENTITY_HEADERS.filter(
  161. (name) => request.headers[name] === undefined && name !== "x-coding-plan-api-key",
  162. );
  163. if (present.includes("authorization") && present.includes("x-bigmodel-authorization")) {
  164. state.identityHeadersSeen = true;
  165. }
  166. console.log(
  167. `\n[#${requestCount}] ${request.method} ${request.url}` +
  168. (rpcMethod ? ` rpc=${rpcMethod}` : "") +
  169. (rpcMethod === "tools/call" ? ` tool=${message.params?.name ?? "(未指定)"}` : ""),
  170. );
  171. for (const name of present) {
  172. console.log(` ✓ ${name}: ${formatHeader(name, String(request.headers[name]))}`);
  173. }
  174. for (const name of missing) {
  175. console.log(` ✗ ${name}: (absent)`);
  176. }
  177. console.log(
  178. ` · x-request-id: ${request.headers["x-request-id"] ?? "(none)"}` +
  179. ` x-trace-id: ${request.headers["x-trace-id"] ?? "(none)"}`,
  180. );
  181. const seenSessionId = request.headers["mcp-session-id"];
  182. console.log(
  183. ` · mcp-session-id: ${seenSessionId ?? "(none)"}` +
  184. (rpcMethod === "initialize"
  185. ? " ← initialize 不带是正常的(此时服务端还没下发)"
  186. : // GET 探测始终被 405,不参与 session 语义,因此不对它报缺失。
  187. state.sessionId && !seenSessionId && request.method !== "GET"
  188. ? " ⚠ 服务端已下发但客户端未回传"
  189. : ""),
  190. );
  191. // 路由:与 zcode-server 的 gin 路由树同形,把线上两个易错点在本地复现。
  192. const requestPath = (request.url ?? "/").split("?")[0];
  193. if (requestPath === `${MCP_PATH}/`) {
  194. console.log(` ✗ 路径多了尾斜杠 → 回 307(gin 同行为)。客户端 redirect:"manual",`);
  195. console.log(` 会判成 official_auth_redirect_blocked。正确路径:${MCP_PATH}`);
  196. console.log(statusLine());
  197. response.writeHead(307, { location: MCP_PATH }).end();
  198. return;
  199. }
  200. if (requestPath !== MCP_PATH) {
  201. console.log(` ✗ 路径不匹配 → 回 404。期望:${MCP_PATH}`);
  202. console.log(" 线上同理:漏掉 :mcp_group 段(只写 /api/v1/mcp/server/)也是 404。");
  203. console.log(statusLine());
  204. response.writeHead(404, { "content-type": "text/plain" }).end("404 page not found");
  205. return;
  206. }
  207. // GET = SSE 推流探测。第一阶段官方 MCP 不启用推流,正确行为是回 405 让客户端安全放弃。
  208. if (request.method === "GET") {
  209. console.log(" → 回 405(第一阶段不启用服务端推流,spec §6.3.4)");
  210. console.log(" 线上因 gin 只注册 POST,GET 实际是 404;对 SDK 行为等价。");
  211. console.log(statusLine());
  212. response.writeHead(405).end();
  213. return;
  214. }
  215. if (parseError) {
  216. console.log(` ✗ 请求体解析失败:${parseError}`);
  217. console.log(statusLine());
  218. sendJsonRpc(response, null, {
  219. error: { code: -32700, message: `Parse error: ${parseError}` },
  220. });
  221. return;
  222. }
  223. if (shouldFail(rpcMethod, request.method)) {
  224. if (control.mode === "redirect") {
  225. console.log(" ✗ 注入 302 → 期望客户端不跟随,分类 official_auth_redirect_blocked");
  226. console.log(statusLine());
  227. response.writeHead(302, { location: "https://attacker.example/mcp" }).end();
  228. return;
  229. }
  230. const status = Number(control.mode);
  231. console.log(
  232. ` ✗ 注入 ${status} → 期望分类 ${
  233. status === 401
  234. ? "official_auth_rejected(至多重试一次,本终端应恰好出现两条注入日志)"
  235. : "official_auth_forbidden(不重试)"
  236. }`,
  237. );
  238. if (rpcMethod === "tools/call") state.toolCallFail += 1;
  239. console.log(statusLine());
  240. response.writeHead(status).end();
  241. return;
  242. }
  243. // 通知没有 id,按 MCP 惯例回 202 且无 body。
  244. if (rpcMethod === "notifications/initialized") {
  245. state.initialized = true;
  246. console.log(" → 回 202 Accepted(握手完成;这也是 SDK 尝试开 GET 推流的触发点)");
  247. console.log(statusLine());
  248. response.writeHead(202).end();
  249. return;
  250. }
  251. if (rpcMethod === "initialize") {
  252. // 协议版本协商:回显客户端请求的版本最安全——服务端擅自降级会让客户端判定不兼容。
  253. const requested = message.params?.protocolVersion;
  254. const negotiated =
  255. typeof requested === "string" && requested ? requested : DEFAULT_PROTOCOL_VERSION;
  256. state.initialize = true;
  257. state.negotiatedVersion = negotiated;
  258. state.sessionId = `dev-session-${Date.now().toString(36)}`;
  259. const clientInfo = message.params?.clientInfo;
  260. console.log(
  261. ` → 协议版本协商:client=${requested ?? "(未声明)"} server=${negotiated}` +
  262. (requested && requested !== negotiated ? " ⚠ 已降级" : " ✓"),
  263. );
  264. if (clientInfo) {
  265. console.log(` → 客户端:${clientInfo.name ?? "?"} ${clientInfo.version ?? ""}`.trimEnd());
  266. }
  267. console.log(` → 下发 mcp-session-id: ${state.sessionId}`);
  268. console.log(statusLine());
  269. sendJsonRpc(
  270. response,
  271. message.id,
  272. {
  273. result: {
  274. capabilities: { tools: { listChanged: false } },
  275. protocolVersion: negotiated,
  276. serverInfo: { name: "dev-official-mcp", version: "0.0.1" },
  277. },
  278. },
  279. { "mcp-session-id": state.sessionId },
  280. );
  281. return;
  282. }
  283. if (rpcMethod === "tools/list") {
  284. const tools = [
  285. {
  286. description: "本地自测用:回显服务端实际收到的官方 MCP 身份头名称(不回显凭证内容)",
  287. inputSchema: {
  288. additionalProperties: false,
  289. properties: {
  290. note: { description: "可选备注,会原样回显", type: "string" },
  291. },
  292. type: "object",
  293. },
  294. name: TOOL_NAME,
  295. },
  296. ];
  297. state.toolsListed = tools.length;
  298. console.log(` → 返回 ${tools.length} 个工具:${tools.map((tool) => tool.name).join(", ")}`);
  299. console.log(` → 模型侧完整名:${QUALIFIED_TOOL_NAME}`);
  300. console.log(statusLine());
  301. sendJsonRpc(response, message.id, { result: { tools } });
  302. return;
  303. }
  304. if (rpcMethod === "tools/call") {
  305. const requestedTool = message.params?.name;
  306. const args = message.params?.arguments ?? {};
  307. console.log(` → 入参:${JSON.stringify(args)}`);
  308. if (control.delayMs > 0) {
  309. // 复现"上游慢 → 客户端预算先到期"。客户端超时后会断开,这里的响应会写到已关闭的
  310. // socket 上(被忽略),正好对应线上"服务端还在处理、客户端已放弃"的形态。
  311. console.log(` ⏳ 人为延迟 ${control.delayMs}ms(--delay-ms)…`);
  312. await sleep(control.delayMs);
  313. if (response.writableEnded || response.destroyed) {
  314. console.log(` ✗ 延迟结束时客户端已断开 → 这就是客户端超时的现场`);
  315. console.log(statusLine());
  316. return;
  317. }
  318. }
  319. if (requestedTool !== TOOL_NAME) {
  320. // 未知工具属业务错误,走 in-band isError(不是 JSON-RPC error)。
  321. state.toolCallFail += 1;
  322. console.log(` ✗ 未知工具:${requestedTool ?? "(未指定)"} → isError`);
  323. console.log(statusLine());
  324. sendJsonRpc(response, message.id, {
  325. result: {
  326. content: [{ text: `unknown tool: ${String(requestedTool)}`, type: "text" }],
  327. isError: true,
  328. },
  329. });
  330. return;
  331. }
  332. const inBandFailure = IN_BAND_TOOL_FAILURES[control.mode];
  333. if (inBandFailure) {
  334. // MCP 业务错误走 in-band isError,不是 HTTP 状态码。这类失败**不属于**
  335. // §6.3.3 的鉴权分类:MCP 连接保持 connected,错误由模型/上层看到。
  336. state.toolCallFail += 1;
  337. console.log(
  338. ` ✗ 注入业务级失败 error_code=${inBandFailure.error_code} → isError(连接保持 connected)`,
  339. );
  340. console.log(statusLine());
  341. const text = JSON.stringify({
  342. ...inBandFailure,
  343. request_id: `dev-${state.toolCallFail}`,
  344. });
  345. sendJsonRpc(response, message.id, {
  346. result: { content: [{ text, type: "text" }], isError: true },
  347. });
  348. return;
  349. }
  350. state.toolCallOk += 1;
  351. const summary = {
  352. identityHeaders: present,
  353. negotiatedProtocolVersion: state.negotiatedVersion ?? null,
  354. note: typeof args.note === "string" ? args.note : null,
  355. sessionId: seenSessionId ?? null,
  356. targetType: request.headers["bigmodel-target-type"] ?? null,
  357. teamIdentityPaired: Boolean(
  358. request.headers["bigmodel-organization"] && request.headers["bigmodel-project"],
  359. ),
  360. };
  361. console.log(` ✓ 调用成功,回显身份头:${present.join(", ") || "(无)"}`);
  362. console.log(statusLine());
  363. sendJsonRpc(response, message.id, {
  364. result: {
  365. content: [{ text: JSON.stringify(summary, null, 2), type: "text" }],
  366. structuredContent: summary,
  367. },
  368. });
  369. return;
  370. }
  371. // 其余方法按 JSON-RPC 规范返回 Method not found,而不是静默回空结果。
  372. console.log(` ✗ 未实现的方法:${rpcMethod ?? "(无)"} → JSON-RPC -32601`);
  373. console.log(statusLine());
  374. sendJsonRpc(response, message.id, {
  375. error: { code: -32601, message: `Method not found: ${String(rpcMethod)}` },
  376. });
  377. });
  378. });
  379. process.on("SIGINT", () => {
  380. console.log("\n\n=== 本次会话总览 ===");
  381. console.log(statusLine().replace(" ★ ", ""));
  382. console.log(`总请求数:${requestCount}`);
  383. if (!state.identityHeadersSeen) {
  384. console.log("⚠ 从未收到完整身份头——客户端可能在发请求前就被拒(查 officialAuthKind)");
  385. }
  386. server.close(() => process.exit(0));
  387. });
  388. server.listen(port, "127.0.0.1", () => {
  389. const origin = `http://127.0.0.1:${port}`;
  390. const marketplace = "dev-official-marketplace";
  391. // 走 marketplace 安装(而非 plugins.dirs):这是官方插件真实的交付方式,
  392. // 也是新版设置页唯一会显示的形态——settings 的 selectPluginsForScope 只显示
  393. // installedPlugins 里有记录的、或 source === "official" 的插件,
  394. // 因此经 plugins.dirs 挂进来的 inline 插件在那里不可见(agent 侧照常加载)。
  395. const pluginId = `${PLUGIN_NAME}@${marketplace}`;
  396. const marketRoot = `${process.env.HOME ?? "~"}/.zcode-dev-plugins/${marketplace}`;
  397. console.log(`fake 官方 MCP 已监听 ${origin}${MCP_PATH}`);
  398. console.log(" (路径与线上 POST /api/v1/mcp/server/:mcp_group 同形;其它路径回 404)");
  399. console.log(`故障注入:mode=${control.mode} fail-on=${control.failOn}`);
  400. console.log(`期望的 pluginId:${pluginId}`);
  401. console.log(`模型侧工具全名:${QUALIFIED_TOOL_NAME}\n`);
  402. console.log("=== 四步 ===\n");
  403. console.log("1) 建本地 marketplace(含一个插件):");
  404. console.log(`
  405. mkdir -p ${marketRoot}/.claude-plugin ${marketRoot}/${PLUGIN_NAME}/.zcode-plugin
  406. cat > ${marketRoot}/.claude-plugin/marketplace.json <<'JSON'
  407. {
  408. "name": "${marketplace}",
  409. "plugins": [{ "name": "${PLUGIN_NAME}", "source": "./${PLUGIN_NAME}" }]
  410. }
  411. JSON
  412. cat > ${marketRoot}/${PLUGIN_NAME}/.zcode-plugin/plugin.json <<'JSON'
  413. { "name": "${PLUGIN_NAME}", "version": "0.0.1" }
  414. JSON
  415. cat > ${marketRoot}/${PLUGIN_NAME}/.mcp.json <<'JSON'
  416. {
  417. "mcpServers": {
  418. "${MCP_KEY}": {
  419. "type": "http",
  420. "url": "${origin}${MCP_PATH}",
  421. "auth": { "type": "zcode_official", "provider": "jwt_token" }
  422. }
  423. }
  424. }
  425. JSON
  426. `);
  427. console.log("2) 在设置页「添加 marketplace」里填这个目录(注意是 marketplace 根目录,");
  428. console.log(` 不是插件目录):${marketRoot}`);
  429. console.log(" 然后在插件列表里找到 " + PLUGIN_NAME + " 并「安装」。");
  430. console.log(" 若之前用 plugins.dirs 挂过同名插件,先从 ~/.zcode/cli/config.json 的");
  431. console.log(" plugins.dirs 里移除,避免两个来源的同名插件互相干扰。\n");
  432. console.log("3) 安装后**启用**它——marketplace 安装的插件默认不启用,未启用时其 MCP 不会被解析:");
  433. console.log(" 设置页直接打开开关即可;或写配置:");
  434. console.log(`
  435. node -e '
  436. const fs=require("fs"),os=require("os"),path=require("path");
  437. const f=path.join(os.homedir(),".zcode/cli/config.json");
  438. const c=JSON.parse(fs.readFileSync(f,"utf8"));
  439. c.plugins=c.plugins||{};
  440. c.plugins.enabled=true;
  441. c.plugins.enabledPlugins={...(c.plugins.enabledPlugins||{}),"${pluginId}":true};
  442. c.plugins.dirs=(c.plugins.dirs||[]).filter((d)=>!d.includes("${PLUGIN_NAME}"));
  443. fs.writeFileSync(f,JSON.stringify(c,null,2));
  444. console.log("enabledPlugins.${pluginId} = true");
  445. console.log("plugins.dirs =",c.plugins.dirs);
  446. '
  447. `);
  448. console.log("4) 带 dev 开关启动 desktop(值为逗号分隔的 loopback origin):");
  449. console.log(`
  450. export ZCODE_OFFICIAL_MCP_DEV_TRUSTED_ORIGINS='${origin}'
  451. pnpm dev:desktop
  452. `);
  453. console.log(" 该开关只接受 http loopback,无法把凭证导向远端;不设置时一切 fail closed。");
  454. console.log(
  455. " 正式规则是「官方 marketplace 的 plugin + origin 等于当前 ZCode API origin」。\n" +
  456. ` 本地 marketplace 叫 ${marketplace}(非官方),且 origin 是 loopback,\n` +
  457. " 因此自测必须依赖该开关。\n",
  458. );
  459. console.log("启动后让模型调用该工具,本终端会打印每一步的协议状态与身份头。");
  460. console.log("Ctrl-C 退出时会打印本次会话总览。\n");
  461. });