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