local-mcp-manager 0.5.4 → 0.9.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 +51 -0
- package/README.md +46 -43
- package/THIRD_PARTY_NOTICES.md +3 -1
- package/assets/mcp-manager.svg +7 -0
- package/dist/workbench.js +2887 -0
- package/lib/config-import.js +63 -0
- package/lib/controller.js +94 -20
- package/lib/health.js +119 -0
- package/lib/index.js +162 -7
- package/lib/path-format.js +10 -0
- package/lib/registry.js +186 -0
- package/lib/resource-support.js +294 -0
- package/lib/runtime.js +294 -29
- package/lib/stats.js +144 -0
- package/lib/store.js +39 -16
- package/lib/tool-preview.js +40 -0
- package/lib/tool-trust.js +105 -0
- package/lib/web.js +863 -0
- package/lib/workbench-host.js +70 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +99 -17
- package/src/workbench/contract.js +198 -0
package/lib/runtime.js
CHANGED
|
@@ -1,20 +1,29 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
3
|
+
import { stripVTControlCharacters } from 'node:util';
|
|
3
4
|
import { Client, StreamableHTTPClientTransport, SSEClientTransport } from '@modelcontextprotocol/client';
|
|
4
5
|
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
|
|
5
6
|
import { createMcpToolDefinition } from '@deepseek-ai/dsh-mcp-client';
|
|
6
7
|
import { scrubbedParentEnv } from '@deepseek-ai/dsh-subprocess';
|
|
8
|
+
import { isWindowsAbsoluteCwd } from './path-format.js';
|
|
9
|
+
import { createResourceWatches, expandResourceTemplate, resourceTemplateVariables } from './resource-support.js';
|
|
10
|
+
import { createToolTrust, toolFingerprint, toolHint, toolIdentity, toolTarget } from './tool-trust.js';
|
|
11
|
+
import manifest from '../package.json' with { type: 'json' };
|
|
7
12
|
|
|
8
13
|
const MESSAGES = Object.freeze({
|
|
9
14
|
'connection-failed': '连接失败,请检查服务器地址与凭据。',
|
|
10
15
|
'discovery-failed': '无法刷新服务器工具列表。',
|
|
11
16
|
'tool-failed': 'MCP 工具调用失败。',
|
|
12
17
|
'tool-disabled': 'MCP 工具已禁用或连接配置已改变。',
|
|
18
|
+
'tool-review-required': 'MCP 工具定义待复核。请在工作台查看新的说明与参数。',
|
|
13
19
|
'credential-missing': '请求头凭据不可用。请打开基础设置,点击该请求头重新填写并保存。',
|
|
14
20
|
'auth-rejected': '服务器拒绝鉴权(401)。请检查请求头名称和值;x-api-key 通常直接填 Key。',
|
|
15
21
|
'access-denied': '服务器拒绝访问(403)。请检查 Key 权限或服务商的网络访问限制。',
|
|
16
22
|
'rate-limited': '请求过于频繁或额度不足(429)。请稍后重新连接或检查服务商额度。',
|
|
17
23
|
'invalid-transport': '服务器连接配置无效。',
|
|
24
|
+
'stdio-cwd-platform': '工作目录与 DSH 引擎所在主机的路径格式不匹配。',
|
|
25
|
+
'stdio-start-not-found': 'DSH 主机找不到启动程序或工作目录。',
|
|
26
|
+
'stdio-start-denied': 'DSH 主机没有权限启动此程序或进入工作目录。',
|
|
18
27
|
'unsafe-request': '已阻止跨来源请求或重定向。',
|
|
19
28
|
'registration-failed': '工具名称冲突,无法注册。',
|
|
20
29
|
'schema-secret': '服务器工具定义包含连接凭据,已拒绝加载,请联系服务器维护者。',
|
|
@@ -22,6 +31,12 @@ const MESSAGES = Object.freeze({
|
|
|
22
31
|
'cancelled': '操作已取消。',
|
|
23
32
|
'close-failed': '无法确认旧连接已关闭;请重启引擎后重试。',
|
|
24
33
|
'retry-exhausted': '连接多次失败,请手动重连。',
|
|
34
|
+
'unsupported': '该服务器未提供此能力或当前未连接。',
|
|
35
|
+
'read-failed': '读取资源失败,请稍后重试。',
|
|
36
|
+
'invalid-template': '资源模板已变化,或参数不能展开为有效 URI。',
|
|
37
|
+
'watch-limit': '每个连接最多订阅 16 个资源。',
|
|
38
|
+
'watch-failed': '资源订阅未完成,请核对当前连接。',
|
|
39
|
+
'prompt-failed': '渲染提示词失败,请检查参数。',
|
|
25
40
|
});
|
|
26
41
|
const faults = new WeakSet();
|
|
27
42
|
function fault(code) {
|
|
@@ -36,6 +51,35 @@ const clone = value => structuredClone(value);
|
|
|
36
51
|
const timeoutFor = server => Number.isFinite(server.timeoutMs)
|
|
37
52
|
? Math.max(100, Math.min(300000, server.timeoutMs)) : 60000;
|
|
38
53
|
const sleepTimer = (fn, ms) => { const timer = setTimeout(fn, ms); timer.unref?.(); return timer; };
|
|
54
|
+
const LOG_MAX = 300;
|
|
55
|
+
const STDERR_LINE_MAX = 8192;
|
|
56
|
+
|
|
57
|
+
function captureStderr(stream, onLine) {
|
|
58
|
+
let pending = '', overflow = false;
|
|
59
|
+
const flush = () => {
|
|
60
|
+
if (overflow) onLine('[stderr line exceeded capture limit]');
|
|
61
|
+
else if (pending.trim()) onLine(pending);
|
|
62
|
+
pending = '';
|
|
63
|
+
overflow = false;
|
|
64
|
+
};
|
|
65
|
+
stream.setEncoding('utf8');
|
|
66
|
+
stream.on('data', chunk => {
|
|
67
|
+
for (let start = 0; start < chunk.length;) {
|
|
68
|
+
const newline = chunk.indexOf('\n', start);
|
|
69
|
+
const end = newline < 0 ? chunk.length : newline;
|
|
70
|
+
if (!overflow) {
|
|
71
|
+
if (pending.length + end - start > STDERR_LINE_MAX) { overflow = true; pending = ''; }
|
|
72
|
+
else pending += chunk.slice(start, end);
|
|
73
|
+
}
|
|
74
|
+
if (newline < 0) break;
|
|
75
|
+
flush();
|
|
76
|
+
start = newline + 1;
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
stream.on('end', flush);
|
|
80
|
+
stream.on('error', () => { pending = ''; overflow = false; });
|
|
81
|
+
return flush;
|
|
82
|
+
}
|
|
39
83
|
|
|
40
84
|
/** Mirrors the public naming contract; the upstream helper is private. */
|
|
41
85
|
export function publicToolName(serverId, rawName) {
|
|
@@ -122,21 +166,21 @@ export class ManagerRuntime {
|
|
|
122
166
|
this.owned = new Map();
|
|
123
167
|
this.secrets = new Set();
|
|
124
168
|
this.callFaults = new AsyncLocalStorage();
|
|
169
|
+
this.toolTrust = options.toolTrust ?? createToolTrust();
|
|
125
170
|
this.closed = false;
|
|
126
171
|
this.disposers = [];
|
|
127
172
|
this.disposers.push(ctx.tools.guard(exec => {
|
|
128
173
|
const item = this.owned.get(exec.name);
|
|
129
|
-
return item
|
|
174
|
+
return item ? MESSAGES[this.toolFault(item.generation, item.rawName)] : undefined;
|
|
130
175
|
}));
|
|
131
176
|
this.disposers.push(ctx.on('tools/pre-execute', async (exec, next) => {
|
|
132
177
|
const downstream = await next();
|
|
133
178
|
if (downstream.kind !== 'allow') return downstream;
|
|
134
179
|
const item = this.owned.get(exec.name);
|
|
135
180
|
if (!item) return downstream;
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
if (policy?.requireApproval ?? server?.requireApproval ?? true) return {
|
|
181
|
+
const denied = this.toolFault(item.generation, item.rawName);
|
|
182
|
+
if (denied) return { kind: 'deny', reason: MESSAGES[denied] };
|
|
183
|
+
if (this.toolAccess(item.generation.slot.id, item.rawName)?.requireApproval) return {
|
|
140
184
|
kind: 'ask', reason: 'This MCP tool requires approval for this call.',
|
|
141
185
|
displayReason: { en: 'Approve this MCP tool call', zh: '批准本次 MCP 工具调用' },
|
|
142
186
|
};
|
|
@@ -154,11 +198,44 @@ export class ManagerRuntime {
|
|
|
154
198
|
return !this.closed && !generation.controller.signal.aborted && generation.slot.generation === generation
|
|
155
199
|
&& server?.enabled === true && connectionKey(server) === generation.key;
|
|
156
200
|
}
|
|
157
|
-
|
|
158
|
-
return
|
|
201
|
+
registration(generation, rawName) {
|
|
202
|
+
return generation?.registrations?.get(publicToolName(generation.slot.id, rawName));
|
|
159
203
|
}
|
|
160
|
-
|
|
161
|
-
|
|
204
|
+
accepted(generation, rawName, row) {
|
|
205
|
+
return row?.rawName === rawName && generation.observed?.get(rawName) === row.signature
|
|
206
|
+
&& this.toolTrust.isAccepted(generation.toolTarget, row.identity, row.signature);
|
|
207
|
+
}
|
|
208
|
+
toolFault(generation, rawName, ticket) {
|
|
209
|
+
if (!this.live(generation) || this.server(generation.slot.id)?.tools?.[rawName]?.enabled === false) return 'tool-disabled';
|
|
210
|
+
const row = this.registration(generation, rawName);
|
|
211
|
+
if (!row || (ticket && row.ticket !== ticket)) return 'tool-disabled';
|
|
212
|
+
if (!this.accepted(generation, rawName, row)) return 'tool-review-required';
|
|
213
|
+
}
|
|
214
|
+
allowed(generation, rawName, ticket) { return !this.toolFault(generation, rawName, ticket); }
|
|
215
|
+
assertCurrent(generation, rawName, ticket) {
|
|
216
|
+
const code = rawName === undefined ? (this.live(generation) ? undefined : 'tool-disabled') : this.toolFault(generation, rawName, ticket);
|
|
217
|
+
if (code) throw fault(code);
|
|
218
|
+
}
|
|
219
|
+
toolAccess(id, rawName) {
|
|
220
|
+
const generation = this.slots.get(id)?.generation;
|
|
221
|
+
const row = this.registration(generation, rawName);
|
|
222
|
+
if (!row || row.rawName !== rawName || !this.live(generation)) return undefined;
|
|
223
|
+
const server = this.server(id), hint = row.hint;
|
|
224
|
+
return {hint, pending: !this.accepted(generation, rawName, row),
|
|
225
|
+
requireApproval: hint === 'destructive' || (server.tools?.[rawName]?.requireApproval ?? server.requireApproval ?? true)};
|
|
226
|
+
}
|
|
227
|
+
async reviewTool(id, rawName, assertStamp) {
|
|
228
|
+
const generation = this.slots.get(id)?.generation;
|
|
229
|
+
const row = this.registration(generation, rawName);
|
|
230
|
+
const check = () => {
|
|
231
|
+
assertStamp?.();
|
|
232
|
+
if (!generation || !this.live(generation) || generation.connecting || generation.slot.view.refreshing
|
|
233
|
+
|| !row || this.registration(generation, rawName) !== row || generation.observed?.get(rawName) !== row.signature) throw fault('tool-review-required');
|
|
234
|
+
};
|
|
235
|
+
check();
|
|
236
|
+
await this.toolTrust.accept(generation.toolTarget, row.identity, row.signature, check);
|
|
237
|
+
this.changed();
|
|
238
|
+
return true;
|
|
162
239
|
}
|
|
163
240
|
rememberSecret(value) {
|
|
164
241
|
if (typeof value === 'string' && value.length) this.secrets.add(value);
|
|
@@ -182,7 +259,7 @@ export class ManagerRuntime {
|
|
|
182
259
|
const slot = this.slots.get(server.id);
|
|
183
260
|
const view = slot?.view ?? { status: server.enabled ? 'disconnected' : 'disabled', error: null,
|
|
184
261
|
tools: [], resources: [], prompts: [] };
|
|
185
|
-
return [server.id, this.safe({ ...view, resourcesCallable: false, promptsCallable: false,
|
|
262
|
+
return [server.id, this.safe({ ...view, resourcesCallable: view.resourcesCallable ?? false, promptsCallable: view.promptsCallable ?? false,
|
|
186
263
|
retries: slot?.retries ?? 0, nextRetryAt: slot?.nextRetryAt ?? null,
|
|
187
264
|
history: slot?.history ?? [], stats: slot?.stats ?? { calls: 0, failures: 0, active: 0 },
|
|
188
265
|
})];
|
|
@@ -200,6 +277,11 @@ export class ManagerRuntime {
|
|
|
200
277
|
const slot = this.slots.get(server.id);
|
|
201
278
|
const view = slot?.view;
|
|
202
279
|
const tools = view?.tools ?? [];
|
|
280
|
+
const generation = slot?.generation;
|
|
281
|
+
const access = tool => {
|
|
282
|
+
const row = this.registration(generation, tool.name);
|
|
283
|
+
return row ? { ...(row.hint ? {hint: row.hint} : {}), ...(!this.accepted(generation, tool.name, row) ? {pending: true} : {}) } : {};
|
|
284
|
+
};
|
|
203
285
|
// Build the allowlisted fields before redaction. In particular, summary
|
|
204
286
|
// projections never access inputSchema, resource entries or prompt args.
|
|
205
287
|
const row = {
|
|
@@ -210,12 +292,14 @@ export class ManagerRuntime {
|
|
|
210
292
|
serverInfo: view?.serverInfo ?? null,
|
|
211
293
|
retries: slot?.retries ?? 0,
|
|
212
294
|
nextRetryAt: slot?.nextRetryAt ?? null,
|
|
213
|
-
counts: { tools: tools.length, enabledTools: tools.reduce((total, tool) => total + (server.tools?.[tool.name]?.enabled === false ? 0 : 1), 0), resources: view?.resources?.length ?? 0, prompts: view?.prompts?.length ?? 0 },
|
|
295
|
+
counts: { tools: tools.length, enabledTools: tools.reduce((total, tool) => total + (server.tools?.[tool.name]?.enabled === false || access(tool).pending ? 0 : 1), 0), resources: view?.resources?.length ?? 0, prompts: view?.prompts?.length ?? 0 },
|
|
296
|
+
loggingCallable: view?.loggingCallable ?? false,
|
|
214
297
|
tools: detail === 'tool'
|
|
215
298
|
? tools.filter(tool => tool.name === toolName).slice(0, 1).map(tool => ({
|
|
216
299
|
name: tool.name, description: tool.description ?? '', inputSchema: tool.inputSchema,
|
|
300
|
+
...(tool.outputSchema ? {outputSchema: tool.outputSchema} : {}),
|
|
217
301
|
}))
|
|
218
|
-
: detail === 'tools' ? tools.slice(0, 500).map(tool => ({ name: tool.name, description: tool.description ?? '' })) : [],
|
|
302
|
+
: detail === 'tools' ? tools.slice(0, 500).map(tool => ({ name: tool.name, description: tool.description ?? '', ...access(tool) })) : [],
|
|
219
303
|
};
|
|
220
304
|
if (detail === 'overview') {
|
|
221
305
|
row.stats = slot?.stats ?? { calls: 0, failures: 0, active: 0 };
|
|
@@ -228,7 +312,11 @@ export class ManagerRuntime {
|
|
|
228
312
|
row.resources = (view?.resources ?? []).slice(0, 500).map(resource => ({
|
|
229
313
|
name: resource.name, uri: resource.uri, description: resource.description ?? '', mimeType: resource.mimeType ?? '',
|
|
230
314
|
}));
|
|
231
|
-
|
|
315
|
+
if (view?.resourceTemplates?.length) row.resourceTemplates = view.resourceTemplates;
|
|
316
|
+
if (slot?.generation?.watches?.supported) row.canWatchResources = true;
|
|
317
|
+
row.prompts = (view?.prompts ?? []).slice(0, 500).map(prompt => ({ name: prompt.name, description: prompt.description ?? '',
|
|
318
|
+
arguments: Array.isArray(prompt.arguments) ? prompt.arguments.slice(0, 16).map(arg => ({
|
|
319
|
+
name: String(arg?.name ?? '').slice(0, 64), description: String(arg?.description ?? '').slice(0, 300), required: arg?.required === true })) : [] }));
|
|
232
320
|
row.metadataUnavailable = view?.metadataUnavailable ?? { resources: false, prompts: false };
|
|
233
321
|
}
|
|
234
322
|
return [server.id, this.safe(row)];
|
|
@@ -245,7 +333,7 @@ export class ManagerRuntime {
|
|
|
245
333
|
let slot = this.slots.get(id);
|
|
246
334
|
if (!slot) {
|
|
247
335
|
slot = { id, generation: null, chain: Promise.resolve(), retries: 0, timer: null, nextRetryAt: null,
|
|
248
|
-
halted: false, exhausted: false, history: [], stats: { calls: 0, failures: 0, active: 0 },
|
|
336
|
+
halted: false, exhausted: false, history: [], stats: { calls: 0, failures: 0, active: 0 }, logs: [], logLevel: null,
|
|
249
337
|
view: { status: 'disconnected', error: null, tools: [], resources: [], prompts: [] } };
|
|
250
338
|
this.slots.set(id, slot);
|
|
251
339
|
}
|
|
@@ -258,16 +346,19 @@ export class ManagerRuntime {
|
|
|
258
346
|
}
|
|
259
347
|
clearTimer(slot) { if (slot.timer) clearTimeout(slot.timer); slot.timer = null; slot.nextRetryAt = null; }
|
|
260
348
|
recordCall(slot, rawName, started, code) {
|
|
349
|
+
const at = Date.now(), durationMs = at - started;
|
|
261
350
|
slot.stats.active = Math.max(0, slot.stats.active - 1);
|
|
262
351
|
if (code) slot.stats.failures++;
|
|
263
|
-
slot.history.unshift({ tool: rawName, at
|
|
352
|
+
slot.history.unshift({ tool: rawName, at, durationMs,
|
|
264
353
|
ok: !code, ...(code ? { code, message: MESSAGES[code] } : {}) });
|
|
265
354
|
slot.history.length = Math.min(20, slot.history.length);
|
|
355
|
+
this.options.onCall?.({ serverId: slot.id, tool: rawName, at, durationMs, ok: !code, ...(code ? { code } : {}) });
|
|
266
356
|
this.changed();
|
|
267
357
|
}
|
|
268
358
|
revoke(generation) {
|
|
269
359
|
if (!generation) return;
|
|
270
360
|
generation.controller.abort();
|
|
361
|
+
generation.watches?.dispose();
|
|
271
362
|
for (const [name, registration] of generation.registrations) {
|
|
272
363
|
registration.dispose();
|
|
273
364
|
if (this.owned.get(name)?.generation === generation) this.owned.delete(name);
|
|
@@ -413,6 +504,9 @@ export class ManagerRuntime {
|
|
|
413
504
|
const rememberSecret = value => this.rememberSecret(value);
|
|
414
505
|
for (const row of [...server.headers ?? [], ...server.env ?? []]) if (row.value) rememberSecret(row.value);
|
|
415
506
|
if (server.transport === 'stdio') {
|
|
507
|
+
if (server.cwd && !(process.platform === 'win32' ? isWindowsAbsoluteCwd(server.cwd) : server.cwd.startsWith('/'))) {
|
|
508
|
+
throw fault('stdio-cwd-platform');
|
|
509
|
+
}
|
|
416
510
|
const env = scrubbedParentEnv();
|
|
417
511
|
for (const row of server.env ?? []) {
|
|
418
512
|
let value = row.value ?? '';
|
|
@@ -424,8 +518,26 @@ export class ManagerRuntime {
|
|
|
424
518
|
env[row.name] = value;
|
|
425
519
|
}
|
|
426
520
|
this.assertCurrent(generation);
|
|
427
|
-
|
|
428
|
-
cwd: server.cwd || undefined, env, stderr: '
|
|
521
|
+
const transport = new StdioClientTransport({ command: server.command, args: server.args ?? [],
|
|
522
|
+
cwd: server.cwd || undefined, env, stderr: 'pipe' });
|
|
523
|
+
// Auto negotiation may fail in the SDK's disposable probe before the
|
|
524
|
+
// session transport starts. Only a real session needs the close barrier.
|
|
525
|
+
const start = transport.start.bind(transport);
|
|
526
|
+
transport.start = async () => {
|
|
527
|
+
generation.started = true;
|
|
528
|
+
try { await start(); }
|
|
529
|
+
catch (error) { if (!transport.pid) generation.started = false; throw error; }
|
|
530
|
+
};
|
|
531
|
+
// Attach before connect/start: some failed launches only log once, at boot.
|
|
532
|
+
generation.flushStderr = captureStderr(transport.stderr, raw => {
|
|
533
|
+
if (generation.slot.generation !== generation || generation.controller.signal.aborted) return;
|
|
534
|
+
const line = this.safe(stripVTControlCharacters(raw).replace(/[\x00-\x08\x0a-\x1f\x7f]/g, ''))
|
|
535
|
+
.replace(/(\bhttps?:\/\/)[^/\s@]+@/gi, '$1[已隐藏]@')
|
|
536
|
+
.replace(/(\b[\w-]*(?:api[-_]?key|password|passwd|secret|token)\b["']?\s*[:=]\s*)(?:"[^"]*"|'[^']*'|\S+)/gi, '$1[已隐藏]')
|
|
537
|
+
.trimEnd();
|
|
538
|
+
if (line) this.appendLog(generation.slot, 'stderr', 'stdio', line.slice(0, 4000));
|
|
539
|
+
});
|
|
540
|
+
return transport;
|
|
429
541
|
}
|
|
430
542
|
for (const row of server.headers ?? []) if (row.credentialRef) {
|
|
431
543
|
const value = await this.options.resolveSecret(row.credentialRef);
|
|
@@ -446,9 +558,11 @@ export class ManagerRuntime {
|
|
|
446
558
|
async start(slot, server) {
|
|
447
559
|
let resolveClosed;
|
|
448
560
|
const generation = { slot, server, key: connectionKey(server), controller: new AbortController(),
|
|
449
|
-
registrations: new Map(), client: null, transport: null, started: false, connecting: true,
|
|
561
|
+
registrations: new Map(), toolTarget: toolTarget(server), client: null, transport: null, started: false, connecting: true,
|
|
450
562
|
closeObserved: false, closePromise: new Promise(resolve => { resolveClosed = resolve; }),
|
|
451
563
|
sync: Promise.resolve() };
|
|
564
|
+
if (slot.logKey !== generation.key) { slot.logs = []; slot.logKey = generation.key; }
|
|
565
|
+
slot.logLevel = null;
|
|
452
566
|
slot.generation = generation;
|
|
453
567
|
const started = Date.now();
|
|
454
568
|
slot.view = { status: 'connecting', error: null, tools: [], resources: [], prompts: [], refreshing: false };
|
|
@@ -460,9 +574,10 @@ export class ManagerRuntime {
|
|
|
460
574
|
const listChanged = Object.fromEntries(['tools', 'resources', 'prompts'].map(kind => [kind,
|
|
461
575
|
{ autoRefresh: false, debounceMs: 100, onChanged: refresh }]));
|
|
462
576
|
const factory = this.options.createClient ?? ((identity, options) => new Client(identity, options));
|
|
463
|
-
generation.client = factory({ name: 'dsh-go-mcp-manager', version:
|
|
577
|
+
generation.client = factory({ name: 'dsh-go-mcp-manager', version: manifest.version },
|
|
464
578
|
{ capabilities: {}, versionNegotiation: { mode: 'auto' }, listChanged });
|
|
465
579
|
generation.client.onclose = () => {
|
|
580
|
+
generation.flushStderr?.();
|
|
466
581
|
generation.closeObserved = true;
|
|
467
582
|
resolveClosed();
|
|
468
583
|
if (!generation.connecting && this.live(generation)) this.down(generation);
|
|
@@ -471,7 +586,6 @@ export class ManagerRuntime {
|
|
|
471
586
|
generation.client.onerror = () => {};
|
|
472
587
|
generation.transport = await bounded(() => this.transport(generation), generation.controller.signal, timeoutFor(server));
|
|
473
588
|
this.assertCurrent(generation);
|
|
474
|
-
generation.started = true;
|
|
475
589
|
await bounded(signal => generation.client.connect(generation.transport, { signal, timeout: timeoutFor(server) }),
|
|
476
590
|
generation.controller.signal, timeoutFor(server));
|
|
477
591
|
if (generation.closeObserved) throw fault('connection-failed');
|
|
@@ -492,11 +606,14 @@ export class ManagerRuntime {
|
|
|
492
606
|
await this.retire(slot);
|
|
493
607
|
if (slot.halted || this.closed) return;
|
|
494
608
|
slot.view.status = cancelled ? 'disconnected' : 'error';
|
|
495
|
-
const
|
|
609
|
+
const launchFault = server.transport === 'stdio'
|
|
610
|
+
? ({ ENOENT: 'stdio-start-not-found', EACCES: 'stdio-start-denied', EPERM: 'stdio-start-denied' })[error?.code]
|
|
611
|
+
: undefined;
|
|
612
|
+
const code = errorCode(error, generation.lastFetchFault ?? launchFault ?? 'connection-failed');
|
|
496
613
|
slot.view.error = cancelled ? null : { code, message: MESSAGES[code] };
|
|
497
614
|
slot.view.tools = []; slot.view.resources = []; slot.view.prompts = [];
|
|
498
615
|
slot.view.lastCheck = { at: Date.now(), durationMs: Date.now() - started, ok: false };
|
|
499
|
-
slot.blocked = !cancelled && ['credential-missing','auth-rejected','access-denied','rate-limited','invalid-transport','unsafe-request','registration-failed','schema-secret'].includes(code);
|
|
616
|
+
slot.blocked = !cancelled && ['credential-missing','auth-rejected','access-denied','rate-limited','invalid-transport','stdio-cwd-platform','stdio-start-not-found','stdio-start-denied','unsafe-request','registration-failed','schema-secret'].includes(code);
|
|
500
617
|
if (!cancelled && !slot.blocked) this.retry(slot);
|
|
501
618
|
this.changed();
|
|
502
619
|
}
|
|
@@ -527,10 +644,131 @@ export class ManagerRuntime {
|
|
|
527
644
|
this.enqueue(slot, () => this.ensure(slot));
|
|
528
645
|
}, delay);
|
|
529
646
|
}
|
|
647
|
+
slotConnection(id) {
|
|
648
|
+
const generation = this.slots.get(id)?.generation;
|
|
649
|
+
if (!generation?.client || generation.connecting || !this.live(generation)) throw fault('unsupported');
|
|
650
|
+
return generation;
|
|
651
|
+
}
|
|
652
|
+
async readResource(id, selection) {
|
|
653
|
+
const generation = this.slotConnection(id);
|
|
654
|
+
if (!generation.capabilities?.resources) throw fault('unsupported');
|
|
655
|
+
let uri = selection;
|
|
656
|
+
if (selection && typeof selection === 'object') {
|
|
657
|
+
const { uriTemplate, values } = selection;
|
|
658
|
+
if (!(generation.slot.view.resourceTemplates ?? []).some(row => row.uriTemplate === uriTemplate)) throw fault('invalid-template');
|
|
659
|
+
try { uri = expandResourceTemplate(uriTemplate, values); }
|
|
660
|
+
catch { throw fault('invalid-template'); }
|
|
661
|
+
}
|
|
662
|
+
if (typeof uri !== 'string' || !uri || uri.length > 4096) throw fault('read-failed');
|
|
663
|
+
const server = this.server(id);
|
|
664
|
+
const result = await bounded(signal => generation.client.readResource({ uri },
|
|
665
|
+
{ signal, timeout: timeoutFor(server), cacheMode: 'refresh' }), generation.controller.signal, timeoutFor(server));
|
|
666
|
+
this.assertCurrent(generation);
|
|
667
|
+
if (generation.watches?.supported && this.safe(uri) === uri) {
|
|
668
|
+
generation.previewed ??= new Set();
|
|
669
|
+
if (generation.previewed.size >= 64) generation.previewed.delete(generation.previewed.values().next().value);
|
|
670
|
+
generation.previewed.add(uri);
|
|
671
|
+
}
|
|
672
|
+
uri = this.safe(uri);
|
|
673
|
+
const row = Array.isArray(result?.contents) ? result.contents[0] : null;
|
|
674
|
+
if (!row || typeof row !== 'object') return { uri, mimeType: null, text: null, blob: null, truncated: false, size: 0 };
|
|
675
|
+
const mimeType = typeof row.mimeType === 'string' && row.mimeType ? row.mimeType.slice(0, 120) : null;
|
|
676
|
+
if (typeof row.text === 'string') {
|
|
677
|
+
const text = this.safe(row.text);
|
|
678
|
+
return { uri, mimeType, text, blob: null, truncated: text.length >= 16000, size: row.text.length };
|
|
679
|
+
}
|
|
680
|
+
if (typeof row.blob === 'string' && row.blob) {
|
|
681
|
+
const valid = /^(?:image\/(?:png|jpeg|gif|webp))$/i.test(mimeType ?? '') && row.blob.length <= 160000
|
|
682
|
+
&& /^[A-Za-z0-9+/]+={0,2}$/.test(row.blob) && row.blob.length % 4 === 0;
|
|
683
|
+
return { uri, mimeType, text: null, blob: valid ? row.blob : null, truncated: row.blob.length > 160000, size: row.blob.length };
|
|
684
|
+
}
|
|
685
|
+
return { uri, mimeType, text: null, blob: null, truncated: false, size: 0 };
|
|
686
|
+
}
|
|
687
|
+
resourceWatches(id) {
|
|
688
|
+
const generation = this.slotConnection(id);
|
|
689
|
+
const rows = generation.watches?.list() ?? [];
|
|
690
|
+
return { supported: generation.watches?.supported === true, rows: rows.filter(row => this.safe(row.uri) === row.uri) };
|
|
691
|
+
}
|
|
692
|
+
async setResourceWatch(id, uri, enabled) {
|
|
693
|
+
const generation = this.slotConnection(id);
|
|
694
|
+
if (!generation.watches?.supported) throw fault('unsupported');
|
|
695
|
+
if (enabled && !(generation.previewed?.has(uri) || generation.watches.list().some(row => row.uri === uri))) throw fault('invalid-template');
|
|
696
|
+
try { await generation.watches.set(uri, enabled); }
|
|
697
|
+
catch (error) {
|
|
698
|
+
const code = ['timeout', 'cancelled', 'unsupported', 'watch-limit'].includes(error?.code) ? error.code : 'watch-failed';
|
|
699
|
+
throw fault(code);
|
|
700
|
+
}
|
|
701
|
+
if (!this.live(generation)) throw fault('cancelled');
|
|
702
|
+
return this.resourceWatches(id);
|
|
703
|
+
}
|
|
704
|
+
async getPrompt(id, name, args) {
|
|
705
|
+
const generation = this.slotConnection(id);
|
|
706
|
+
if (!generation.capabilities?.prompts) throw fault('unsupported');
|
|
707
|
+
if (typeof name !== 'string' || !name || name.length > 256) throw fault('prompt-failed');
|
|
708
|
+
const pairs = (Array.isArray(args) ? args : [])
|
|
709
|
+
.filter(row => row && typeof row.name === 'string' && row.name && typeof row.value === 'string')
|
|
710
|
+
.slice(0, 16).map(row => [row.name.slice(0, 64), row.value.slice(0, 2000)]);
|
|
711
|
+
const server = this.server(id);
|
|
712
|
+
const result = await bounded(signal => generation.client.getPrompt({ name,
|
|
713
|
+
arguments: pairs.length ? Object.fromEntries(pairs) : undefined },
|
|
714
|
+
{ signal, timeout: timeoutFor(server) }), generation.controller.signal, timeoutFor(server));
|
|
715
|
+
const messages = (Array.isArray(result?.messages) ? result.messages : []).slice(0, 10).map(message => {
|
|
716
|
+
const content = message?.content;
|
|
717
|
+
const text = typeof content?.text === 'string' ? content.text
|
|
718
|
+
: content ? `[未支持的内容类型:${String(content.type ?? 'unknown').slice(0, 24)}]` : '[空消息]';
|
|
719
|
+
return { role: message?.role === 'assistant' ? 'assistant' : 'user', text: this.safe(text) };
|
|
720
|
+
});
|
|
721
|
+
return { description: typeof result?.description === 'string' && result.description ? this.safe(result.description) : null, messages };
|
|
722
|
+
}
|
|
723
|
+
async setLogLevel(id, level) {
|
|
724
|
+
const generation = this.slotConnection(id);
|
|
725
|
+
if (!generation.capabilities?.logging) throw fault('unsupported');
|
|
726
|
+
if (!['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency'].includes(level)) throw fault('unsupported');
|
|
727
|
+
await bounded(signal => generation.client.setLoggingLevel({ level }, { signal, timeout: 15000 }),
|
|
728
|
+
generation.controller.signal, 15000);
|
|
729
|
+
const slot = this.slots.get(id);
|
|
730
|
+
if (slot) slot.logLevel = level;
|
|
731
|
+
return level;
|
|
732
|
+
}
|
|
733
|
+
appendLog(slot, level, logger, data) {
|
|
734
|
+
if (!slot) return;
|
|
735
|
+
slot.logs ??= [];
|
|
736
|
+
slot.logs.unshift({
|
|
737
|
+
at: Date.now(),
|
|
738
|
+
level: String(level ?? 'info').slice(0, 16),
|
|
739
|
+
logger: typeof logger === 'string' && logger ? this.safe(logger).slice(0, 64) : null,
|
|
740
|
+
data: this.safe(data),
|
|
741
|
+
});
|
|
742
|
+
slot.logs.length = Math.min(LOG_MAX, slot.logs.length);
|
|
743
|
+
}
|
|
744
|
+
logTail(id) {
|
|
745
|
+
const slot = this.slots.get(id), server = this.server(id);
|
|
746
|
+
if (!slot || !server || slot.logKey !== connectionKey(server)) return { level: null, lines: [] };
|
|
747
|
+
return { level: slot.logLevel ?? null, lines: slot.logs.slice(0, LOG_MAX) };
|
|
748
|
+
}
|
|
530
749
|
async discover(generation) {
|
|
531
750
|
this.assertCurrent(generation);
|
|
532
751
|
const client = generation.client;
|
|
533
752
|
const capabilities = client.getServerCapabilities() ?? {};
|
|
753
|
+
generation.capabilities = capabilities;
|
|
754
|
+
if (!generation.watches && capabilities.resources?.subscribe === true) {
|
|
755
|
+
try { generation.watches = createResourceWatches(client, generation.controller.signal, {
|
|
756
|
+
timeoutMs: Math.min(timeoutFor(generation.server), 6000), isCurrent: () => this.live(generation),
|
|
757
|
+
}); } catch { /* Unavailable subscription must not break ordinary reads. */ }
|
|
758
|
+
}
|
|
759
|
+
generation.slot.view.resourcesCallable = Boolean(capabilities.resources);
|
|
760
|
+
generation.slot.view.promptsCallable = Boolean(capabilities.prompts);
|
|
761
|
+
generation.slot.view.loggingCallable = Boolean(capabilities.logging);
|
|
762
|
+
if (capabilities.logging && !generation.loggingHandler && typeof client.setNotificationHandler === 'function') {
|
|
763
|
+
try {
|
|
764
|
+
client.setNotificationHandler('notifications/message', note => {
|
|
765
|
+
if (generation.slot.generation !== generation || generation.controller.signal.aborted) return;
|
|
766
|
+
const params = note?.params ?? {};
|
|
767
|
+
this.appendLog(generation.slot, params.level ?? 'info', params.logger, params.data);
|
|
768
|
+
});
|
|
769
|
+
generation.loggingHandler = true;
|
|
770
|
+
} catch { /* Best effort: servers without the logging capability never emit. */ }
|
|
771
|
+
}
|
|
534
772
|
const server = generation.server;
|
|
535
773
|
generation.lastFetchFault = null;
|
|
536
774
|
const request = fn => bounded(signal => fn({ signal, timeout: timeoutFor(server), cacheMode: 'refresh' }),
|
|
@@ -538,17 +776,30 @@ export class ManagerRuntime {
|
|
|
538
776
|
if (!capabilities.tools && !capabilities.resources && !capabilities.prompts) await request(options => client.ping(options));
|
|
539
777
|
const response = capabilities.tools ? await request(options => client.listTools(undefined, options)) : { tools: [] };
|
|
540
778
|
if (response.tools.length > 500) throw fault('discovery-failed');
|
|
779
|
+
const selected = new Map();
|
|
780
|
+
for (const tool of response.tools) {
|
|
781
|
+
if (typeof tool.name !== 'string' || !tool.name || tool.name.length > 1024 || selected.has(tool.name)) throw fault('discovery-failed');
|
|
782
|
+
selected.set(tool.name, { signature: toolFingerprint(tool), identity: toolIdentity(tool.name), hint: toolHint(tool.annotations) });
|
|
783
|
+
}
|
|
784
|
+
this.assertCurrent(generation);
|
|
785
|
+
// Freeze a changed/removed definition as soon as we have a new valid list,
|
|
786
|
+
// even if a later registration swap fails and reinstates old objects.
|
|
787
|
+
generation.observed = new Map([...selected].map(([name, row]) => [name, row.signature]));
|
|
541
788
|
const resources = capabilities.resources && client.listResources
|
|
542
789
|
? await request(options => client.listResources(undefined, options)).catch(() => ({ resources: [], unavailable: true }))
|
|
543
790
|
: { resources: [] };
|
|
791
|
+
const templates = capabilities.resources && typeof client.listResourceTemplates === 'function'
|
|
792
|
+
? await request(options => client.listResourceTemplates(undefined, options)).catch(() => ({resourceTemplates: []}))
|
|
793
|
+
: {resourceTemplates: []};
|
|
544
794
|
const prompts = capabilities.prompts && client.listPrompts
|
|
545
795
|
? await request(options => client.listPrompts(undefined, options)).catch(() => ({ prompts: [], unavailable: true }))
|
|
546
796
|
: { prompts: [] };
|
|
547
797
|
this.assertCurrent(generation);
|
|
548
798
|
const definitions = new Map();
|
|
549
799
|
for (const tool of response.tools) {
|
|
550
|
-
if (typeof tool.name !== 'string' || !tool.name || tool.name.length > 1024) throw fault('discovery-failed');
|
|
551
800
|
const name = publicToolName(server.id, tool.name);
|
|
801
|
+
const {signature, identity, hint} = selected.get(tool.name);
|
|
802
|
+
const ticket = Symbol();
|
|
552
803
|
if (definitions.has(name)) throw fault('discovery-failed');
|
|
553
804
|
// Reflected connection credentials must never become model-visible schema.
|
|
554
805
|
const serialized = JSON.stringify([tool.name, tool.inputSchema, tool.outputSchema]);
|
|
@@ -557,10 +808,10 @@ export class ManagerRuntime {
|
|
|
557
808
|
description: this.safe(tool.description ?? ''), inputSchema: clone(tool.inputSchema), outputSchema: tool.outputSchema,
|
|
558
809
|
taskRequired: tool.execution?.taskSupport === 'required',
|
|
559
810
|
call: async (args, execution) => {
|
|
560
|
-
this.assertCurrent(generation, tool.name);
|
|
811
|
+
this.assertCurrent(generation, tool.name, ticket);
|
|
561
812
|
const signal = AbortSignal.any([execution.signal, generation.controller.signal]);
|
|
562
813
|
const result = await bounded(async boundedSignal => {
|
|
563
|
-
this.assertCurrent(generation, tool.name);
|
|
814
|
+
this.assertCurrent(generation, tool.name, ticket);
|
|
564
815
|
return client.callTool({ name: tool.name, arguments: args },
|
|
565
816
|
{ signal: boundedSignal, timeout: timeoutFor(this.server(server.id)), toolDefinition: tool });
|
|
566
817
|
}, signal, timeoutFor(this.server(server.id)));
|
|
@@ -572,7 +823,7 @@ export class ManagerRuntime {
|
|
|
572
823
|
// or result bodies. Arbitrary tools are never replayed automatically.
|
|
573
824
|
const execute = definition.execute;
|
|
574
825
|
definition.execute = async (args, execution) => {
|
|
575
|
-
this.assertCurrent(generation, tool.name);
|
|
826
|
+
this.assertCurrent(generation, tool.name, ticket);
|
|
576
827
|
const slot = generation.slot, started = Date.now();
|
|
577
828
|
slot.stats.calls++; slot.stats.active++;
|
|
578
829
|
this.changed();
|
|
@@ -589,14 +840,17 @@ export class ManagerRuntime {
|
|
|
589
840
|
}
|
|
590
841
|
finally { this.recordCall(slot, tool.name, started, code); }
|
|
591
842
|
};
|
|
592
|
-
definitions.set(name, { definition, rawName: tool.name, signature
|
|
843
|
+
definitions.set(name, { definition, rawName: tool.name, signature, identity, hint, ticket });
|
|
593
844
|
}
|
|
845
|
+
if (capabilities.tools) await this.toolTrust.observe(generation.toolTarget, [...selected.values()].map(row => [row.identity, row.signature]),
|
|
846
|
+
() => this.assertCurrent(generation));
|
|
847
|
+
this.assertCurrent(generation);
|
|
594
848
|
// Install new names before replacing existing ones. Failed replacement rolls
|
|
595
849
|
// back the prior definitions, keeping its last successfully read catalog.
|
|
596
850
|
const prior = new Map(generation.registrations);
|
|
597
851
|
const installed = new Set(), removed = new Set();
|
|
598
852
|
const register = (name, item) => {
|
|
599
|
-
const dispose = this.ctx.tools.register(item.definition, { when: () => this.allowed(generation, item.rawName) });
|
|
853
|
+
const dispose = this.ctx.tools.register(item.definition, { when: () => this.allowed(generation, item.rawName, item.ticket) });
|
|
600
854
|
generation.registrations.set(name, { ...item, dispose });
|
|
601
855
|
this.owned.set(name, { generation, rawName: item.rawName });
|
|
602
856
|
};
|
|
@@ -623,10 +877,21 @@ export class ManagerRuntime {
|
|
|
623
877
|
}
|
|
624
878
|
for (const [name, item] of prior) if (!definitions.has(name)) remove(name, item);
|
|
625
879
|
generation.slot.view.tools = response.tools.map(tool => ({ name: tool.name,
|
|
626
|
-
description: tool.description ?? '', inputSchema: tool.inputSchema }));
|
|
880
|
+
description: tool.description ?? '', inputSchema: tool.inputSchema, ...(tool.outputSchema ? {outputSchema: tool.outputSchema} : {}) }));
|
|
627
881
|
generation.slot.view.resources = (resources.resources ?? []).slice(0, 500).map(resource => ({
|
|
628
882
|
name: resource.name, uri: resource.uri, description: resource.description ?? '', mimeType: resource.mimeType ?? '',
|
|
629
883
|
}));
|
|
884
|
+
const refs = new Set();
|
|
885
|
+
generation.slot.view.resourceTemplates = (Array.isArray(templates.resourceTemplates) ? templates.resourceTemplates : []).slice(0, 32).flatMap(row => {
|
|
886
|
+
try {
|
|
887
|
+
const template = row?.uriTemplate;
|
|
888
|
+
if (typeof template !== 'string' || refs.has(template) || this.safe(template) !== template) return [];
|
|
889
|
+
const variables = resourceTemplateVariables(template);
|
|
890
|
+
refs.add(template);
|
|
891
|
+
return [{uriTemplate: template, name: typeof row.name === 'string' ? row.name.slice(0, 200) : '',
|
|
892
|
+
description: typeof row.description === 'string' ? row.description.slice(0, 720) : '', variables}];
|
|
893
|
+
} catch { return []; }
|
|
894
|
+
});
|
|
630
895
|
generation.slot.view.prompts = (prompts.prompts ?? []).slice(0, 500).map(prompt => ({
|
|
631
896
|
name: prompt.name, description: prompt.description ?? '', arguments: prompt.arguments ?? [],
|
|
632
897
|
}));
|