pi-web-ui 0.105.0 → 0.106.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/CHANGELOG.md +58 -1
- package/README.md +193 -797
- package/README.zh-CN.md +186 -625
- package/README.zh-TW.md +781 -0
- package/bin/frp-manager.mjs +1488 -0
- package/bin/pi-web-ui.mjs +27 -0
- package/deploy/nginx-subpath.conf +16 -1
- package/dist/server/agent-service-daemon.js +34 -0
- package/dist/server/agent-service.js +227 -44
- package/dist/server/claim-files-tool.js +8 -1
- package/dist/server/client-state.js +146 -32
- package/dist/server/conversation-read-tool.js +12 -4
- package/dist/server/delegate-task.js +9 -1
- package/dist/server/dispatch-domain-handlers.js +15 -0
- package/dist/server/dsh/dsh-agent-service.js +838 -241
- package/dist/server/dsh/dsh-client.js +59 -18
- package/dist/server/dsh/dsh-market-service.js +233 -0
- package/dist/server/dsh/dsh-serialize.js +11 -3
- package/dist/server/dsh/dsh-sessions.js +64 -2
- package/dist/server/dsh/preset-clones.js +12 -1
- package/dist/server/dsh/runtime/goal-rpc.mjs +183 -45
- package/dist/server/engine-capabilities.js +72 -0
- package/dist/server/engine-probe.js +243 -0
- package/dist/server/goal-service.js +23 -12
- package/dist/server/i18n.js +20 -1
- package/dist/server/index.js +171 -66
- package/dist/server/locales.js +1 -0
- package/dist/server/mcp-agent-tool.js +10 -7
- package/dist/server/mcp-bridge.js +428 -24
- package/dist/server/model-admin.js +172 -74
- package/dist/server/model-resolver.js +221 -0
- package/dist/server/plugin-installer.js +4 -2
- package/dist/server/plugins.js +71 -11
- package/dist/server/present-files-tool.js +10 -2
- package/dist/server/preset-fields.js +14 -0
- package/dist/server/preset-share.js +2 -0
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/schedule-agent-tool.js +2 -1
- package/dist/server/scm-commitmsg.js +3 -2
- package/dist/server/settings-service.js +10 -2
- package/dist/server/skill-discovery.js +161 -0
- package/dist/server/skill-tool.js +2 -1
- package/dist/server/slash-commands.js +154 -73
- package/dist/server/subagent-templates-hant.js +215 -0
- package/dist/server/subagent-templates.js +49 -2
- package/dist/server/subagents.js +22 -12
- package/dist/server/terminals.js +2 -2
- package/dist/server/tool-manager.js +3 -0
- package/dist/server/universal/driver-base.js +56 -0
- package/dist/server/universal/drivers/claude-code.js +462 -0
- package/dist/server/universal/drivers/dsh-driver.js +376 -0
- package/dist/server/universal/drivers/mock-driver.js +103 -0
- package/dist/server/universal/index.js +10 -0
- package/dist/server/universal/session-store.js +100 -0
- package/dist/server/universal/universal-attachments.js +175 -0
- package/dist/server/universal/universal-service.js +149 -0
- package/dist/server/universal/universal-session.js +2610 -0
- package/dist/server/universal/universal-types.js +4 -0
- package/dist/server/update-check.js +4 -1
- package/dist/server/worktree-service.js +1 -1
- package/dist/server/worktree-tool.js +9 -7
- package/package.json +3 -2
- package/plugin-sdk/index.d.ts +12 -2
- package/plugins/catalog.json +39 -5
- package/themes/dark-teal.css +20 -23
- package/themes/md-preview.css +1 -2
- package/themes/wallpaper-obsidian.css +693 -0
- package/web/dist/assets/{TerminalPanel-B9exeXrl.js → TerminalPanel-CfxKLDW9.js} +2 -2
- package/web/dist/assets/index-BtcP6BDk.css +1 -0
- package/web/dist/assets/index-XVtCzcHR.js +690 -0
- package/web/dist/index.html +2 -2
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/index-BQC6lADz.css +0 -1
- package/web/dist/assets/index-D79IKG33.js +0 -690
|
@@ -17,6 +17,10 @@ import { spawn } from "node:child_process";
|
|
|
17
17
|
import { existsSync, readFileSync } from "node:fs";
|
|
18
18
|
import { homedir } from "node:os";
|
|
19
19
|
import { join } from "node:path";
|
|
20
|
+
/** 展开字符串中的 ${VAR_NAME} 环境变量占位符。 */
|
|
21
|
+
export function expandEnvVars(val) {
|
|
22
|
+
return val.replace(/\$\{([^}]+)\}/g, (_, k) => process.env[k] ?? "");
|
|
23
|
+
}
|
|
20
24
|
/** 获取全局 MCP 配置文件路径 */
|
|
21
25
|
export function getGlobalMcpPath(agentDir, dataDir) {
|
|
22
26
|
if (agentDir) {
|
|
@@ -54,16 +58,18 @@ const MCP_MAX_LINE_CHARS = 1024 * 1024;
|
|
|
54
58
|
const MCP_MAX_BUFFER_CHARS = 4 * 1024 * 1024;
|
|
55
59
|
let rpcSeq = 0;
|
|
56
60
|
/**
|
|
57
|
-
* 单个 MCP
|
|
61
|
+
* 单个 MCP 服务器的客户端:管理子进程或 HTTP 传输、请求/响应按 id 关联、握手与工具调用。
|
|
62
|
+
* 传输支持:
|
|
63
|
+
* - stdio:通过 child_process.spawn 与 NDJSON 交互
|
|
64
|
+
* - streamable-http / http:通过原生 fetch 发送 JSON-RPC POST 请求,支持 Mcp-Session-Id 与 SSE 流式响应
|
|
58
65
|
* 线程模型:无需并发控制(MCP 允许乱序 + 我们按请求 id 匹配响应)。
|
|
59
|
-
*
|
|
66
|
+
* 自愈:子进程意外退出(崩溃/被杀)或 HTTP 会话失效后不永久失效 —— 下一次工具调用会惰性重启并
|
|
60
67
|
* 重新握手、重新拉取工具列表;显式 close() 之后才永久停用。
|
|
61
68
|
*/
|
|
62
69
|
export class McpClient {
|
|
63
70
|
spec;
|
|
64
71
|
child = null;
|
|
65
72
|
buffer = "";
|
|
66
|
-
nextId = 1;
|
|
67
73
|
pending = new Map();
|
|
68
74
|
log;
|
|
69
75
|
name;
|
|
@@ -74,6 +80,12 @@ export class McpClient {
|
|
|
74
80
|
starting = null;
|
|
75
81
|
/** 已启动次数(含自愈重启;诊断/测试用)。 */
|
|
76
82
|
startedCount = 0;
|
|
83
|
+
/** HTTP 会话 ID(服务端返回 Mcp-Session-Id 时记录)。 */
|
|
84
|
+
sessionId = null;
|
|
85
|
+
/** 是否已成功握手(HTTP 模式无 child,以 initialized 标志为准)。 */
|
|
86
|
+
initialized = false;
|
|
87
|
+
/** 工具列表动态更新回调(收到 notifications/tools/list_changed 时触发)。 */
|
|
88
|
+
onToolsChanged;
|
|
77
89
|
constructor(name,
|
|
78
90
|
/** 启动规格;热加载按它判断「这个服务器要不要重启」(见 McpBridge.reload)。 */
|
|
79
91
|
spec, log) {
|
|
@@ -81,22 +93,37 @@ export class McpClient {
|
|
|
81
93
|
this.name = name;
|
|
82
94
|
this.log = log ?? (() => { });
|
|
83
95
|
}
|
|
84
|
-
|
|
96
|
+
get isHttp() {
|
|
97
|
+
return !this.spec.command && !!this.spec.url;
|
|
98
|
+
}
|
|
99
|
+
/** 启动子进程或 HTTP 连接 + 握手 + 拉取工具列表。可安全重入:退出后再次调用即全新启动。 */
|
|
85
100
|
async start(timeoutMs = 8000) {
|
|
101
|
+
if (this.isHttp) {
|
|
102
|
+
if (this.initialized)
|
|
103
|
+
return;
|
|
104
|
+
await this.startHttp(timeoutMs);
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
86
107
|
if (this.child)
|
|
87
108
|
return;
|
|
109
|
+
await this.startStdio(timeoutMs);
|
|
110
|
+
}
|
|
111
|
+
async startStdio(timeoutMs = 8000) {
|
|
88
112
|
const { command, args = [], cwd, env } = this.spec;
|
|
89
113
|
if (!command) {
|
|
90
|
-
if (this.spec.url) {
|
|
91
|
-
throw new Error(`远程 HTTP MCP 服务器(${this.spec.url})暂不支持 stdio 直接直连`);
|
|
92
|
-
}
|
|
93
114
|
throw new Error("MCP 服务器规格未声明 command 启动命令");
|
|
94
115
|
}
|
|
95
116
|
this.log(`[mcp:${this.name}] starting: ${command} ${args.join(" ")}`);
|
|
96
117
|
this.buffer = "";
|
|
118
|
+
const spawnedEnv = { ...process.env };
|
|
119
|
+
if (env) {
|
|
120
|
+
for (const [k, v] of Object.entries(env)) {
|
|
121
|
+
spawnedEnv[k] = expandEnvVars(v);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
97
124
|
const child = spawn(command, args, {
|
|
98
125
|
cwd: cwd ?? undefined,
|
|
99
|
-
env:
|
|
126
|
+
env: spawnedEnv,
|
|
100
127
|
stdio: ["pipe", "pipe", "pipe"],
|
|
101
128
|
windowsHide: true,
|
|
102
129
|
});
|
|
@@ -156,24 +183,56 @@ export class McpClient {
|
|
|
156
183
|
throw err;
|
|
157
184
|
}
|
|
158
185
|
}
|
|
186
|
+
async startHttp(timeoutMs = 8000) {
|
|
187
|
+
const url = this.spec.url;
|
|
188
|
+
if (!url)
|
|
189
|
+
throw new Error("MCP HTTP 服务器规格未声明 url");
|
|
190
|
+
this.log(`[mcp:${this.name}] connecting (HTTP): ${url}`);
|
|
191
|
+
this.sessionId = null;
|
|
192
|
+
this.initialized = false;
|
|
193
|
+
this.startedCount++;
|
|
194
|
+
try {
|
|
195
|
+
const handshake = await this.requestHttp("initialize", {
|
|
196
|
+
protocolVersion: this.spec.protocolVersion ?? PROTOCOL_VERSION,
|
|
197
|
+
capabilities: {},
|
|
198
|
+
clientInfo: { name: "pi-web-ui", version: "0.41.0" },
|
|
199
|
+
}, timeoutMs);
|
|
200
|
+
const version = handshake?.protocolVersion ?? this.spec.protocolVersion ?? PROTOCOL_VERSION;
|
|
201
|
+
void version;
|
|
202
|
+
// 通知 initialized(无 id 的 notification)
|
|
203
|
+
await this.sendHttpNotification("notifications/initialized", {});
|
|
204
|
+
const listed = ((await this.requestHttp("tools/list", {}, timeoutMs)) ?? {});
|
|
205
|
+
this.tools = Array.isArray(listed?.tools) ? listed.tools : [];
|
|
206
|
+
this.initialized = true;
|
|
207
|
+
this.log(`[mcp:${this.name}] ready (HTTP), ${this.tools.length} tools`);
|
|
208
|
+
}
|
|
209
|
+
catch (err) {
|
|
210
|
+
this.initialized = false;
|
|
211
|
+
this.sessionId = null;
|
|
212
|
+
throw err;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
159
215
|
/** 已启动次数(含自愈重启;诊断/测试用)。 */
|
|
160
216
|
get startCount() {
|
|
161
217
|
return this.startedCount;
|
|
162
218
|
}
|
|
163
219
|
/**
|
|
164
|
-
*
|
|
220
|
+
* 保活:连接存活就直接返回;已意外退出则惰性重启(并发调用共享同一次重连)。
|
|
165
221
|
* 显式 close() 后抛错,绝不复活。
|
|
166
222
|
*/
|
|
167
223
|
async ensureStarted(timeoutMs) {
|
|
168
224
|
if (this.shuttingDown)
|
|
169
225
|
throw new Error(`[mcp:${this.name}] 客户端已关闭,不会重启`);
|
|
170
|
-
// 先认「进行中的重连」再认 child:start() 是同步把 child 落位的,握手却还没完 ——
|
|
171
|
-
// 此时若按 child 判存活就直接返回,并发的第二个调用会抢在 initialize 应答前发出
|
|
172
|
-
// tools/call(严格实现会回「未初始化」)。共享同一个 promise 才能真正串行化。
|
|
173
226
|
if (this.starting)
|
|
174
227
|
return this.starting;
|
|
175
|
-
if (this.
|
|
176
|
-
|
|
228
|
+
if (this.isHttp) {
|
|
229
|
+
if (this.initialized)
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
else {
|
|
233
|
+
if (this.child)
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
177
236
|
this.starting = this.start(timeoutMs).finally(() => {
|
|
178
237
|
this.starting = null;
|
|
179
238
|
});
|
|
@@ -183,22 +242,50 @@ export class McpClient {
|
|
|
183
242
|
getTools() {
|
|
184
243
|
return this.tools.map((t) => ({ ...t }));
|
|
185
244
|
}
|
|
245
|
+
/**
|
|
246
|
+
* 刷新工具列表(收到 notifications/tools/list_changed 或手动刷新用)。
|
|
247
|
+
*/
|
|
248
|
+
async refreshTools(timeoutMs = 8000) {
|
|
249
|
+
const listed = ((await this.request("tools/list", {}, timeoutMs)) ?? {});
|
|
250
|
+
this.tools = Array.isArray(listed.tools) ? listed.tools : [];
|
|
251
|
+
this.log(`[mcp:${this.name}] tools refreshed, ${this.tools.length} tools`);
|
|
252
|
+
this.onToolsChanged?.();
|
|
253
|
+
return this.tools;
|
|
254
|
+
}
|
|
186
255
|
/**
|
|
187
256
|
* 调用一个工具,返回其结果。
|
|
188
|
-
*
|
|
257
|
+
* 纯文本块拼接成字符串(向后兼容);出现非文本块(image/resource/audio 等)时按序透传或退化提示,不再静默丢弃。
|
|
258
|
+
* 超时遵循 spec.timeout(秒,默认 60s),收到 progress 通知会自动重置超时计时器。
|
|
189
259
|
*/
|
|
190
|
-
async call(name, args, timeoutMs
|
|
260
|
+
async call(name, args, timeoutMs, signal) {
|
|
191
261
|
if (this.shuttingDown)
|
|
192
262
|
throw new Error(`[mcp:${this.name}] 客户端已关闭,不会重启`);
|
|
263
|
+
const effectiveTimeoutMs = timeoutMs ?? (this.spec.timeout && this.spec.timeout > 0 ? this.spec.timeout * 1000 : 60000);
|
|
193
264
|
try {
|
|
194
|
-
//
|
|
265
|
+
// 自愈:已断开或退出(非主动关闭)→ 先惰性重启/重新握手;失败给出明确错误。
|
|
195
266
|
await this.ensureStarted(8000);
|
|
196
267
|
}
|
|
197
268
|
catch (err) {
|
|
198
269
|
const detail = err instanceof Error ? err.message : String(err);
|
|
199
270
|
throw new Error(`[mcp:${this.name}] 服务器进程已退出且自动重启失败:${detail}`);
|
|
200
271
|
}
|
|
201
|
-
|
|
272
|
+
try {
|
|
273
|
+
return await this.executeCall(name, args, effectiveTimeoutMs, signal);
|
|
274
|
+
}
|
|
275
|
+
catch (err) {
|
|
276
|
+
// HTTP 模式下的会话失效自愈:若远端提示会话过期,重新握手并重试一次
|
|
277
|
+
if (this.isHttp && err instanceof Error && err.message.includes("MCP_SESSION_EXPIRED")) {
|
|
278
|
+
this.log(`[mcp:${this.name}] 会话已失效,重新握手重试调用...`);
|
|
279
|
+
this.sessionId = null;
|
|
280
|
+
this.initialized = false;
|
|
281
|
+
await this.ensureStarted(8000);
|
|
282
|
+
return await this.executeCall(name, args, effectiveTimeoutMs, signal);
|
|
283
|
+
}
|
|
284
|
+
throw err;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
async executeCall(name, args, timeoutMs, signal) {
|
|
288
|
+
const res = (await this.request("tools/call", { name, arguments: args, _meta: { progressToken: String(rpcSeq) } }, timeoutMs, signal));
|
|
202
289
|
if (res?.isError) {
|
|
203
290
|
const msg = (res.content ?? [])
|
|
204
291
|
.map((c) => c.text ?? "")
|
|
@@ -250,9 +337,10 @@ export class McpClient {
|
|
|
250
337
|
}
|
|
251
338
|
return { content: blocks, isError: !!res.isError };
|
|
252
339
|
}
|
|
253
|
-
/** 关闭:kill
|
|
340
|
+
/** 关闭:kill 子进程或注销 HTTP 会话,拒绝所有在途请求。 */
|
|
254
341
|
close() {
|
|
255
342
|
this.shuttingDown = true;
|
|
343
|
+
this.initialized = false;
|
|
256
344
|
this.rejectAll(new Error("[mcp] client closed"));
|
|
257
345
|
if (this.child) {
|
|
258
346
|
try {
|
|
@@ -263,6 +351,15 @@ export class McpClient {
|
|
|
263
351
|
}
|
|
264
352
|
this.child = null;
|
|
265
353
|
}
|
|
354
|
+
if (this.isHttp && this.sessionId && this.spec.url) {
|
|
355
|
+
const url = this.spec.url;
|
|
356
|
+
const sid = this.sessionId;
|
|
357
|
+
this.sessionId = null;
|
|
358
|
+
void fetch(url, {
|
|
359
|
+
method: "DELETE",
|
|
360
|
+
headers: { "Mcp-Session-Id": sid },
|
|
361
|
+
}).catch(() => { });
|
|
362
|
+
}
|
|
266
363
|
}
|
|
267
364
|
// -- 内部 -------------------------------------------------------------
|
|
268
365
|
send(msg) {
|
|
@@ -271,18 +368,286 @@ export class McpClient {
|
|
|
271
368
|
return;
|
|
272
369
|
stdin.write(JSON.stringify(msg) + "\n");
|
|
273
370
|
}
|
|
274
|
-
request(method, params, timeoutMs = 8000) {
|
|
371
|
+
request(method, params, timeoutMs = 8000, signal) {
|
|
372
|
+
if (this.isHttp) {
|
|
373
|
+
return this.requestHttp(method, params, timeoutMs, signal);
|
|
374
|
+
}
|
|
375
|
+
return this.requestStdio(method, params, timeoutMs, signal);
|
|
376
|
+
}
|
|
377
|
+
requestStdio(method, params, timeoutMs = 8000, signal) {
|
|
275
378
|
const id = rpcSeq++;
|
|
276
379
|
const outId = String(id);
|
|
277
380
|
return new Promise((resolve, reject) => {
|
|
381
|
+
if (signal?.aborted) {
|
|
382
|
+
reject(new Error("Request aborted"));
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
const onAbort = () => {
|
|
386
|
+
this.pending.delete(outId);
|
|
387
|
+
clearTimeout(timer);
|
|
388
|
+
this.send({
|
|
389
|
+
jsonrpc: "2.0",
|
|
390
|
+
method: "notifications/cancelled",
|
|
391
|
+
params: { requestId: id, reason: "Cancelled by user" },
|
|
392
|
+
});
|
|
393
|
+
reject(new Error("Request aborted"));
|
|
394
|
+
};
|
|
395
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
278
396
|
const timer = setTimeout(() => {
|
|
279
397
|
this.pending.delete(outId);
|
|
398
|
+
signal?.removeEventListener("abort", onAbort);
|
|
280
399
|
reject(new Error(`[mcp:${this.name}] ${method} 超时 (${timeoutMs}ms)`));
|
|
281
400
|
}, timeoutMs);
|
|
282
|
-
this.pending.set(outId, {
|
|
401
|
+
this.pending.set(outId, {
|
|
402
|
+
resolve: (v) => {
|
|
403
|
+
signal?.removeEventListener("abort", onAbort);
|
|
404
|
+
resolve(v);
|
|
405
|
+
},
|
|
406
|
+
reject: (e) => {
|
|
407
|
+
signal?.removeEventListener("abort", onAbort);
|
|
408
|
+
reject(e);
|
|
409
|
+
},
|
|
410
|
+
timer,
|
|
411
|
+
timeoutMs,
|
|
412
|
+
method,
|
|
413
|
+
progressToken: outId,
|
|
414
|
+
});
|
|
283
415
|
this.send({ jsonrpc: "2.0", id: id, method, params });
|
|
284
416
|
});
|
|
285
417
|
}
|
|
418
|
+
async requestHttp(method, params, timeoutMs = 8000, signal) {
|
|
419
|
+
const url = this.spec.url;
|
|
420
|
+
if (!url)
|
|
421
|
+
throw new Error("MCP HTTP 服务器未声明 url");
|
|
422
|
+
const id = rpcSeq++;
|
|
423
|
+
const outId = String(id);
|
|
424
|
+
const abortController = new AbortController();
|
|
425
|
+
if (signal?.aborted) {
|
|
426
|
+
throw new Error("Request aborted");
|
|
427
|
+
}
|
|
428
|
+
const onAbort = () => {
|
|
429
|
+
abortController.abort();
|
|
430
|
+
};
|
|
431
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
432
|
+
const headers = {
|
|
433
|
+
"Content-Type": "application/json",
|
|
434
|
+
Accept: "application/json, text/event-stream",
|
|
435
|
+
};
|
|
436
|
+
if (this.sessionId) {
|
|
437
|
+
headers["Mcp-Session-Id"] = this.sessionId;
|
|
438
|
+
}
|
|
439
|
+
if (this.spec.headers) {
|
|
440
|
+
for (const [k, v] of Object.entries(this.spec.headers)) {
|
|
441
|
+
headers[k] = expandEnvVars(v);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
let timedOut = false;
|
|
445
|
+
let reqResolve;
|
|
446
|
+
let reqReject;
|
|
447
|
+
const reqPromise = new Promise((res, rej) => {
|
|
448
|
+
reqResolve = res;
|
|
449
|
+
reqReject = rej;
|
|
450
|
+
});
|
|
451
|
+
const timer = setTimeout(() => {
|
|
452
|
+
timedOut = true;
|
|
453
|
+
this.pending.delete(outId);
|
|
454
|
+
abortController.abort();
|
|
455
|
+
reqReject(new Error(`[mcp:${this.name}] ${method} 超时 (${timeoutMs}ms)`));
|
|
456
|
+
}, timeoutMs);
|
|
457
|
+
this.pending.set(outId, {
|
|
458
|
+
resolve: (v) => {
|
|
459
|
+
clearTimeout(timer);
|
|
460
|
+
signal?.removeEventListener("abort", onAbort);
|
|
461
|
+
this.pending.delete(outId);
|
|
462
|
+
reqResolve(v);
|
|
463
|
+
},
|
|
464
|
+
reject: (e) => {
|
|
465
|
+
clearTimeout(timer);
|
|
466
|
+
signal?.removeEventListener("abort", onAbort);
|
|
467
|
+
this.pending.delete(outId);
|
|
468
|
+
reqReject(e);
|
|
469
|
+
},
|
|
470
|
+
timer,
|
|
471
|
+
timeoutMs,
|
|
472
|
+
method,
|
|
473
|
+
progressToken: outId,
|
|
474
|
+
abortController,
|
|
475
|
+
});
|
|
476
|
+
try {
|
|
477
|
+
const res = await fetch(url, {
|
|
478
|
+
method: "POST",
|
|
479
|
+
headers,
|
|
480
|
+
body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
|
|
481
|
+
signal: abortController.signal,
|
|
482
|
+
});
|
|
483
|
+
const newSid = res.headers.get("mcp-session-id");
|
|
484
|
+
if (newSid)
|
|
485
|
+
this.sessionId = newSid;
|
|
486
|
+
if (res.status === 202) {
|
|
487
|
+
const pending = this.pending.get(outId);
|
|
488
|
+
pending?.resolve(null);
|
|
489
|
+
return await reqPromise;
|
|
490
|
+
}
|
|
491
|
+
if (res.status === 404 || res.status === 400) {
|
|
492
|
+
const errText = await res.text().catch(() => "");
|
|
493
|
+
if (res.status === 404 || /session/i.test(errText)) {
|
|
494
|
+
this.sessionId = null;
|
|
495
|
+
this.initialized = false;
|
|
496
|
+
const pending = this.pending.get(outId);
|
|
497
|
+
pending?.reject(new Error(`MCP_SESSION_EXPIRED: ${errText || "Session expired or not found"}`));
|
|
498
|
+
return await reqPromise;
|
|
499
|
+
}
|
|
500
|
+
throw new Error(`HTTP ${res.status}: ${errText}`);
|
|
501
|
+
}
|
|
502
|
+
if (!res.ok) {
|
|
503
|
+
const errText = await res.text().catch(() => "");
|
|
504
|
+
throw new Error(`HTTP ${res.status}: ${errText}`);
|
|
505
|
+
}
|
|
506
|
+
const contentType = res.headers.get("content-type") || "";
|
|
507
|
+
if (contentType.includes("text/event-stream") && res.body) {
|
|
508
|
+
void this.readSseStream(res.body, outId, signal);
|
|
509
|
+
}
|
|
510
|
+
else {
|
|
511
|
+
const text = await res.text();
|
|
512
|
+
let parsed;
|
|
513
|
+
try {
|
|
514
|
+
parsed = JSON.parse(text);
|
|
515
|
+
}
|
|
516
|
+
catch {
|
|
517
|
+
let matched;
|
|
518
|
+
if (text.includes("data:")) {
|
|
519
|
+
for (const l of text.split("\n")) {
|
|
520
|
+
const trimmed = l.trim();
|
|
521
|
+
if (trimmed.startsWith("data:")) {
|
|
522
|
+
try {
|
|
523
|
+
const item = JSON.parse(trimmed.slice(5).trim());
|
|
524
|
+
if (item.id !== undefined && String(item.id) === outId) {
|
|
525
|
+
matched = item;
|
|
526
|
+
break;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
catch { }
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
if (matched) {
|
|
534
|
+
parsed = matched;
|
|
535
|
+
}
|
|
536
|
+
else {
|
|
537
|
+
throw new Error(`Invalid JSON response: ${text.slice(0, 200)}`);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
const pending = this.pending.get(outId);
|
|
541
|
+
if (pending) {
|
|
542
|
+
if (parsed.error) {
|
|
543
|
+
pending.reject(new Error(`[mcp:${this.name}] ${parsed.error.message ?? "MCP 错误"}`));
|
|
544
|
+
}
|
|
545
|
+
else {
|
|
546
|
+
pending.resolve(parsed.result);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
return await reqPromise;
|
|
551
|
+
}
|
|
552
|
+
catch (err) {
|
|
553
|
+
if (timedOut) {
|
|
554
|
+
return await reqPromise;
|
|
555
|
+
}
|
|
556
|
+
if (signal?.aborted) {
|
|
557
|
+
const pending = this.pending.get(outId);
|
|
558
|
+
pending?.reject(new Error("Request aborted"));
|
|
559
|
+
return await reqPromise;
|
|
560
|
+
}
|
|
561
|
+
const pending = this.pending.get(outId);
|
|
562
|
+
pending?.reject(err instanceof Error ? err : new Error(String(err)));
|
|
563
|
+
return await reqPromise;
|
|
564
|
+
}
|
|
565
|
+
finally {
|
|
566
|
+
signal?.removeEventListener("abort", onAbort);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
async sendHttpNotification(method, params) {
|
|
570
|
+
const url = this.spec.url;
|
|
571
|
+
if (!url)
|
|
572
|
+
return;
|
|
573
|
+
const headers = {
|
|
574
|
+
"Content-Type": "application/json",
|
|
575
|
+
Accept: "application/json, text/event-stream",
|
|
576
|
+
};
|
|
577
|
+
if (this.sessionId) {
|
|
578
|
+
headers["Mcp-Session-Id"] = this.sessionId;
|
|
579
|
+
}
|
|
580
|
+
if (this.spec.headers) {
|
|
581
|
+
for (const [k, v] of Object.entries(this.spec.headers)) {
|
|
582
|
+
headers[k] = expandEnvVars(v);
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
try {
|
|
586
|
+
const res = await fetch(url, {
|
|
587
|
+
method: "POST",
|
|
588
|
+
headers,
|
|
589
|
+
body: JSON.stringify({ jsonrpc: "2.0", method, params }),
|
|
590
|
+
});
|
|
591
|
+
const newSid = res.headers.get("mcp-session-id");
|
|
592
|
+
if (newSid)
|
|
593
|
+
this.sessionId = newSid;
|
|
594
|
+
}
|
|
595
|
+
catch (err) {
|
|
596
|
+
this.log(`[mcp:${this.name}] HTTP notification ${method} failed:`, err);
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
async readSseStream(body, targetId, signal) {
|
|
600
|
+
const reader = body.getReader();
|
|
601
|
+
const decoder = new TextDecoder("utf-8");
|
|
602
|
+
let buffer = "";
|
|
603
|
+
const onAbort = () => {
|
|
604
|
+
void reader.cancel().catch(() => { });
|
|
605
|
+
};
|
|
606
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
607
|
+
try {
|
|
608
|
+
while (true) {
|
|
609
|
+
const { done, value } = await reader.read();
|
|
610
|
+
if (done)
|
|
611
|
+
break;
|
|
612
|
+
buffer += decoder.decode(value, { stream: true });
|
|
613
|
+
let nl;
|
|
614
|
+
while ((nl = buffer.indexOf("\n")) >= 0) {
|
|
615
|
+
const rawLine = buffer.slice(0, nl);
|
|
616
|
+
buffer = buffer.slice(nl + 1);
|
|
617
|
+
const line = rawLine.replace(/\r$/, "").trim();
|
|
618
|
+
if (!line || !line.startsWith("data:"))
|
|
619
|
+
continue;
|
|
620
|
+
const dataStr = line.slice(5).trim();
|
|
621
|
+
if (!dataStr)
|
|
622
|
+
continue;
|
|
623
|
+
let msg;
|
|
624
|
+
try {
|
|
625
|
+
msg = JSON.parse(dataStr);
|
|
626
|
+
}
|
|
627
|
+
catch {
|
|
628
|
+
continue;
|
|
629
|
+
}
|
|
630
|
+
this.handleMessage(msg);
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
catch (err) {
|
|
635
|
+
if (!signal?.aborted) {
|
|
636
|
+
const pending = this.pending.get(targetId);
|
|
637
|
+
if (pending) {
|
|
638
|
+
clearTimeout(pending.timer);
|
|
639
|
+
this.pending.delete(targetId);
|
|
640
|
+
pending.reject(err instanceof Error ? err : new Error(String(err)));
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
finally {
|
|
645
|
+
if (signal) {
|
|
646
|
+
signal.removeEventListener("abort", onAbort);
|
|
647
|
+
}
|
|
648
|
+
reader.releaseLock();
|
|
649
|
+
}
|
|
650
|
+
}
|
|
286
651
|
onData(chunk) {
|
|
287
652
|
this.buffer += chunk;
|
|
288
653
|
// 总缓冲上限:服务器一直输出却不换行(或极慢地换行)时,缓冲会无限涨,
|
|
@@ -330,6 +695,24 @@ export class McpClient {
|
|
|
330
695
|
}
|
|
331
696
|
}
|
|
332
697
|
}
|
|
698
|
+
handleProgress(params) {
|
|
699
|
+
const token = params?.progressToken !== undefined ? String(params.progressToken) : undefined;
|
|
700
|
+
let target;
|
|
701
|
+
if (token && this.pending.has(token)) {
|
|
702
|
+
target = this.pending.get(token);
|
|
703
|
+
}
|
|
704
|
+
else if (this.pending.size === 1) {
|
|
705
|
+
target = this.pending.values().next().value;
|
|
706
|
+
}
|
|
707
|
+
if (target) {
|
|
708
|
+
clearTimeout(target.timer);
|
|
709
|
+
target.timer = setTimeout(() => {
|
|
710
|
+
this.pending.delete(token ?? "");
|
|
711
|
+
target.reject(new Error(`[mcp:${this.name}] ${target.method} 超时 (${target.timeoutMs}ms)`));
|
|
712
|
+
}, target.timeoutMs);
|
|
713
|
+
this.log(`[mcp:${this.name}] progress received (${params.progress ?? "?"}/${params.total ?? "?"}), timeout reset (${target.timeoutMs}ms)`);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
333
716
|
handleMessage(msg) {
|
|
334
717
|
if (msg.id !== undefined) {
|
|
335
718
|
const pending = this.pending.get(String(msg.id));
|
|
@@ -345,7 +728,18 @@ export class McpClient {
|
|
|
345
728
|
pending.resolve(msg.result);
|
|
346
729
|
return;
|
|
347
730
|
}
|
|
348
|
-
// 服务端主动通知(
|
|
731
|
+
// 服务端主动通知(progress / tools/list_changed / message 等)
|
|
732
|
+
if (msg.method === "notifications/progress") {
|
|
733
|
+
this.handleProgress(msg.params);
|
|
734
|
+
return;
|
|
735
|
+
}
|
|
736
|
+
if (msg.method === "notifications/tools/list_changed") {
|
|
737
|
+
this.log(`[mcp:${this.name}] tools/list_changed notification received, refreshing tools...`);
|
|
738
|
+
void this.refreshTools().catch((err) => {
|
|
739
|
+
this.log(`[mcp:${this.name}] tools refresh failed:`, err);
|
|
740
|
+
});
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
349
743
|
if (msg.method === "notifications/message") {
|
|
350
744
|
const p = msg.params;
|
|
351
745
|
if (p?.message)
|
|
@@ -457,8 +851,8 @@ function adaptMcpTool(serverName, mcpTool, client) {
|
|
|
457
851
|
// 这个能力(#403)。这里从 description 提取首句做极简 snippet。
|
|
458
852
|
promptSnippet: firstSentenceSnippet(mcpTool.description) ?? `MCP tool ${mcpTool.name} (server: ${serverName})`,
|
|
459
853
|
parameters: mcpTool.inputSchema ?? {},
|
|
460
|
-
execute: async (_toolCallId, params,
|
|
461
|
-
return client.call(mcpTool.name, params ?? {});
|
|
854
|
+
execute: async (_toolCallId, params, signal) => {
|
|
855
|
+
return client.call(mcpTool.name, params ?? {}, undefined, signal);
|
|
462
856
|
},
|
|
463
857
|
};
|
|
464
858
|
}
|
|
@@ -541,6 +935,7 @@ export class McpBridge {
|
|
|
541
935
|
async startOne(name, spec) {
|
|
542
936
|
try {
|
|
543
937
|
const client = new McpClient(name, spec, this.log);
|
|
938
|
+
client.onToolsChanged = () => this.reaggregateTools();
|
|
544
939
|
await client.start();
|
|
545
940
|
this.serverErrors.delete(name);
|
|
546
941
|
return client;
|
|
@@ -552,6 +947,15 @@ export class McpBridge {
|
|
|
552
947
|
return null;
|
|
553
948
|
}
|
|
554
949
|
}
|
|
950
|
+
reaggregateTools() {
|
|
951
|
+
this.tools = [];
|
|
952
|
+
for (const c of this.clients) {
|
|
953
|
+
for (const t of c.getTools()) {
|
|
954
|
+
this.tools.push(adaptMcpTool(c.name, t, c));
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
this.opts.onToolsChanged?.();
|
|
958
|
+
}
|
|
555
959
|
/**
|
|
556
960
|
* 按磁盘上的最新配置**整体换入**服务器集合(`mcp.json` 热加载用),可重复调用。
|
|
557
961
|
*/
|