@uncarved/jade 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/README.md +1 -0
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/host.d.ts +2 -0
  5. package/dist/host.js +39 -5
  6. package/dist/host.js.map +1 -1
  7. package/dist/remote.js +5 -0
  8. package/dist/remote.js.map +1 -1
  9. package/dist/session.d.ts +7 -0
  10. package/dist/session.js +490 -29
  11. package/dist/session.js.map +1 -1
  12. package/package.json +4 -4
  13. package/plugins/approval/index.ts +36 -14
  14. package/plugins/approval/policy.ts +15 -10
  15. package/plugins/approval/review.ts +9 -5
  16. package/plugins/checks/checks.ts +10 -7
  17. package/plugins/checks/index.ts +13 -13
  18. package/plugins/checks/plugin.json +1 -1
  19. package/plugins/checks/project.ts +37 -38
  20. package/plugins/commands/index.ts +27 -3
  21. package/plugins/compact/compact.ts +13 -5
  22. package/plugins/compact/index.ts +20 -3
  23. package/plugins/compact/style.ts +13 -14
  24. package/plugins/completions/index.ts +35 -0
  25. package/plugins/completions/plugin.json +7 -0
  26. package/plugins/copy/index.ts +46 -0
  27. package/plugins/copy/plugin.json +7 -0
  28. package/plugins/editor/index.ts +10 -4
  29. package/plugins/fs/diff.ts +7 -6
  30. package/plugins/fs/fs.ts +8 -4
  31. package/plugins/fs/grep.ts +42 -9
  32. package/plugins/fs/index.ts +2 -7
  33. package/plugins/fs/plugin.json +1 -1
  34. package/plugins/fs/renderers.ts +16 -15
  35. package/plugins/fs/style.ts +16 -15
  36. package/plugins/hooks/index.ts +3 -2
  37. package/plugins/keys/index.ts +5 -1
  38. package/plugins/mcp/index.ts +197 -78
  39. package/plugins/mcp/install.ts +5 -3
  40. package/plugins/mcp/mcp.ts +163 -11
  41. package/plugins/mcp/plugin.json +2 -1
  42. package/plugins/mcp/project.ts +47 -50
  43. package/plugins/memory/index.ts +4 -4
  44. package/plugins/memory/style.ts +13 -14
  45. package/plugins/mentions/candidates.ts +67 -0
  46. package/plugins/mentions/index.ts +12 -5
  47. package/plugins/mentions/plugin.json +1 -1
  48. package/plugins/mentions/style.ts +13 -14
  49. package/plugins/models/configure.ts +47 -12
  50. package/plugins/models/index.ts +27 -1
  51. package/plugins/models/provider.ts +24 -0
  52. package/plugins/models/saved.ts +1 -1
  53. package/plugins/modes/index.ts +13 -2
  54. package/plugins/print/index.ts +7 -4
  55. package/plugins/prompts/index.ts +0 -0
  56. package/plugins/renderers/index.ts +10 -5
  57. package/plugins/repeats/index.ts +8 -8
  58. package/plugins/schedule/index.ts +5 -1
  59. package/plugins/screenshot/browser.ts +10 -0
  60. package/plugins/sessions/index.ts +48 -2
  61. package/plugins/shell/index.ts +27 -28
  62. package/plugins/shell/plugin.json +1 -1
  63. package/plugins/shell/renderers.ts +9 -7
  64. package/plugins/shell/shell.ts +3 -1
  65. package/plugins/skills/index.ts +28 -19
  66. package/plugins/skills/project.ts +12 -7
  67. package/plugins/steer/index.ts +5 -4
  68. package/plugins/task/index.ts +80 -50
  69. package/plugins/task/plugin.json +6 -2
  70. package/plugins/task/style.ts +13 -14
  71. package/plugins/task/subagent.ts +67 -184
  72. package/plugins/todo/index.ts +39 -9
  73. package/plugins/tools/index.ts +9 -2
  74. package/plugins/tui/frontend.ts +139 -89
  75. package/plugins/tui/index.ts +2 -3
  76. package/plugins/tui/mentions.ts +11 -80
  77. package/plugins/tui/plugin.json +1 -1
  78. package/plugins/tui/screen.ts +55 -5
  79. package/plugins/tui/transcript.ts +17 -7
  80. package/plugins/tui/tui.ts +337 -101
  81. package/plugins/tui/vendor.ts +1 -1
  82. package/plugins/undo/checkpoint.ts +8 -4
  83. package/plugins/undo/index.ts +170 -31
  84. package/plugins/undo/plugin.json +1 -0
  85. package/plugins/undo/snapshot.ts +87 -14
  86. package/plugins/undo/style.ts +13 -14
  87. package/plugins/web/index.ts +7 -18
  88. package/plugins/web/plugin.json +1 -1
  89. package/plugins-dist/approval/index.js +363 -418
  90. package/plugins-dist/approval/policy.js +391 -508
  91. package/plugins-dist/approval/review.js +132 -158
  92. package/plugins-dist/approval/schema.js +50 -55
  93. package/plugins-dist/ask/index.js +115 -129
  94. package/plugins-dist/budget/index.js +27 -31
  95. package/plugins-dist/checks/checks.js +293 -329
  96. package/plugins-dist/checks/index.js +119 -139
  97. package/plugins-dist/checks/plugin.json +2 -1
  98. package/plugins-dist/checks/project.js +57 -65
  99. package/plugins-dist/commands/index.js +47 -29
  100. package/plugins-dist/compact/compact.js +233 -249
  101. package/plugins-dist/compact/index.js +98 -95
  102. package/plugins-dist/compact/style.js +9 -14
  103. package/plugins-dist/completions/index.js +30 -0
  104. package/plugins-dist/completions/plugin.json +9 -0
  105. package/plugins-dist/continue/index.js +40 -52
  106. package/plugins-dist/copy/index.js +40 -0
  107. package/plugins-dist/copy/plugin.json +9 -0
  108. package/plugins-dist/cost/index.js +98 -115
  109. package/plugins-dist/custom-commands/index.js +55 -72
  110. package/plugins-dist/editor/index.js +64 -72
  111. package/plugins-dist/fs/diff.js +111 -124
  112. package/plugins-dist/fs/fs.js +426 -469
  113. package/plugins-dist/fs/grep.js +262 -253
  114. package/plugins-dist/fs/index.js +20 -34
  115. package/plugins-dist/fs/plugin.json +1 -2
  116. package/plugins-dist/fs/renderers.js +100 -112
  117. package/plugins-dist/fs/style.js +11 -15
  118. package/plugins-dist/fs/sys.js +31 -43
  119. package/plugins-dist/hooks/index.js +107 -127
  120. package/plugins-dist/keys/index.js +27 -31
  121. package/plugins-dist/mcp/index.js +271 -199
  122. package/plugins-dist/mcp/install.js +123 -137
  123. package/plugins-dist/mcp/mcp.js +638 -577
  124. package/plugins-dist/mcp/plugin.json +3 -1
  125. package/plugins-dist/mcp/project.js +98 -115
  126. package/plugins-dist/memory/index.js +83 -88
  127. package/plugins-dist/memory/memory.js +111 -128
  128. package/plugins-dist/memory/style.js +9 -14
  129. package/plugins-dist/mentions/attach.js +91 -99
  130. package/plugins-dist/mentions/candidates.js +49 -0
  131. package/plugins-dist/mentions/index.js +71 -81
  132. package/plugins-dist/mentions/plugin.json +2 -1
  133. package/plugins-dist/mentions/style.js +9 -14
  134. package/plugins-dist/models/config.js +29 -43
  135. package/plugins-dist/models/configure.js +421 -474
  136. package/plugins-dist/models/context.js +14 -22
  137. package/plugins-dist/models/index.js +182 -189
  138. package/plugins-dist/models/provider.js +263 -307
  139. package/plugins-dist/models/saved.js +60 -72
  140. package/plugins-dist/modes/index.js +138 -165
  141. package/plugins-dist/plugins/index.js +34 -34
  142. package/plugins-dist/print/index.js +192 -175
  143. package/plugins-dist/prompts/index.js +86 -89
  144. package/plugins-dist/prompts/notes.js +31 -37
  145. package/plugins-dist/prompts/prompts.js +155 -193
  146. package/plugins-dist/prompts/results.js +40 -53
  147. package/plugins-dist/prompts/sys.js +39 -50
  148. package/plugins-dist/renderers/index.js +32 -32
  149. package/plugins-dist/repeats/index.js +131 -174
  150. package/plugins-dist/schedule/cron.js +49 -56
  151. package/plugins-dist/schedule/index.js +230 -247
  152. package/plugins-dist/schedule/store.js +93 -109
  153. package/plugins-dist/scratch/index.js +12 -18
  154. package/plugins-dist/screenshot/browser.js +136 -154
  155. package/plugins-dist/screenshot/index.js +37 -46
  156. package/plugins-dist/screenshot/sys.js +53 -65
  157. package/plugins-dist/screenshot/tool.js +98 -126
  158. package/plugins-dist/sessions/index.js +149 -117
  159. package/plugins-dist/shell/index.js +117 -135
  160. package/plugins-dist/shell/plugin.json +1 -1
  161. package/plugins-dist/shell/renderers.js +28 -33
  162. package/plugins-dist/shell/service.js +17 -23
  163. package/plugins-dist/shell/shell.js +307 -362
  164. package/plugins-dist/shell/sys.js +64 -79
  165. package/plugins-dist/skills/index.js +193 -211
  166. package/plugins-dist/skills/install.js +122 -149
  167. package/plugins-dist/skills/project.js +65 -73
  168. package/plugins-dist/skills/skills.js +135 -171
  169. package/plugins-dist/steer/index.js +108 -125
  170. package/plugins-dist/suggest/index.js +235 -259
  171. package/plugins-dist/task/index.js +130 -117
  172. package/plugins-dist/task/plugin.json +5 -2
  173. package/plugins-dist/task/style.js +9 -14
  174. package/plugins-dist/task/subagent.js +156 -279
  175. package/plugins-dist/todo/index.js +79 -63
  176. package/plugins-dist/tools/index.js +36 -42
  177. package/plugins-dist/tui/editor.js +145 -160
  178. package/plugins-dist/tui/frontend.js +639 -678
  179. package/plugins-dist/tui/history.js +34 -37
  180. package/plugins-dist/tui/index.js +16 -18
  181. package/plugins-dist/tui/markdown.js +203 -247
  182. package/plugins-dist/tui/mascot.js +266 -355
  183. package/plugins-dist/tui/mentions.js +67 -144
  184. package/plugins-dist/tui/plugin.json +1 -2
  185. package/plugins-dist/tui/render.js +35 -45
  186. package/plugins-dist/tui/screen.js +197 -180
  187. package/plugins-dist/tui/transcript.js +436 -468
  188. package/plugins-dist/tui/tui.js +1554 -1656
  189. package/plugins-dist/tui/vendor.js +1088 -1388
  190. package/plugins-dist/undo/checkpoint.js +97 -118
  191. package/plugins-dist/undo/index.js +281 -192
  192. package/plugins-dist/undo/plugin.json +3 -0
  193. package/plugins-dist/undo/snapshot.js +134 -99
  194. package/plugins-dist/undo/style.js +9 -14
  195. package/plugins-dist/update/index.js +26 -28
  196. package/plugins-dist/web/env.js +55 -68
  197. package/plugins-dist/web/index.js +80 -110
  198. package/plugins-dist/web/plugin.json +1 -2
  199. package/plugins-dist/web/renderers.js +4 -5
  200. package/plugins-dist/web/web.js +514 -593
  201. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  202. package/sdk/python/jade_plugin.py +9 -2
  203. package/src/api.ts +1 -1
  204. package/src/host.ts +39 -4
  205. package/src/remote.ts +6 -1
  206. package/src/session.ts +496 -36
@@ -1,645 +1,706 @@
1
- // MCP(Model Context Protocol)客户端:连接 MCP 服务,把它们的工具变成 jade 的工具。
2
- //
3
- // 配置兼容 Claude Code 的 .mcp.json:{ "mcpServers": { "<name>": { command, args, env } | { type: "http", url, headers } } }。
4
- // 读取顺序(同名时后面的覆盖前面的):
5
- // $JADE_HOME/mcp.json(用户层)、<仓库根目录>/.mcp.json、仓库根目录到工作目录每一级的 .jade/mcp.json(项目层)。
6
- // 项目层的服务随仓库分发,启动它就是执行仓库指定的命令,所以第一次启动前要用户确认(按配置内容记录,见 index.ts)。
7
- //
8
- // 传输:stdio(一行一条 JSON-RPC 消息)和 Streamable HTTP(POST,回复是 JSON 或 SSE)。旧的 HTTP+SSE 传输不支持。
9
- // 从旧 jade 的 src/mcp.ts 移植;旧 jade 的"插件自带 MCP 配置"(PluginBundle)没有移植:新的插件宿主没有内容包的概念。
10
1
  import { spawn } from "node:child_process";
11
2
  import { createHash } from "node:crypto";
12
3
  import { readFileSync, statSync } from "node:fs";
13
- import { readFile } from "node:fs/promises";
4
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
14
5
  import path from "node:path";
15
6
  import { projectDirs } from "./project.js";
16
7
  export const PROTOCOL_VERSION = "2025-06-18";
17
- /** 告诉服务端的客户端版本:jade 的版本(和 jade/tui 一样从 apps/jade/package.json 读) */
18
8
  const CLIENT_INFO = {
19
- name: "jade",
20
- version: (() => {
21
- try {
22
- return JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
23
- }
24
- catch {
25
- return "0.0.0";
26
- }
27
- })(),
9
+ name: "jade",
10
+ version: (() => {
11
+ try {
12
+ return JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
13
+ } catch {
14
+ return "0.0.0";
15
+ }
16
+ })()
28
17
  };
29
- /** 一次工具调用结果里文本的上限,超过时保留开头 */
30
- const MAX_RESULT_CHARS = 60_000;
18
+ const MAX_RESULT_CHARS = 60000;
31
19
  const STDERR_LINES = 20;
32
- /** 工具名的上限:OpenAI 的接口要求不超过 64 个字符 */
33
20
  const MAX_TOOL_NAME = 64;
34
- // ---------- 配置 ----------
35
- /** 用户层在前,项目层从仓库根目录往下;同名的后面覆盖前面 */
36
21
  export async function loadMcpConfig(opts) {
37
- const env = opts.env ?? process.env;
38
- const files = [
39
- { file: path.join(opts.home, "mcp.json"), layer: "user" },
40
- { file: path.join(opts.root, ".mcp.json"), layer: "project" },
41
- ...projectDirs(opts.root, opts.cwd).map((d) => ({ file: path.join(d, ".jade", "mcp.json"), layer: "project" })),
42
- ];
43
- const out = new Map();
44
- const warnings = [];
45
- for (const { file, layer } of files) {
46
- let text;
47
- try {
48
- text = await readFile(file, "utf8");
49
- }
50
- catch {
51
- continue;
52
- }
53
- let json;
54
- try {
55
- json = JSON.parse(text);
56
- }
57
- catch (err) {
58
- warnings.push(`${file}: ${err instanceof Error ? err.message : String(err)}`);
59
- continue;
60
- }
61
- const servers = json?.mcpServers;
62
- if (typeof servers !== "object" || servers === null || Array.isArray(servers)) {
63
- warnings.push(`${file}: expected { "mcpServers": { ... } }`);
64
- continue;
65
- }
66
- for (const [name, raw] of Object.entries(servers)) {
67
- const problem = checkConfig(name, raw);
68
- if (problem) {
69
- warnings.push(`${file}: MCP server ${JSON.stringify(name)}: ${problem}`);
70
- continue;
71
- }
72
- const missing = [];
73
- const config = expandConfig(raw, env, missing);
74
- if (missing.length) {
75
- warnings.push(`${file}: MCP server ${name} is skipped: environment variable ${[...new Set(missing)].join(", ")} is not set`);
76
- out.delete(name);
77
- continue;
78
- }
79
- // 地址里可以有 ${VAR},展开之后再检查格式
80
- if (config.command === undefined && !/^https?:\/\//.test(config.url)) {
81
- warnings.push(`${file}: MCP server ${name}: "url" must start with http:// or https://`);
82
- out.delete(name);
83
- continue;
84
- }
85
- if (config.cwd && !path.isAbsolute(config.cwd))
86
- config.cwd = path.resolve(path.dirname(file), config.cwd);
87
- out.set(name, { name, layer, file, config });
88
- }
22
+ const env = opts.env ?? process.env;
23
+ const files = [
24
+ { file: path.join(opts.home, "mcp.json"), layer: "user" },
25
+ { file: path.join(opts.root, ".mcp.json"), layer: "project" },
26
+ ...projectDirs(opts.root, opts.cwd).map((d) => ({ file: path.join(d, ".jade", "mcp.json"), layer: "project" }))
27
+ ];
28
+ const out = new Map;
29
+ const warnings = [];
30
+ for (const { file, layer } of files) {
31
+ let text;
32
+ try {
33
+ text = await readFile(file, "utf8");
34
+ } catch {
35
+ continue;
89
36
  }
90
- return { servers: [...out.values()], warnings };
91
- }
92
- const SERVER_NAME = /^[A-Za-z0-9_.-]+$/;
93
- /** 一条服务配置的问题;没问题时为 undefined。/mcp add 写入前也用它检查 */
94
- export function checkConfig(name, raw) {
95
- if (!SERVER_NAME.test(name))
96
- return "the name may only contain letters, digits, '.', '_' and '-'";
97
- if (typeof raw !== "object" || raw === null || Array.isArray(raw))
98
- return "must be an object";
99
- const c = raw;
100
- const strings = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
101
- const stringMap = (v) => typeof v === "object" && v !== null && !Array.isArray(v) && Object.values(v).every((x) => typeof x === "string");
102
- if (c.type === "sse")
103
- return 'the legacy "sse" transport is not supported; use a streamable HTTP endpoint ("type": "http")';
104
- if (c.type !== undefined && !["stdio", "http", "streamable-http"].includes(c.type))
105
- return `unknown type ${JSON.stringify(c.type)}`;
106
- const http = c.type === "http" || c.type === "streamable-http" || (c.type === undefined && c.command === undefined);
107
- if (http) {
108
- if (typeof c.url !== "string" || !c.url)
109
- return 'needs "command" (stdio) or an http(s) "url"';
110
- if (c.headers !== undefined && !stringMap(c.headers))
111
- return '"headers" must map names to strings';
37
+ let json;
38
+ try {
39
+ json = JSON.parse(text);
40
+ } catch (err) {
41
+ warnings.push(`${file}: ${err instanceof Error ? err.message : String(err)}`);
42
+ continue;
112
43
  }
113
- else {
114
- if (typeof c.command !== "string" || !c.command)
115
- return '"command" must be a non-empty string';
116
- if (c.args !== undefined && !strings(c.args))
117
- return '"args" must be an array of strings';
118
- if (c.env !== undefined && !stringMap(c.env))
119
- return '"env" must map names to strings';
120
- if (c.cwd !== undefined && typeof c.cwd !== "string")
121
- return '"cwd" must be a string';
44
+ const servers = json?.mcpServers;
45
+ if (typeof servers !== "object" || servers === null || Array.isArray(servers)) {
46
+ warnings.push(`${file}: expected { "mcpServers": { ... } }`);
47
+ continue;
122
48
  }
123
- for (const k of ["startupTimeoutMs", "toolTimeoutMs"]) {
124
- if (c[k] !== undefined && !(typeof c[k] === "number" && c[k] > 0))
125
- return `"${k}" must be a positive number`;
49
+ for (const [name, raw] of Object.entries(servers)) {
50
+ const problem = checkConfig(name, raw);
51
+ if (problem) {
52
+ warnings.push(`${file}: MCP server ${JSON.stringify(name)}: ${problem}`);
53
+ continue;
54
+ }
55
+ const missing = [];
56
+ const config = expandConfig(raw, env, missing);
57
+ if (missing.length) {
58
+ warnings.push(`${file}: MCP server ${name} is skipped: environment variable ${[...new Set(missing)].join(", ")} is not set`);
59
+ out.delete(name);
60
+ continue;
61
+ }
62
+ if (config.command === undefined && !/^https?:\/\//.test(config.url)) {
63
+ warnings.push(`${file}: MCP server ${name}: "url" must start with http:// or https://`);
64
+ out.delete(name);
65
+ continue;
66
+ }
67
+ if (config.cwd && !path.isAbsolute(config.cwd))
68
+ config.cwd = path.resolve(path.dirname(file), config.cwd);
69
+ out.set(name, { name, layer, file, config });
126
70
  }
127
- return undefined;
71
+ }
72
+ return { servers: [...out.values()], warnings };
73
+ }
74
+ const SERVER_NAME = /^[A-Za-z0-9_.-]+$/;
75
+ export function checkConfig(name, raw) {
76
+ if (!SERVER_NAME.test(name))
77
+ return "the name may only contain letters, digits, '.', '_' and '-'";
78
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
79
+ return "must be an object";
80
+ const c = raw;
81
+ const strings = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
82
+ const stringMap = (v) => typeof v === "object" && v !== null && !Array.isArray(v) && Object.values(v).every((x) => typeof x === "string");
83
+ if (c.type === "sse")
84
+ return 'the legacy "sse" transport is not supported; use a streamable HTTP endpoint ("type": "http")';
85
+ if (c.type !== undefined && !["stdio", "http", "streamable-http"].includes(c.type))
86
+ return `unknown type ${JSON.stringify(c.type)}`;
87
+ const http = c.type === "http" || c.type === "streamable-http" || c.type === undefined && c.command === undefined;
88
+ if (http) {
89
+ if (typeof c.url !== "string" || !c.url)
90
+ return 'needs "command" (stdio) or an http(s) "url"';
91
+ if (c.headers !== undefined && !stringMap(c.headers))
92
+ return '"headers" must map names to strings';
93
+ } else {
94
+ if (typeof c.command !== "string" || !c.command)
95
+ return '"command" must be a non-empty string';
96
+ if (c.args !== undefined && !strings(c.args))
97
+ return '"args" must be an array of strings';
98
+ if (c.env !== undefined && !stringMap(c.env))
99
+ return '"env" must map names to strings';
100
+ if (c.cwd !== undefined && typeof c.cwd !== "string")
101
+ return '"cwd" must be a string';
102
+ }
103
+ for (const k of ["startupTimeoutMs", "toolTimeoutMs"]) {
104
+ if (c[k] !== undefined && !(typeof c[k] === "number" && c[k] > 0))
105
+ return `"${k}" must be a positive number`;
106
+ }
107
+ return;
128
108
  }
129
- /** ${VAR} 和 ${VAR:-默认值},和 Claude Code 一样;没有设置又没有默认值的变量记进 missing */
130
109
  export function expandEnv(text, env, missing) {
131
- return text.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g, (_, name, fallback) => {
132
- const v = env[name];
133
- if (v !== undefined && v !== "")
134
- return v;
135
- if (fallback !== undefined)
136
- return fallback;
137
- missing.push(name);
138
- return "";
139
- });
110
+ return text.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g, (_, name, fallback) => {
111
+ const v = env[name];
112
+ if (v !== undefined && v !== "")
113
+ return v;
114
+ if (fallback !== undefined)
115
+ return fallback;
116
+ missing.push(name);
117
+ return "";
118
+ });
140
119
  }
141
120
  function expandConfig(c, env, missing) {
142
- const s = (v) => expandEnv(v, env, missing);
143
- const map = (m) => (m ? Object.fromEntries(Object.entries(m).map(([k, v]) => [k, s(v)])) : undefined);
144
- return {
145
- ...c,
146
- command: c.command === undefined ? undefined : s(c.command),
147
- args: c.args?.map(s),
148
- env: map(c.env),
149
- cwd: c.cwd === undefined ? undefined : s(c.cwd),
150
- url: c.url === undefined ? undefined : s(c.url),
151
- headers: map(c.headers),
152
- };
121
+ const s = (v) => expandEnv(v, env, missing);
122
+ const map = (m) => m ? Object.fromEntries(Object.entries(m).map(([k, v]) => [k, s(v)])) : undefined;
123
+ return {
124
+ ...c,
125
+ command: c.command === undefined ? undefined : s(c.command),
126
+ args: c.args?.map(s),
127
+ env: map(c.env),
128
+ cwd: c.cwd === undefined ? undefined : s(c.cwd),
129
+ url: c.url === undefined ? undefined : s(c.url),
130
+ headers: map(c.headers)
131
+ };
153
132
  }
154
- /** 项目层服务的确认记录:同一个仓库里同样的配置只问一次。配置变了(包括展开后的环境变量)就要重新确认 */
155
133
  export function mcpTrustHash(root, entry) {
156
- const { command, args, env, cwd, url, headers, type } = entry.config;
157
- // 请求头里通常是密钥,只记名字
158
- const spec = JSON.stringify({ type, command, args, env, cwd, url, headers: headers ? Object.keys(headers).sort() : undefined });
159
- return createHash("sha256").update(`jade-mcp\0${root}\0${entry.name}\0${spec}`).digest("hex");
134
+ const { command, args, env, cwd, url, headers, type } = entry.config;
135
+ const spec = JSON.stringify({ type, command, args, env, cwd, url, headers: headers ? Object.keys(headers).sort() : undefined });
136
+ return createHash("sha256").update(`jade-mcp\x00${root}\x00${entry.name}\x00${spec}`).digest("hex");
137
+ }
138
+ const KNOWN_MAX_AGE_MS = 90 * 24 * 3600000;
139
+ export function mcpCacheKey(entry) {
140
+ const { command, args, env, cwd, url, headers, type } = entry.config;
141
+ const spec = JSON.stringify({ type, command, args, env, cwd, url, headers: headers ? Object.keys(headers).sort() : undefined });
142
+ return createHash("sha256").update(`jade-mcp-tools\x00${entry.file}\x00${entry.name}\x00${spec}`).digest("hex");
143
+ }
144
+
145
+ export class McpToolCache {
146
+ file;
147
+ #entries = {};
148
+ #writing = Promise.resolve();
149
+ constructor(home) {
150
+ this.file = path.join(home, "state", "mcp-tools.json");
151
+ }
152
+ async load() {
153
+ try {
154
+ const raw = JSON.parse(await readFile(this.file, "utf8"));
155
+ if (raw?.version === 1 && raw.servers && typeof raw.servers === "object")
156
+ this.#entries = raw.servers;
157
+ } catch {}
158
+ }
159
+ get(entry) {
160
+ const e = this.#entries[mcpCacheKey(entry)];
161
+ return e && Array.isArray(e.tools) ? { tools: e.tools, ...e.instructions ? { instructions: e.instructions } : {} } : undefined;
162
+ }
163
+ put(entry, known) {
164
+ const now = Date.now();
165
+ this.#entries[mcpCacheKey(entry)] = { tools: known.tools, ...known.instructions ? { instructions: known.instructions } : {}, at: now };
166
+ for (const [k, e] of Object.entries(this.#entries))
167
+ if (!(now - e.at < KNOWN_MAX_AGE_MS))
168
+ delete this.#entries[k];
169
+ const body = `${JSON.stringify({ version: 1, servers: this.#entries })}
170
+ `;
171
+ this.#writing = this.#writing.then(async () => {
172
+ try {
173
+ await mkdir(path.dirname(this.file), { recursive: true });
174
+ const tmp = `${this.file}.${process.pid}.tmp`;
175
+ await writeFile(tmp, body);
176
+ await rename(tmp, this.file);
177
+ } catch {}
178
+ });
179
+ return this.#writing;
180
+ }
160
181
  }
161
- /** 给用户看的启动方式 */
162
182
  export function describeServer(c) {
163
- return c.command !== undefined ? [c.command, ...(c.args ?? [])].join(" ") : `${c.url}`;
183
+ return c.command !== undefined ? [c.command, ...c.args ?? []].join(" ") : `${c.url}`;
164
184
  }
185
+
165
186
  export class McpError extends Error {
166
- code;
167
- constructor(message, code) {
168
- super(message);
169
- this.name = "McpError";
170
- this.code = code;
171
- }
187
+ code;
188
+ constructor(message, code) {
189
+ super(message);
190
+ this.name = "McpError";
191
+ this.code = code;
192
+ }
172
193
  }
173
- /** 一个 MCP 服务的连接 */
194
+
174
195
  export class McpClient {
175
- entry;
176
- status = "disconnected";
177
- error;
178
- serverInfo;
179
- instructions;
180
- tools = [];
181
- stderr = [];
182
- #opts;
183
- #transport;
184
- #connecting;
185
- #closing = false;
186
- constructor(entry, opts) {
187
- this.entry = entry;
188
- this.#opts = opts;
189
- }
190
- get name() {
191
- return this.entry.name;
196
+ entry;
197
+ status = "disconnected";
198
+ error;
199
+ serverInfo;
200
+ instructions;
201
+ tools = [];
202
+ stderr = [];
203
+ known;
204
+ #opts;
205
+ #transport;
206
+ #connecting;
207
+ #closing = false;
208
+ #dropped = false;
209
+ constructor(entry, opts) {
210
+ this.entry = entry;
211
+ this.#opts = opts;
212
+ }
213
+ get name() {
214
+ return this.entry.name;
215
+ }
216
+ connect() {
217
+ this.#connecting ??= this.#connect().finally(() => this.#connecting = undefined);
218
+ return this.#connecting;
219
+ }
220
+ async#connect() {
221
+ this.status = "connecting";
222
+ this.error = undefined;
223
+ this.#closing = false;
224
+ this.#dropped = false;
225
+ const c = this.entry.config;
226
+ const signal = AbortSignal.timeout(c.startupTimeoutMs ?? 30000);
227
+ try {
228
+ const t = c.command !== undefined ? stdioTransport(c, this.#opts.cwd, this.stderr) : httpTransport(c, this.#opts.fetch ?? fetch);
229
+ this.#transport = t;
230
+ t.onNotification = (method) => {
231
+ if (method === "notifications/tools/list_changed" && this.#transport === t && this.status === "connected")
232
+ this.#relist(t);
233
+ };
234
+ t.closed.then((why) => {
235
+ if (this.#transport !== t)
236
+ return;
237
+ this.#transport = undefined;
238
+ if (this.#closing)
239
+ return;
240
+ this.status = "failed";
241
+ this.error = why;
242
+ this.#dropped = this.tools.length > 0;
243
+ this.#opts.onDisconnect?.(this, why);
244
+ });
245
+ const init = await t.request("initialize", { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: CLIENT_INFO }, signal);
246
+ this.serverInfo = init?.serverInfo;
247
+ this.instructions = typeof init?.instructions === "string" && init.instructions.trim() ? init.instructions.trim() : undefined;
248
+ await t.notify("notifications/initialized");
249
+ this.tools = init?.capabilities?.tools === undefined ? [] : await this.#listTools(t, signal);
250
+ this.status = "connected";
251
+ } catch (err) {
252
+ const why = signal.aborted ? `did not finish starting within ${(c.startupTimeoutMs ?? 30000) / 1000}s` : errorText(err);
253
+ this.status = "failed";
254
+ this.error = why;
255
+ await this.close().catch(() => {});
256
+ this.status = "failed";
257
+ try {
258
+ this.#opts.onFailed?.(this);
259
+ } catch {}
260
+ throw new McpError(why);
192
261
  }
193
- /** 启动、初始化并列出工具;已经在连接时等同一次连接 */
194
- connect() {
195
- this.#connecting ??= this.#connect().finally(() => (this.#connecting = undefined));
196
- return this.#connecting;
262
+ this.#listed();
263
+ }
264
+ #listed() {
265
+ try {
266
+ this.#opts.onTools?.(this);
267
+ } catch {}
268
+ }
269
+ #relisting;
270
+ #relistAgain = false;
271
+ #relist(t) {
272
+ if (this.#relisting) {
273
+ this.#relistAgain = true;
274
+ return this.#relisting;
197
275
  }
198
- async #connect() {
199
- this.status = "connecting";
200
- this.error = undefined;
201
- this.#closing = false;
202
- const c = this.entry.config;
203
- const signal = AbortSignal.timeout(c.startupTimeoutMs ?? 30_000);
276
+ this.#relisting = (async () => {
277
+ do {
278
+ this.#relistAgain = false;
204
279
  try {
205
- const t = c.command !== undefined ? stdioTransport(c, this.#opts.cwd, this.stderr) : httpTransport(c, this.#opts.fetch ?? fetch);
206
- this.#transport = t;
207
- void t.closed.then((why) => {
208
- if (this.#transport !== t)
209
- return;
210
- this.#transport = undefined;
211
- if (this.#closing)
212
- return;
213
- this.status = "failed";
214
- this.error = why;
215
- this.#opts.onDisconnect?.(this, why);
216
- });
217
- const init = (await t.request("initialize", { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: CLIENT_INFO }, signal));
218
- this.serverInfo = init?.serverInfo;
219
- this.instructions = typeof init?.instructions === "string" && init.instructions.trim() ? init.instructions.trim() : undefined;
220
- await t.notify("notifications/initialized");
221
- this.tools = init?.capabilities?.tools === undefined ? [] : await this.#listTools(t, signal);
222
- this.status = "connected";
223
- }
224
- catch (err) {
225
- const why = signal.aborted ? `did not finish starting within ${(c.startupTimeoutMs ?? 30_000) / 1000}s` : errorText(err);
226
- this.status = "failed";
227
- this.error = why;
228
- await this.close().catch(() => { });
229
- this.status = "failed";
230
- throw new McpError(why);
280
+ const tools = await this.#listTools(t, AbortSignal.timeout(this.entry.config.startupTimeoutMs ?? 30000));
281
+ if (this.#transport !== t)
282
+ return;
283
+ this.tools = tools;
284
+ this.#listed();
285
+ } catch {
286
+ return;
231
287
  }
288
+ } while (this.#relistAgain);
289
+ })().finally(() => this.#relisting = undefined);
290
+ return this.#relisting;
291
+ }
292
+ offered() {
293
+ if (this.status === "connected" || this.#dropped)
294
+ return this.tools;
295
+ if (this.status === "failed")
296
+ return [];
297
+ return this.known?.tools ?? [];
298
+ }
299
+ offeredInstructions() {
300
+ if (this.status === "connected" || this.#dropped)
301
+ return this.instructions;
302
+ if (this.status === "failed")
303
+ return;
304
+ return this.known?.instructions;
305
+ }
306
+ async#listTools(t, signal) {
307
+ const tools = [];
308
+ let cursor;
309
+ for (let page = 0;page < 100; page++) {
310
+ const r = await t.request("tools/list", cursor ? { cursor } : undefined, signal);
311
+ for (const tool of r?.tools ?? [])
312
+ if (tool && typeof tool.name === "string")
313
+ tools.push(tool);
314
+ cursor = typeof r?.nextCursor === "string" && r.nextCursor ? r.nextCursor : undefined;
315
+ if (!cursor)
316
+ break;
232
317
  }
233
- async #listTools(t, signal) {
234
- const tools = [];
235
- let cursor;
236
- for (let page = 0; page < 100; page++) {
237
- const r = (await t.request("tools/list", cursor ? { cursor } : undefined, signal));
238
- for (const tool of r?.tools ?? [])
239
- if (tool && typeof tool.name === "string")
240
- tools.push(tool);
241
- cursor = typeof r?.nextCursor === "string" && r.nextCursor ? r.nextCursor : undefined;
242
- if (!cursor)
243
- break;
244
- }
245
- return tools;
318
+ return tools;
319
+ }
320
+ async callTool(name, args, signal) {
321
+ if (this.status !== "connected" || !this.#transport)
322
+ await this.connect();
323
+ if (!this.tools.some((x) => x.name === name))
324
+ throw new McpError(`the server no longer offers the tool "${name}"; /mcp lists its current tools`);
325
+ const t = this.#transport;
326
+ const limit = AbortSignal.timeout(this.entry.config.toolTimeoutMs ?? 600000);
327
+ const both = AbortSignal.any([signal, limit]);
328
+ try {
329
+ return await t.request("tools/call", { name, arguments: args ?? {} }, both);
330
+ } catch (err) {
331
+ if (limit.aborted && !signal.aborted)
332
+ throw new McpError(`timed out after ${(this.entry.config.toolTimeoutMs ?? 600000) / 1000}s`);
333
+ throw err;
246
334
  }
247
- /** 调用工具。连接断了先重连一次 */
248
- async callTool(name, args, signal) {
249
- if (this.status !== "connected" || !this.#transport)
250
- await this.connect();
251
- const t = this.#transport;
252
- const limit = AbortSignal.timeout(this.entry.config.toolTimeoutMs ?? 600_000);
253
- const both = AbortSignal.any([signal, limit]);
254
- try {
255
- return (await t.request("tools/call", { name, arguments: args ?? {} }, both));
256
- }
257
- catch (err) {
258
- if (limit.aborted && !signal.aborted)
259
- throw new McpError(`timed out after ${(this.entry.config.toolTimeoutMs ?? 600_000) / 1000}s`);
260
- throw err;
261
- }
335
+ }
336
+ async close() {
337
+ this.#closing = true;
338
+ const t = this.#transport;
339
+ this.#transport = undefined;
340
+ if (this.status !== "failed")
341
+ this.status = "disconnected";
342
+ await t?.close();
343
+ }
344
+ }
345
+ function stdioTransport(c, cwd, stderr) {
346
+ const { file, args, verbatim } = resolveCommand(c.command, c.args ?? []);
347
+ const child = spawn(file, args, {
348
+ cwd: c.cwd ?? cwd,
349
+ env: mergeEnv(c.env),
350
+ stdio: ["pipe", "pipe", "pipe"],
351
+ windowsHide: true,
352
+ windowsVerbatimArguments: verbatim,
353
+ detached: process.platform !== "win32"
354
+ });
355
+ const rpc = new Rpc((msg) => {
356
+ if (child.stdin?.writable)
357
+ child.stdin.write(JSON.stringify(msg) + `
358
+ `);
359
+ });
360
+ let partialErr = "";
361
+ child.stderr.setEncoding("utf8");
362
+ child.stderr.on("data", (text) => {
363
+ const lines = (partialErr + text).split(/\r?\n/);
364
+ partialErr = lines.pop() ?? "";
365
+ stderr.push(...lines.filter((l) => l.trim()));
366
+ stderr.splice(0, Math.max(0, stderr.length - STDERR_LINES));
367
+ });
368
+ let buf = "";
369
+ child.stdout.setEncoding("utf8");
370
+ child.stdout.on("data", (text) => {
371
+ buf += text;
372
+ let i;
373
+ while ((i = buf.indexOf(`
374
+ `)) >= 0) {
375
+ const line = buf.slice(0, i).trim();
376
+ buf = buf.slice(i + 1);
377
+ if (!line)
378
+ continue;
379
+ try {
380
+ rpc.receive(JSON.parse(line));
381
+ } catch {}
262
382
  }
383
+ });
384
+ child.stdin.on("error", () => {});
385
+ const closed = new Promise((resolve) => {
386
+ child.on("error", (err) => resolve(`could not start ${c.command}: ${err.message}`));
387
+ child.on("close", (code, sig) => resolve(`exited (${sig ?? `code ${code}`})${stderr.length ? `: ${stderr.at(-1)}` : ""}`));
388
+ });
389
+ closed.then((why) => rpc.fail(new McpError(`server ${why}`)));
390
+ const t = {
391
+ request: (method, params, signal) => rpc.request(method, params, signal),
392
+ notify: async (method, params) => rpc.send({ jsonrpc: "2.0", method, ...params ? { params } : {} }),
393
+ closed,
263
394
  async close() {
264
- this.#closing = true;
265
- const t = this.#transport;
266
- this.#transport = undefined;
267
- if (this.status !== "failed")
268
- this.status = "disconnected";
269
- await t?.close();
395
+ child.stdin?.end();
396
+ const done = await Promise.race([closed.then(() => true), new Promise((r) => setTimeout(() => r(false), 2000).unref())]);
397
+ if (!done)
398
+ killTree(child);
270
399
  }
400
+ };
401
+ rpc.onNotify = (method) => t.onNotification?.(method);
402
+ return t;
271
403
  }
272
- // ---------- 传输:stdio ----------
273
- function stdioTransport(c, cwd, stderr) {
274
- const { file, args, verbatim } = resolveCommand(c.command, c.args ?? []);
275
- const child = spawn(file, args, {
276
- cwd: c.cwd ?? cwd,
277
- env: mergeEnv(c.env),
278
- stdio: ["pipe", "pipe", "pipe"],
279
- windowsHide: true,
280
- windowsVerbatimArguments: verbatim,
281
- detached: process.platform !== "win32",
282
- });
283
- const rpc = new Rpc((msg) => {
284
- if (child.stdin?.writable)
285
- child.stdin.write(JSON.stringify(msg) + "\n");
286
- });
287
- let partialErr = "";
288
- child.stderr.setEncoding("utf8");
289
- child.stderr.on("data", (text) => {
290
- const lines = (partialErr + text).split(/\r?\n/);
291
- partialErr = lines.pop() ?? "";
292
- stderr.push(...lines.filter((l) => l.trim()));
293
- stderr.splice(0, Math.max(0, stderr.length - STDERR_LINES));
294
- });
295
- let buf = "";
296
- child.stdout.setEncoding("utf8");
297
- child.stdout.on("data", (text) => {
298
- buf += text;
299
- let i;
300
- while ((i = buf.indexOf("\n")) >= 0) {
301
- const line = buf.slice(0, i).trim();
302
- buf = buf.slice(i + 1);
303
- if (!line)
304
- continue;
305
- try {
306
- rpc.receive(JSON.parse(line));
307
- }
308
- catch {
309
- // 有的服务往 stdout 打日志;不是 JSON 的行忽略
310
- }
311
- }
312
- });
313
- child.stdin.on("error", () => { });
314
- const closed = new Promise((resolve) => {
315
- child.on("error", (err) => resolve(`could not start ${c.command}: ${err.message}`));
316
- child.on("close", (code, sig) => resolve(`exited (${sig ?? `code ${code}`})${stderr.length ? `: ${stderr.at(-1)}` : ""}`));
317
- });
318
- void closed.then((why) => rpc.fail(new McpError(`server ${why}`)));
319
- return {
320
- request: (method, params, signal) => rpc.request(method, params, signal),
321
- notify: async (method, params) => rpc.send({ jsonrpc: "2.0", method, ...(params ? { params } : {}) }),
322
- closed,
323
- async close() {
324
- child.stdin?.end();
325
- const done = await Promise.race([closed.then(() => true), new Promise((r) => setTimeout(() => r(false), 2_000).unref())]);
326
- if (!done)
327
- killTree(child);
328
- },
329
- };
330
- }
331
- /**
332
- * Windows 上 npx、npm 这类命令是 .cmd 脚本,不经过 shell 无法启动:找到它时改用 cmd.exe /c 启动。
333
- * MCP 的配置里大多写的是 "command": "npx"
334
- */
335
404
  function resolveCommand(command, args) {
336
- if (process.platform !== "win32" || /[\\/]/.test(command) || /\.(exe|com)$/i.test(command))
337
- return { file: command, args, verbatim: false };
338
- const exts = /\.(cmd|bat)$/i.test(command) ? [""] : (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";");
339
- for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
340
- if (!dir)
341
- continue;
342
- for (const ext of exts) {
343
- const full = path.join(dir, command + ext.toLowerCase());
344
- let isFile = false;
345
- try {
346
- isFile = statSync(full).isFile();
347
- }
348
- catch {
349
- continue;
350
- }
351
- if (!isFile)
352
- continue;
353
- if (/\.(exe|com)$/i.test(full))
354
- return { file: full, args, verbatim: false };
355
- if (/\.(cmd|bat)$/i.test(full)) {
356
- const line = [full, ...args].map(cmdQuote).join(" ");
357
- return { file: process.env.ComSpec ?? "cmd.exe", args: ["/d", "/s", "/c", `"${line}"`], verbatim: true };
358
- }
359
- }
360
- }
405
+ if (process.platform !== "win32" || /[\\/]/.test(command) || /\.(exe|com)$/i.test(command))
361
406
  return { file: command, args, verbatim: false };
407
+ const exts = /\.(cmd|bat)$/i.test(command) ? [""] : (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";");
408
+ for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
409
+ if (!dir)
410
+ continue;
411
+ for (const ext of exts) {
412
+ const full = path.join(dir, command + ext.toLowerCase());
413
+ let isFile = false;
414
+ try {
415
+ isFile = statSync(full).isFile();
416
+ } catch {
417
+ continue;
418
+ }
419
+ if (!isFile)
420
+ continue;
421
+ if (/\.(exe|com)$/i.test(full))
422
+ return { file: full, args, verbatim: false };
423
+ if (/\.(cmd|bat)$/i.test(full)) {
424
+ const line = [full, ...args].map(cmdQuote).join(" ");
425
+ return { file: process.env.ComSpec ?? "cmd.exe", args: ["/d", "/s", "/c", `"${line}"`], verbatim: true };
426
+ }
427
+ }
428
+ }
429
+ return { file: command, args, verbatim: false };
362
430
  }
363
- /** cmd.exe 的引号规则:含空格或特殊字符的参数用双引号括起来,里面的双引号写两次 */
364
431
  function cmdQuote(arg) {
365
- if (arg && !/[\s"&|<>^%!(),;=]/.test(arg))
366
- return arg;
367
- return `"${arg.replace(/"/g, '""')}"`;
432
+ if (arg && !/[\s"&|<>^%!(),;=]/.test(arg))
433
+ return arg;
434
+ return `"${arg.replace(/"/g, '""')}"`;
368
435
  }
369
436
  function mergeEnv(extra = {}) {
370
- const env = { ...process.env };
371
- if (process.platform === "win32") {
372
- const keys = new Set(Object.keys(extra).map((k) => k.toUpperCase()));
373
- for (const k of Object.keys(env))
374
- if (keys.has(k.toUpperCase()))
375
- delete env[k];
376
- }
377
- return { ...env, ...extra };
437
+ const env = { ...process.env };
438
+ if (process.platform === "win32") {
439
+ const keys = new Set(Object.keys(extra).map((k) => k.toUpperCase()));
440
+ for (const k of Object.keys(env))
441
+ if (keys.has(k.toUpperCase()))
442
+ delete env[k];
443
+ }
444
+ return { ...env, ...extra };
378
445
  }
379
446
  function killTree(child) {
380
- if (child.pid === undefined)
381
- return;
382
- if (process.platform === "win32") {
383
- spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true }).on("error", () => child.kill());
384
- return;
385
- }
386
- try {
387
- process.kill(-child.pid, "SIGKILL");
388
- }
389
- catch {
390
- child.kill("SIGKILL");
391
- }
447
+ if (child.pid === undefined)
448
+ return;
449
+ if (process.platform === "win32") {
450
+ spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true }).on("error", () => child.kill());
451
+ return;
452
+ }
453
+ try {
454
+ process.kill(-child.pid, "SIGKILL");
455
+ } catch {
456
+ child.kill("SIGKILL");
457
+ }
392
458
  }
393
- // ---------- 传输:Streamable HTTP ----------
394
459
  function httpTransport(c, doFetch) {
395
- let session;
396
- let protocol;
397
- let nextId = 1;
398
- const abort = new AbortController();
399
- let markClosed;
400
- const closed = new Promise((r) => (markClosed = r));
401
- const headers = () => ({
402
- ...c.headers,
403
- "content-type": "application/json",
404
- accept: "application/json, text/event-stream",
405
- ...(session ? { "mcp-session-id": session } : {}),
406
- ...(protocol ? { "mcp-protocol-version": protocol } : {}),
407
- });
408
- async function post(body, signal) {
409
- const res = await doFetch(c.url, { method: "POST", headers: headers(), body: JSON.stringify(body), signal: AbortSignal.any([signal, abort.signal]) });
410
- const sid = res.headers.get("mcp-session-id");
411
- if (sid)
412
- session = sid;
413
- return res;
460
+ let session;
461
+ let protocol;
462
+ let nextId = 1;
463
+ const abort = new AbortController;
464
+ let markClosed;
465
+ const closed = new Promise((r) => markClosed = r);
466
+ const headers = () => ({
467
+ ...c.headers,
468
+ "content-type": "application/json",
469
+ accept: "application/json, text/event-stream",
470
+ ...session ? { "mcp-session-id": session } : {},
471
+ ...protocol ? { "mcp-protocol-version": protocol } : {}
472
+ });
473
+ async function post(body, signal) {
474
+ const res = await doFetch(c.url, { method: "POST", headers: headers(), body: JSON.stringify(body), signal: AbortSignal.any([signal, abort.signal]) });
475
+ const sid = res.headers.get("mcp-session-id");
476
+ if (sid)
477
+ session = sid;
478
+ return res;
479
+ }
480
+ const t = {
481
+ async request(method, params, signal) {
482
+ const id = nextId++;
483
+ const res = await post({ jsonrpc: "2.0", id, method, ...params ? { params } : {} }, signal);
484
+ if (!res.ok) {
485
+ const text = (await res.text().catch(() => "")).slice(0, 500);
486
+ throw new McpError(`HTTP ${res.status}${res.status === 401 ? " (unauthorized: check the headers in the MCP config)" : ""}${text ? `: ${text}` : ""}`);
487
+ }
488
+ const type = res.headers.get("content-type") ?? "";
489
+ const reply = type.includes("text/event-stream") ? await fromSse(res, id, signal, (m) => t.onNotification?.(m)) : await res.json();
490
+ const result = unwrap(reply);
491
+ if (method === "initialize")
492
+ protocol = result?.protocolVersion ?? PROTOCOL_VERSION;
493
+ return result;
494
+ },
495
+ async notify(method, params) {
496
+ const res = await post({ jsonrpc: "2.0", method, ...params ? { params } : {} }, AbortSignal.timeout(1e4));
497
+ await res.body?.cancel().catch(() => {});
498
+ },
499
+ closed,
500
+ async close() {
501
+ if (session) {
502
+ await doFetch(c.url, { method: "DELETE", headers: headers(), signal: AbortSignal.timeout(2000) }).catch(() => {});
503
+ }
504
+ abort.abort();
505
+ markClosed("closed");
414
506
  }
415
- return {
416
- async request(method, params, signal) {
417
- const id = nextId++;
418
- const res = await post({ jsonrpc: "2.0", id, method, ...(params ? { params } : {}) }, signal);
419
- if (!res.ok) {
420
- const text = (await res.text().catch(() => "")).slice(0, 500);
421
- throw new McpError(`HTTP ${res.status}${res.status === 401 ? " (unauthorized: check the headers in the MCP config)" : ""}${text ? `: ${text}` : ""}`);
422
- }
423
- const type = res.headers.get("content-type") ?? "";
424
- const reply = type.includes("text/event-stream") ? await fromSse(res, id, signal) : (await res.json());
425
- const result = unwrap(reply);
426
- if (method === "initialize")
427
- protocol = result?.protocolVersion ?? PROTOCOL_VERSION;
428
- return result;
429
- },
430
- async notify(method, params) {
431
- const res = await post({ jsonrpc: "2.0", method, ...(params ? { params } : {}) }, AbortSignal.timeout(10_000));
432
- await res.body?.cancel().catch(() => { });
433
- },
434
- closed,
435
- async close() {
436
- if (session) {
437
- await doFetch(c.url, { method: "DELETE", headers: headers(), signal: AbortSignal.timeout(2_000) }).catch(() => { });
438
- }
439
- abort.abort();
440
- markClosed("closed");
441
- },
442
- };
507
+ };
508
+ return t;
443
509
  }
444
- /** 从 SSE 流里找到 id 对应的回复;流里其他的消息(通知、服务端的请求)忽略 */
445
- async function fromSse(res, id, signal) {
446
- const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
447
- let buf = "";
448
- try {
449
- while (!signal.aborted) {
450
- const { value, done } = await reader.read();
451
- if (done)
452
- break;
453
- buf += value;
454
- let i;
455
- while ((i = buf.search(/\r?\n\r?\n/)) >= 0) {
456
- const event = buf.slice(0, i);
457
- buf = buf.slice(i).replace(/^\r?\n\r?\n/, "");
458
- const data = event
459
- .split(/\r?\n/)
460
- .filter((l) => l.startsWith("data:"))
461
- .map((l) => l.slice(5).replace(/^ /, ""))
462
- .join("\n");
463
- if (!data)
464
- continue;
465
- try {
466
- const msg = JSON.parse(data);
467
- if (msg.id === id && (msg.result !== undefined || msg.error !== undefined))
468
- return msg;
469
- }
470
- catch {
471
- // 不是 JSON 的事件忽略
472
- }
473
- }
474
- }
475
- }
476
- finally {
477
- await reader.cancel().catch(() => { });
510
+ async function fromSse(res, id, signal, onNotify) {
511
+ const reader = res.body.pipeThrough(new TextDecoderStream).getReader();
512
+ let buf = "";
513
+ try {
514
+ while (!signal.aborted) {
515
+ const { value, done } = await reader.read();
516
+ if (done)
517
+ break;
518
+ buf += value;
519
+ let i;
520
+ while ((i = buf.search(/\r?\n\r?\n/)) >= 0) {
521
+ const event = buf.slice(0, i);
522
+ buf = buf.slice(i).replace(/^\r?\n\r?\n/, "");
523
+ const data = event.split(/\r?\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(5).replace(/^ /, "")).join(`
524
+ `);
525
+ if (!data)
526
+ continue;
527
+ try {
528
+ const msg = JSON.parse(data);
529
+ if (msg.id === id && (msg.result !== undefined || msg.error !== undefined))
530
+ return msg;
531
+ if (msg.id === undefined && typeof msg.method === "string")
532
+ onNotify(msg.method);
533
+ } catch {}
534
+ }
478
535
  }
479
- throw new McpError(signal.aborted ? "request aborted" : "the server closed the stream without replying");
536
+ } finally {
537
+ await reader.cancel().catch(() => {});
538
+ }
539
+ throw new McpError(signal.aborted ? "request aborted" : "the server closed the stream without replying");
480
540
  }
481
541
  function unwrap(msg) {
482
- if (msg?.error)
483
- throw new McpError(msg.error.message ?? "error", msg.error.code);
484
- return msg?.result;
542
+ if (msg?.error)
543
+ throw new McpError(msg.error.message ?? "error", msg.error.code);
544
+ return msg?.result;
485
545
  }
546
+
486
547
  class Rpc {
487
- #send;
488
- #nextId = 1;
489
- #pending = new Map();
490
- #dead;
491
- constructor(send) {
492
- this.#send = send;
493
- }
494
- send(msg) {
495
- this.#send(msg);
496
- }
497
- request(method, params, signal) {
498
- if (this.#dead)
499
- return Promise.reject(this.#dead);
500
- const id = this.#nextId++;
501
- return new Promise((resolve, reject) => {
502
- const onAbort = () => {
503
- this.#pending.delete(id);
504
- this.#send({ jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: id, reason: "cancelled by the client" } });
505
- reject(signal.reason ?? new McpError("aborted"));
506
- };
507
- if (signal.aborted)
508
- return onAbort();
509
- signal.addEventListener("abort", onAbort, { once: true });
510
- this.#pending.set(id, {
511
- resolve: (v) => (signal.removeEventListener("abort", onAbort), resolve(v)),
512
- reject: (e) => (signal.removeEventListener("abort", onAbort), reject(e)),
513
- });
514
- this.#send({ jsonrpc: "2.0", id, method, ...(params ? { params } : {}) });
515
- });
516
- }
517
- receive(msg) {
518
- if (msg.method !== undefined) {
519
- // 服务端发来的请求:只支持 ping,其他的回复"不支持",免得服务端一直等
520
- if (msg.id === undefined)
521
- return;
522
- if (msg.method === "ping")
523
- this.#send({ jsonrpc: "2.0", id: msg.id, result: {} });
524
- else
525
- this.#send({ jsonrpc: "2.0", id: msg.id, error: { code: -32601, message: `jade does not support ${msg.method}` } });
526
- return;
527
- }
528
- if (msg.id === undefined)
529
- return;
530
- const p = this.#pending.get(msg.id);
531
- if (!p)
532
- return;
533
- this.#pending.delete(msg.id);
534
- if (msg.error)
535
- p.reject(new McpError(msg.error.message ?? "error", msg.error.code));
536
- else
537
- p.resolve(msg.result);
538
- }
539
- fail(err) {
540
- this.#dead = err;
541
- for (const p of this.#pending.values())
542
- p.reject(err);
543
- this.#pending.clear();
548
+ #send;
549
+ #nextId = 1;
550
+ #pending = new Map;
551
+ #dead;
552
+ onNotify;
553
+ constructor(send) {
554
+ this.#send = send;
555
+ }
556
+ send(msg) {
557
+ this.#send(msg);
558
+ }
559
+ request(method, params, signal) {
560
+ if (this.#dead)
561
+ return Promise.reject(this.#dead);
562
+ const id = this.#nextId++;
563
+ return new Promise((resolve, reject) => {
564
+ const onAbort = () => {
565
+ this.#pending.delete(id);
566
+ this.#send({ jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: id, reason: "cancelled by the client" } });
567
+ reject(signal.reason ?? new McpError("aborted"));
568
+ };
569
+ if (signal.aborted)
570
+ return onAbort();
571
+ signal.addEventListener("abort", onAbort, { once: true });
572
+ this.#pending.set(id, {
573
+ resolve: (v) => (signal.removeEventListener("abort", onAbort), resolve(v)),
574
+ reject: (e) => (signal.removeEventListener("abort", onAbort), reject(e))
575
+ });
576
+ this.#send({ jsonrpc: "2.0", id, method, ...params ? { params } : {} });
577
+ });
578
+ }
579
+ receive(msg) {
580
+ if (msg.method !== undefined) {
581
+ if (msg.id === undefined) {
582
+ try {
583
+ this.onNotify?.(msg.method);
584
+ } catch {}
585
+ return;
586
+ }
587
+ if (msg.method === "ping")
588
+ this.#send({ jsonrpc: "2.0", id: msg.id, result: {} });
589
+ else
590
+ this.#send({ jsonrpc: "2.0", id: msg.id, error: { code: -32601, message: `jade does not support ${msg.method}` } });
591
+ return;
544
592
  }
593
+ if (msg.id === undefined)
594
+ return;
595
+ const p = this.#pending.get(msg.id);
596
+ if (!p)
597
+ return;
598
+ this.#pending.delete(msg.id);
599
+ if (msg.error)
600
+ p.reject(new McpError(msg.error.message ?? "error", msg.error.code));
601
+ else
602
+ p.resolve(msg.result);
603
+ }
604
+ fail(err) {
605
+ this.#dead = err;
606
+ for (const p of this.#pending.values())
607
+ p.reject(err);
608
+ this.#pending.clear();
609
+ }
545
610
  }
546
- // ---------- 工具 ----------
547
- /** mcp__<服务>__<工具>,和 Claude Code 一样;只保留字母数字、_、-,超长时截断并加上哈希避免重名 */
548
611
  export function mcpToolName(server, tool) {
549
- const clean = (s) => s.replace(/[^A-Za-z0-9_-]/g, "_");
550
- const full = `mcp__${clean(server)}__${clean(tool)}`;
551
- if (full.length <= MAX_TOOL_NAME)
552
- return full;
553
- const hash = createHash("sha256").update(`${server}\0${tool}`).digest("hex").slice(0, 8);
554
- return `${full.slice(0, MAX_TOOL_NAME - 9)}_${hash}`;
612
+ const clean = (s) => s.replace(/[^A-Za-z0-9_-]/g, "_");
613
+ const full = `mcp__${clean(server)}__${clean(tool)}`;
614
+ if (full.length <= MAX_TOOL_NAME)
615
+ return full;
616
+ const hash = createHash("sha256").update(`${server}\x00${tool}`).digest("hex").slice(0, 8);
617
+ return `${full.slice(0, MAX_TOOL_NAME - 9)}_${hash}`;
555
618
  }
556
- /** 把已连接的服务的工具变成 jade 的工具;readOnly 为 true 时只要声明了只读的工具(给子 Agent) */
557
619
  export function mcpTools(clients, opts = {}) {
558
- const out = [];
559
- const names = new Set();
560
- for (const client of clients) {
561
- if (client.status !== "connected")
562
- continue;
563
- for (const info of client.tools) {
564
- const readOnly = info.annotations?.readOnlyHint === true;
565
- if (opts.readOnly && !readOnly)
566
- continue;
567
- const name = mcpToolName(client.name, info.name);
568
- if (names.has(name))
569
- continue;
570
- names.add(name);
571
- const schema = info.inputSchema && typeof info.inputSchema === "object" ? info.inputSchema : { type: "object" };
572
- out.push({
573
- name,
574
- description: `${(info.description ?? info.title ?? info.annotations?.title ?? info.name).trim()}\n\n(Tool "${info.name}" from the MCP server "${client.name}".)`,
575
- inputSchema: { type: "object", ...schema },
576
- // 服务没有声明只读的,都按有外部副作用处理:ask 模式下先问,auto 模式下先交给审查
577
- effect: readOnly ? "read" : "external",
578
- concurrency: readOnly ? "safe" : "exclusive",
579
- idempotent: readOnly || info.annotations?.idempotentHint === true,
580
- async execute(input, ctx) {
581
- try {
582
- const r = await client.callTool(info.name, input, ctx.signal);
583
- return { content: toBlocks(name, r), isError: r?.isError === true };
584
- }
585
- catch (err) {
586
- if (ctx.signal.aborted)
587
- throw err;
588
- return { content: `MCP server "${client.name}" failed: ${errorText(err)}`, isError: true };
589
- }
590
- },
591
- });
620
+ const out = [];
621
+ const names = new Set;
622
+ for (const client of clients) {
623
+ for (const info of client.offered()) {
624
+ const readOnly = info.annotations?.readOnlyHint === true;
625
+ if (opts.readOnly && !readOnly)
626
+ continue;
627
+ const name = mcpToolName(client.name, info.name);
628
+ if (names.has(name))
629
+ continue;
630
+ names.add(name);
631
+ const schema = info.inputSchema && typeof info.inputSchema === "object" ? info.inputSchema : { type: "object" };
632
+ out.push({
633
+ name,
634
+ description: `${(info.description ?? info.title ?? info.annotations?.title ?? info.name).trim()}
635
+
636
+ (Tool "${info.name}" from the MCP server "${client.name}".)`,
637
+ inputSchema: { type: "object", ...schema },
638
+ effect: readOnly ? "read" : "external",
639
+ concurrency: readOnly ? "safe" : "exclusive",
640
+ idempotent: readOnly || info.annotations?.idempotentHint === true,
641
+ async execute(input, ctx) {
642
+ try {
643
+ const r = await client.callTool(info.name, input, ctx.signal);
644
+ return { content: toBlocks(name, r), isError: r?.isError === true };
645
+ } catch (err) {
646
+ if (ctx.signal.aborted)
647
+ throw err;
648
+ return { content: `MCP server "${client.name}" failed: ${errorText(err)}`, isError: true };
649
+ }
592
650
  }
651
+ });
593
652
  }
594
- return out;
653
+ }
654
+ return out;
595
655
  }
596
- /** MCP 的内容转成内容块:文本、图片照搬;音频、二进制资源只说明;没有内容时用 structuredContent */
597
656
  export function toBlocks(tool, r) {
598
- const origin = { by: "tool", name: tool };
599
- const blocks = [];
600
- let chars = 0;
601
- const text = (t) => {
602
- if (chars >= MAX_RESULT_CHARS)
603
- return;
604
- const room = MAX_RESULT_CHARS - chars;
605
- const shown = t.length > room ? `${t.slice(0, room)}\n[… ${t.length - room} more characters omitted]` : t;
606
- chars += shown.length;
607
- blocks.push({ kind: "text", text: shown, origin, trust: "untrusted" });
608
- };
609
- for (const raw of r?.content ?? []) {
610
- const c = raw;
611
- switch (c?.type) {
612
- case "text":
613
- if (typeof c.text === "string")
614
- text(c.text);
615
- break;
616
- case "image":
617
- if (typeof c.data === "string" && typeof c.mimeType === "string") {
618
- blocks.push({ kind: "image", source: { type: "base64", media_type: c.mimeType, data: c.data }, origin, trust: "untrusted" });
619
- }
620
- break;
621
- case "resource": {
622
- const res = c.resource;
623
- if (typeof res?.text === "string")
624
- text(`${res.uri ?? "resource"}:\n${res.text}`);
625
- else
626
- text(`[binary resource ${res?.uri ?? ""}${res?.mimeType ? ` (${res.mimeType})` : ""} omitted]`);
627
- break;
628
- }
629
- case "resource_link":
630
- text(`[resource ${c.name ? `${c.name} ` : ""}${c.uri ?? ""}]`);
631
- break;
632
- case "audio":
633
- text(`[audio${c.mimeType ? ` (${c.mimeType})` : ""} omitted]`);
634
- break;
657
+ const origin = { by: "tool", name: tool };
658
+ const blocks = [];
659
+ let chars = 0;
660
+ const text = (t) => {
661
+ if (chars >= MAX_RESULT_CHARS)
662
+ return;
663
+ const room = MAX_RESULT_CHARS - chars;
664
+ const shown = t.length > room ? `${t.slice(0, room)}
665
+ [… ${t.length - room} more characters omitted]` : t;
666
+ chars += shown.length;
667
+ blocks.push({ kind: "text", text: shown, origin, trust: "untrusted" });
668
+ };
669
+ for (const raw of r?.content ?? []) {
670
+ const c = raw;
671
+ switch (c?.type) {
672
+ case "text":
673
+ if (typeof c.text === "string")
674
+ text(c.text);
675
+ break;
676
+ case "image":
677
+ if (typeof c.data === "string" && typeof c.mimeType === "string") {
678
+ blocks.push({ kind: "image", source: { type: "base64", media_type: c.mimeType, data: c.data }, origin, trust: "untrusted" });
635
679
  }
680
+ break;
681
+ case "resource": {
682
+ const res = c.resource;
683
+ if (typeof res?.text === "string")
684
+ text(`${res.uri ?? "resource"}:
685
+ ${res.text}`);
686
+ else
687
+ text(`[binary resource ${res?.uri ?? ""}${res?.mimeType ? ` (${res.mimeType})` : ""} omitted]`);
688
+ break;
689
+ }
690
+ case "resource_link":
691
+ text(`[resource ${c.name ? `${c.name} ` : ""}${c.uri ?? ""}]`);
692
+ break;
693
+ case "audio":
694
+ text(`[audio${c.mimeType ? ` (${c.mimeType})` : ""} omitted]`);
695
+ break;
636
696
  }
637
- if (blocks.length === 0 && r?.structuredContent !== undefined)
638
- text(JSON.stringify(r.structuredContent, null, 2));
639
- if (blocks.length === 0)
640
- text("(no output)");
641
- return blocks;
697
+ }
698
+ if (blocks.length === 0 && r?.structuredContent !== undefined)
699
+ text(JSON.stringify(r.structuredContent, null, 2));
700
+ if (blocks.length === 0)
701
+ text("(no output)");
702
+ return blocks;
642
703
  }
643
704
  function errorText(err) {
644
- return err instanceof Error ? err.message : String(err);
705
+ return err instanceof Error ? err.message : String(err);
645
706
  }