@uncarved/jade 0.3.1 → 0.4.0
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.
- package/dist/api.d.ts +1 -1
- package/dist/api.js +1 -1
- package/dist/host.d.ts +2 -0
- package/dist/host.js +39 -5
- package/dist/host.js.map +1 -1
- package/dist/remote.js +5 -0
- package/dist/remote.js.map +1 -1
- package/dist/session.d.ts +7 -0
- package/dist/session.js +482 -27
- package/dist/session.js.map +1 -1
- package/package.json +4 -4
- package/plugins/approval/index.ts +36 -14
- package/plugins/approval/policy.ts +15 -10
- package/plugins/approval/review.ts +9 -5
- package/plugins/checks/checks.ts +10 -7
- package/plugins/checks/index.ts +13 -13
- package/plugins/checks/plugin.json +1 -1
- package/plugins/checks/project.ts +37 -38
- package/plugins/commands/index.ts +27 -3
- package/plugins/compact/compact.ts +13 -5
- package/plugins/compact/index.ts +20 -3
- package/plugins/compact/style.ts +13 -14
- package/plugins/completions/index.ts +35 -0
- package/plugins/completions/plugin.json +7 -0
- package/plugins/copy/index.ts +46 -0
- package/plugins/copy/plugin.json +7 -0
- package/plugins/editor/index.ts +10 -4
- package/plugins/fs/diff.ts +7 -6
- package/plugins/fs/fs.ts +8 -4
- package/plugins/fs/grep.ts +42 -9
- package/plugins/fs/index.ts +2 -7
- package/plugins/fs/plugin.json +1 -1
- package/plugins/fs/renderers.ts +16 -15
- package/plugins/fs/style.ts +16 -15
- package/plugins/hooks/index.ts +3 -2
- package/plugins/keys/index.ts +5 -1
- package/plugins/mcp/index.ts +197 -78
- package/plugins/mcp/install.ts +5 -3
- package/plugins/mcp/mcp.ts +163 -11
- package/plugins/mcp/plugin.json +2 -1
- package/plugins/mcp/project.ts +47 -50
- package/plugins/memory/index.ts +4 -4
- package/plugins/memory/style.ts +13 -14
- package/plugins/mentions/candidates.ts +67 -0
- package/plugins/mentions/index.ts +12 -5
- package/plugins/mentions/plugin.json +1 -1
- package/plugins/mentions/style.ts +13 -14
- package/plugins/models/configure.ts +10 -9
- package/plugins/models/index.ts +27 -1
- package/plugins/modes/index.ts +13 -2
- package/plugins/print/index.ts +7 -4
- package/plugins/prompts/index.ts +0 -0
- package/plugins/renderers/index.ts +10 -5
- package/plugins/repeats/index.ts +8 -8
- package/plugins/schedule/index.ts +2 -0
- package/plugins/screenshot/browser.ts +10 -0
- package/plugins/sessions/index.ts +48 -2
- package/plugins/shell/index.ts +20 -25
- package/plugins/shell/plugin.json +1 -2
- package/plugins/shell/renderers.ts +9 -7
- package/plugins/shell/shell.ts +3 -1
- package/plugins/skills/index.ts +28 -19
- package/plugins/skills/project.ts +12 -7
- package/plugins/steer/index.ts +5 -4
- package/plugins/task/index.ts +80 -50
- package/plugins/task/plugin.json +6 -2
- package/plugins/task/style.ts +13 -14
- package/plugins/task/subagent.ts +67 -184
- package/plugins/todo/index.ts +39 -9
- package/plugins/tools/index.ts +9 -2
- package/plugins/tui/frontend.ts +139 -89
- package/plugins/tui/index.ts +2 -3
- package/plugins/tui/mentions.ts +11 -80
- package/plugins/tui/plugin.json +1 -1
- package/plugins/tui/screen.ts +55 -5
- package/plugins/tui/transcript.ts +17 -7
- package/plugins/tui/tui.ts +337 -101
- package/plugins/tui/vendor.ts +1 -1
- package/plugins/undo/checkpoint.ts +5 -3
- package/plugins/undo/index.ts +43 -14
- package/plugins/undo/style.ts +13 -14
- package/plugins/web/index.ts +7 -18
- package/plugins/web/plugin.json +1 -1
- package/plugins-dist/approval/index.js +363 -418
- package/plugins-dist/approval/policy.js +391 -508
- package/plugins-dist/approval/review.js +132 -158
- package/plugins-dist/approval/schema.js +50 -55
- package/plugins-dist/ask/index.js +115 -129
- package/plugins-dist/budget/index.js +27 -31
- package/plugins-dist/checks/checks.js +293 -329
- package/plugins-dist/checks/index.js +119 -139
- package/plugins-dist/checks/plugin.json +2 -1
- package/plugins-dist/checks/project.js +57 -65
- package/plugins-dist/commands/index.js +47 -29
- package/plugins-dist/compact/compact.js +233 -249
- package/plugins-dist/compact/index.js +98 -95
- package/plugins-dist/compact/style.js +9 -14
- package/plugins-dist/completions/index.js +30 -0
- package/plugins-dist/completions/plugin.json +9 -0
- package/plugins-dist/continue/index.js +40 -52
- package/plugins-dist/copy/index.js +40 -0
- package/plugins-dist/copy/plugin.json +9 -0
- package/plugins-dist/cost/index.js +98 -115
- package/plugins-dist/custom-commands/index.js +55 -72
- package/plugins-dist/editor/index.js +64 -72
- package/plugins-dist/fs/diff.js +111 -124
- package/plugins-dist/fs/fs.js +426 -469
- package/plugins-dist/fs/grep.js +262 -253
- package/plugins-dist/fs/index.js +20 -34
- package/plugins-dist/fs/plugin.json +1 -2
- package/plugins-dist/fs/renderers.js +100 -112
- package/plugins-dist/fs/style.js +11 -15
- package/plugins-dist/fs/sys.js +31 -43
- package/plugins-dist/hooks/index.js +107 -127
- package/plugins-dist/keys/index.js +27 -31
- package/plugins-dist/mcp/index.js +271 -199
- package/plugins-dist/mcp/install.js +123 -137
- package/plugins-dist/mcp/mcp.js +638 -577
- package/plugins-dist/mcp/plugin.json +3 -1
- package/plugins-dist/mcp/project.js +98 -115
- package/plugins-dist/memory/index.js +83 -88
- package/plugins-dist/memory/memory.js +111 -128
- package/plugins-dist/memory/style.js +9 -14
- package/plugins-dist/mentions/attach.js +91 -99
- package/plugins-dist/mentions/candidates.js +49 -0
- package/plugins-dist/mentions/index.js +71 -81
- package/plugins-dist/mentions/plugin.json +2 -1
- package/plugins-dist/mentions/style.js +9 -14
- package/plugins-dist/models/config.js +29 -43
- package/plugins-dist/models/configure.js +392 -473
- package/plugins-dist/models/context.js +14 -22
- package/plugins-dist/models/index.js +182 -189
- package/plugins-dist/models/provider.js +243 -307
- package/plugins-dist/models/saved.js +59 -71
- package/plugins-dist/modes/index.js +138 -165
- package/plugins-dist/plugins/index.js +34 -34
- package/plugins-dist/print/index.js +192 -175
- package/plugins-dist/prompts/index.js +81 -89
- package/plugins-dist/prompts/notes.js +31 -37
- package/plugins-dist/prompts/prompts.js +155 -193
- package/plugins-dist/prompts/results.js +40 -53
- package/plugins-dist/prompts/sys.js +39 -50
- package/plugins-dist/renderers/index.js +32 -32
- package/plugins-dist/repeats/index.js +131 -174
- package/plugins-dist/schedule/cron.js +49 -56
- package/plugins-dist/schedule/index.js +229 -247
- package/plugins-dist/schedule/store.js +93 -109
- package/plugins-dist/scratch/index.js +12 -18
- package/plugins-dist/screenshot/browser.js +136 -154
- package/plugins-dist/screenshot/index.js +37 -46
- package/plugins-dist/screenshot/sys.js +53 -65
- package/plugins-dist/screenshot/tool.js +98 -126
- package/plugins-dist/sessions/index.js +149 -117
- package/plugins-dist/shell/index.js +115 -135
- package/plugins-dist/shell/plugin.json +1 -2
- package/plugins-dist/shell/renderers.js +28 -33
- package/plugins-dist/shell/service.js +17 -23
- package/plugins-dist/shell/shell.js +307 -362
- package/plugins-dist/shell/sys.js +64 -79
- package/plugins-dist/skills/index.js +193 -211
- package/plugins-dist/skills/install.js +122 -149
- package/plugins-dist/skills/project.js +65 -73
- package/plugins-dist/skills/skills.js +135 -171
- package/plugins-dist/steer/index.js +108 -125
- package/plugins-dist/suggest/index.js +235 -259
- package/plugins-dist/task/index.js +130 -117
- package/plugins-dist/task/plugin.json +5 -2
- package/plugins-dist/task/style.js +9 -14
- package/plugins-dist/task/subagent.js +156 -279
- package/plugins-dist/todo/index.js +79 -63
- package/plugins-dist/tools/index.js +36 -42
- package/plugins-dist/tui/editor.js +145 -160
- package/plugins-dist/tui/frontend.js +639 -678
- package/plugins-dist/tui/history.js +34 -37
- package/plugins-dist/tui/index.js +16 -18
- package/plugins-dist/tui/markdown.js +203 -247
- package/plugins-dist/tui/mascot.js +266 -355
- package/plugins-dist/tui/mentions.js +67 -144
- package/plugins-dist/tui/plugin.json +1 -2
- package/plugins-dist/tui/render.js +35 -45
- package/plugins-dist/tui/screen.js +197 -180
- package/plugins-dist/tui/transcript.js +436 -468
- package/plugins-dist/tui/tui.js +1554 -1656
- package/plugins-dist/undo/checkpoint.js +95 -118
- package/plugins-dist/undo/index.js +185 -192
- package/plugins-dist/undo/snapshot.js +83 -99
- package/plugins-dist/undo/style.js +9 -14
- package/plugins-dist/update/index.js +26 -28
- package/plugins-dist/web/env.js +55 -68
- package/plugins-dist/web/index.js +80 -110
- package/plugins-dist/web/plugin.json +1 -2
- package/plugins-dist/web/renderers.js +4 -5
- package/plugins-dist/web/web.js +514 -593
- package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
- package/sdk/python/jade_plugin.py +9 -2
- package/src/api.ts +1 -1
- package/src/host.ts +39 -4
- package/src/remote.ts +6 -1
- package/src/session.ts +489 -34
package/plugins-dist/mcp/mcp.js
CHANGED
|
@@ -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
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
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
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
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
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
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
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
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
|
|
124
|
-
|
|
125
|
-
|
|
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
|
-
|
|
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
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
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
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
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
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
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
|
-
|
|
183
|
+
return c.command !== undefined ? [c.command, ...c.args ?? []].join(" ") : `${c.url}`;
|
|
164
184
|
}
|
|
185
|
+
|
|
165
186
|
export class McpError extends Error {
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
187
|
+
code;
|
|
188
|
+
constructor(message, code) {
|
|
189
|
+
super(message);
|
|
190
|
+
this.name = "McpError";
|
|
191
|
+
this.code = code;
|
|
192
|
+
}
|
|
172
193
|
}
|
|
173
|
-
|
|
194
|
+
|
|
174
195
|
export class McpClient {
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
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
|
-
|
|
195
|
-
|
|
196
|
-
|
|
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
|
|
199
|
-
|
|
200
|
-
this
|
|
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
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
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
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
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
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
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
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
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
|
-
|
|
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
|
-
|
|
366
|
-
|
|
367
|
-
|
|
432
|
+
if (arg && !/[\s"&|<>^%!(),;=]/.test(arg))
|
|
433
|
+
return arg;
|
|
434
|
+
return `"${arg.replace(/"/g, '""')}"`;
|
|
368
435
|
}
|
|
369
436
|
function mergeEnv(extra = {}) {
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
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
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
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
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
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
|
-
|
|
416
|
-
|
|
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
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
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
|
-
|
|
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
|
-
|
|
483
|
-
|
|
484
|
-
|
|
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
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
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
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
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
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
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
|
-
|
|
653
|
+
}
|
|
654
|
+
return out;
|
|
595
655
|
}
|
|
596
|
-
/** MCP 的内容转成内容块:文本、图片照搬;音频、二进制资源只说明;没有内容时用 structuredContent */
|
|
597
656
|
export function toBlocks(tool, r) {
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
};
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
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
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
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
|
-
|
|
705
|
+
return err instanceof Error ? err.message : String(err);
|
|
645
706
|
}
|