@agentpro/scroll 0.0.0-stage → 2.5.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/AGENTS.md +55 -0
- package/LICENSE +21 -0
- package/README.md +293 -2
- package/SPEC.md +1079 -0
- package/bin/scroll.js +8 -0
- package/docs/prompt-caching.md +128 -0
- package/index.js +33 -0
- package/lib/audit.js +358 -0
- package/lib/auth.js +849 -0
- package/lib/chat-sdk/admin-controller.js +289 -0
- package/lib/chat-sdk/debouncer.js +94 -0
- package/lib/chat-sdk/group-grants.js +150 -0
- package/lib/chat-sdk/index.js +222 -0
- package/lib/chat-sdk/long-task-runner.js +413 -0
- package/lib/chat-session.js +1788 -0
- package/lib/chat-telemetry.js +557 -0
- package/lib/codex-app-server.js +851 -0
- package/lib/digest.js +112 -0
- package/lib/effects.js +157 -0
- package/lib/eval.js +408 -0
- package/lib/grounding.js +356 -0
- package/lib/installers.js +176 -0
- package/lib/knowledge.js +335 -0
- package/lib/ledger.js +38 -0
- package/lib/loop.js +197 -0
- package/lib/mcp-client.js +926 -0
- package/lib/memory-cli.js +66 -0
- package/lib/memory-tracker.js +1472 -0
- package/lib/memory.js +1279 -0
- package/lib/people-cli.js +81 -0
- package/lib/people.js +534 -0
- package/lib/permissions.js +272 -0
- package/lib/providers.js +1572 -0
- package/lib/runtime.js +928 -0
- package/lib/sandbox.js +744 -0
- package/lib/scheduler.js +402 -0
- package/lib/scroll.js +1225 -0
- package/lib/skill-cli.js +120 -0
- package/lib/skill-eval.js +156 -0
- package/lib/skills.js +860 -0
- package/lib/style.js +126 -0
- package/lib/tool-retriever.js +489 -0
- package/lib/tools.js +1833 -0
- package/lib/user.js +711 -0
- package/lib/vault.js +151 -0
- package/package.json +88 -4
- package/templates/agent/IDENTITY.md +56 -0
- package/templates/agent/SOUL.md +23 -0
- package/templates/agent/TOOLS.md +25 -0
- package/templates/agent/evals/case-02-citation-discipline.md +29 -0
- package/templates/agent/evals/case-03-boundary.md +27 -0
- package/templates/agent/evals/case-example.md +43 -0
- package/templates/agent/hard-rules.md +11 -0
- package/templates/agent/memory/lessons.md +5 -0
- package/templates/agent/memory/log/.gitkeep +0 -0
- package/templates/external-safety-contract.md +5 -0
- package/templates/long-task-planner.md +17 -0
- package/templates/work/LOOP.md +37 -0
- package/templates/work/WORK.md +50 -0
- package/types/chat.d.ts +61 -0
- package/types/index.d.ts +112 -0
|
@@ -0,0 +1,926 @@
|
|
|
1
|
+
// SCROLL 2.5 -- §47 Zero-Dependency MCP (Model Context Protocol) Client:
|
|
2
|
+
// - stdio JSON-RPC 2.0 transport with sanitized subprocess env (no ambient secret leak!)
|
|
3
|
+
// - Streamable HTTP transport (`POST` JSON-RPC + `application/json` & `text/event-stream`,
|
|
4
|
+
// `Mcp-Session-Id` header lifecycle, automatic HTTP 404 stale-session re-initialization)
|
|
5
|
+
// - Fail-closed `${vault:KEY}` resolution (throws on missing secret instead of empty string)
|
|
6
|
+
// - Per-server fault isolation in `connectAll()` (one dead server never aborts others)
|
|
7
|
+
// - `notifications/tools/list_changed` handling + `.scroll/mcp.lock.json` TOFU schema pinning
|
|
8
|
+
// & ASI04 rug-pull quarantine (`diffMcpLock` / `approveMcpLock`)
|
|
9
|
+
//
|
|
10
|
+
// Zero runtime dependencies. Node >= 20 built-ins only.
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import crypto from 'node:crypto';
|
|
14
|
+
import readline from 'node:readline';
|
|
15
|
+
import { spawn } from 'node:child_process';
|
|
16
|
+
import { buildSanitizedEnv } from './sandbox.js';
|
|
17
|
+
import { resolveVaultPlaceholders } from './vault.js';
|
|
18
|
+
import { computeSchemaHash, computeDescHash } from './tool-retriever.js';
|
|
19
|
+
|
|
20
|
+
function normalizeTransport(cfg) {
|
|
21
|
+
const raw = String(cfg.transport || cfg.type || '').trim().toLowerCase();
|
|
22
|
+
if (raw === 'stdio') return 'stdio';
|
|
23
|
+
if (raw === 'http' || raw === 'streamable-http' || raw === 'streamable_http') return 'http';
|
|
24
|
+
if (raw) return raw;
|
|
25
|
+
if (cfg.command) return 'stdio';
|
|
26
|
+
if (cfg.url) return 'http';
|
|
27
|
+
return 'stdio';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function hashCommandSpec(cfg) {
|
|
31
|
+
const basis = cfg.transport === 'http'
|
|
32
|
+
? JSON.stringify({ transport: 'http', url: String(cfg.url || '') })
|
|
33
|
+
: JSON.stringify({
|
|
34
|
+
transport: 'stdio',
|
|
35
|
+
command: String(cfg.command || ''),
|
|
36
|
+
args: Array.isArray(cfg.args) ? cfg.args.map(String) : [],
|
|
37
|
+
cwd: cfg.cwd ? path.resolve(String(cfg.cwd)) : '',
|
|
38
|
+
});
|
|
39
|
+
return crypto.createHash('sha256').update(basis).digest('hex').slice(0, 16);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const SUPPORTED_MCP_PROTOCOLS = ['2025-06-18', '2025-03-26', '2024-11-05'];
|
|
43
|
+
|
|
44
|
+
function assertSafeMcpHttpUrl(rawUrl) {
|
|
45
|
+
let u;
|
|
46
|
+
try { u = new URL(String(rawUrl || '')); } catch { throw new Error(`mcp_http_invalid_url:${rawUrl}`); }
|
|
47
|
+
if (u.protocol !== 'http:' && u.protocol !== 'https:') {
|
|
48
|
+
throw new Error(`mcp_http_disallowed_protocol:${u.protocol}`);
|
|
49
|
+
}
|
|
50
|
+
const host = (u.hostname || '').toLowerCase().replace(/^\[|\]$/g, '');
|
|
51
|
+
if (!host || host === '169.254.169.254' || host === 'metadata.google.internal' || host === 'metadata') {
|
|
52
|
+
throw new Error(`mcp_http_ssrf_blocked:${host}`);
|
|
53
|
+
}
|
|
54
|
+
return u.toString();
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function loadMcpConfig({
|
|
58
|
+
cwd = process.cwd(),
|
|
59
|
+
agentDir = null,
|
|
60
|
+
env = process.env,
|
|
61
|
+
vault = null,
|
|
62
|
+
failClosed = true,
|
|
63
|
+
isolateErrors = false,
|
|
64
|
+
onServerError = null,
|
|
65
|
+
} = {}) {
|
|
66
|
+
const files = [path.join(cwd, '.mcp.json')];
|
|
67
|
+
if (agentDir) files.push(path.join(agentDir, '.mcp.json'));
|
|
68
|
+
const servers = {};
|
|
69
|
+
for (const file of files) {
|
|
70
|
+
if (!fs.existsSync(file)) continue;
|
|
71
|
+
let parsed;
|
|
72
|
+
try { parsed = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { continue; }
|
|
73
|
+
for (const [name, cfg] of Object.entries(parsed.mcpServers || {})) {
|
|
74
|
+
if (!cfg || typeof cfg !== 'object') continue;
|
|
75
|
+
try {
|
|
76
|
+
const resolvedEnv = {};
|
|
77
|
+
for (const [k, v] of Object.entries(cfg.env || {})) {
|
|
78
|
+
resolvedEnv[k] = resolveVaultPlaceholders(String(v), { env, vault, failClosed });
|
|
79
|
+
}
|
|
80
|
+
const resolvedHeaders = {};
|
|
81
|
+
for (const [k, v] of Object.entries(cfg.headers || {})) {
|
|
82
|
+
resolvedHeaders[k] = resolveVaultPlaceholders(String(v), { env, vault, failClosed });
|
|
83
|
+
}
|
|
84
|
+
const transport = normalizeTransport(cfg);
|
|
85
|
+
const args = Array.isArray(cfg.args)
|
|
86
|
+
? cfg.args.map((a) => resolveVaultPlaceholders(String(a), { env, vault, failClosed }))
|
|
87
|
+
: [];
|
|
88
|
+
const url = cfg.url ? resolveVaultPlaceholders(String(cfg.url), { env, vault, failClosed }) : null;
|
|
89
|
+
servers[name] = {
|
|
90
|
+
name,
|
|
91
|
+
command: cfg.command || null,
|
|
92
|
+
args,
|
|
93
|
+
url,
|
|
94
|
+
transport,
|
|
95
|
+
cwd: cfg.cwd ? path.resolve(cwd, cfg.cwd) : cwd,
|
|
96
|
+
env: resolvedEnv,
|
|
97
|
+
headers: resolvedHeaders,
|
|
98
|
+
description: cfg.description || '',
|
|
99
|
+
deferLoading: cfg.defer_loading !== undefined ? Boolean(cfg.defer_loading) : null,
|
|
100
|
+
tags: Array.isArray(cfg.tags) ? cfg.tags.map(String) : [],
|
|
101
|
+
allowEnv: Array.isArray(cfg.allow_env) ? cfg.allow_env.map(String) : null,
|
|
102
|
+
tools: cfg.tools && typeof cfg.tools === 'object' ? cfg.tools : {},
|
|
103
|
+
};
|
|
104
|
+
servers[name].cmdHash = hashCommandSpec(servers[name]);
|
|
105
|
+
} catch (err) {
|
|
106
|
+
if (!isolateErrors) throw err;
|
|
107
|
+
if (typeof onServerError === 'function') {
|
|
108
|
+
onServerError({ server: name, error: String(err?.message || err) });
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return servers;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ── .scroll/mcp.lock.json (TOFU Pinning & ASI04 Rug-Pull Quarantine) ───────────
|
|
117
|
+
export function mcpLockPath(cwd = process.cwd()) {
|
|
118
|
+
return path.join(path.resolve(cwd), '.scroll', 'mcp.lock.json');
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function loadMcpLock(cwd = process.cwd()) {
|
|
122
|
+
const p = mcpLockPath(cwd);
|
|
123
|
+
if (!fs.existsSync(p)) return { version: 1, tools: {} };
|
|
124
|
+
let parsed;
|
|
125
|
+
try {
|
|
126
|
+
parsed = JSON.parse(fs.readFileSync(p, 'utf8'));
|
|
127
|
+
} catch (err) {
|
|
128
|
+
// Fail-closed: a corrupt/truncated lockfile MUST NEVER be treated as first-run TOFU!
|
|
129
|
+
throw new Error(`mcp_lock_corrupt:${p}:${String(err?.message || err)}`);
|
|
130
|
+
}
|
|
131
|
+
if (
|
|
132
|
+
!parsed
|
|
133
|
+
|| typeof parsed !== 'object'
|
|
134
|
+
|| Array.isArray(parsed)
|
|
135
|
+
|| parsed.version !== 1
|
|
136
|
+
|| !parsed.tools
|
|
137
|
+
|| typeof parsed.tools !== 'object'
|
|
138
|
+
|| Array.isArray(parsed.tools)
|
|
139
|
+
) {
|
|
140
|
+
throw new Error(`mcp_lock_corrupt:${p}:invalid_schema`);
|
|
141
|
+
}
|
|
142
|
+
for (const [k, entry] of Object.entries(parsed.tools)) {
|
|
143
|
+
if (
|
|
144
|
+
!k
|
|
145
|
+
|| !entry
|
|
146
|
+
|| typeof entry !== 'object'
|
|
147
|
+
|| Array.isArray(entry)
|
|
148
|
+
|| typeof entry.server !== 'string'
|
|
149
|
+
|| !entry.server.trim()
|
|
150
|
+
|| typeof entry.schemaHash !== 'string'
|
|
151
|
+
|| !entry.schemaHash.trim()
|
|
152
|
+
|| typeof entry.descHash !== 'string'
|
|
153
|
+
|| !entry.descHash.trim()
|
|
154
|
+
) {
|
|
155
|
+
throw new Error(`mcp_lock_corrupt:${p}:invalid_tool_entry:${k || 'empty'}`);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return { version: 1, tools: parsed.tools };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function saveMcpLock(cwd = process.cwd(), lockObj) {
|
|
162
|
+
const p = mcpLockPath(cwd);
|
|
163
|
+
fs.mkdirSync(path.dirname(p), { recursive: true, mode: 0o700 });
|
|
164
|
+
const tmp = `${p}.tmp.${process.pid}.${crypto.randomBytes(3).toString('hex')}`;
|
|
165
|
+
fs.writeFileSync(tmp, JSON.stringify({ version: 1, updatedAt: new Date().toISOString(), tools: lockObj.tools || {} }, null, 2) + '\n', { mode: 0o600 });
|
|
166
|
+
fs.renameSync(tmp, p);
|
|
167
|
+
return p;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function verifyServerConfigAgainstLock(serverName, cfg, { cwd = process.cwd() } = {}) {
|
|
171
|
+
const lock = loadMcpLock(cwd);
|
|
172
|
+
const entries = Object.values(lock.tools || {}).filter((e) => e && e.server === serverName);
|
|
173
|
+
if (!entries.length) {
|
|
174
|
+
return { ok: true, pinnedServer: false };
|
|
175
|
+
}
|
|
176
|
+
const actualCmdHash = cfg?.cmdHash || null;
|
|
177
|
+
for (const e of entries) {
|
|
178
|
+
if ((e.cmdHash && actualCmdHash !== e.cmdHash) || (!e.cmdHash && actualCmdHash)) {
|
|
179
|
+
return {
|
|
180
|
+
ok: false,
|
|
181
|
+
pinnedServer: true,
|
|
182
|
+
reason: 'mcp_server_command_drifted_asi04',
|
|
183
|
+
expectedCmdHash: e.cmdHash || null,
|
|
184
|
+
actualCmdHash,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return { ok: true, pinnedServer: true };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export function verifyAndPinTools(discoveredTools, { cwd = process.cwd(), autoPin = true, pinnedBy = 'tofu' } = {}) {
|
|
192
|
+
const lock = loadMcpLock(cwd);
|
|
193
|
+
// Snapshot servers that ALREADY have pinned tools BEFORE this pass:
|
|
194
|
+
// TOFU `autoPin` may only onboard brand-new servers, NEVER silently approve newly-injected tools on an already-locked server!
|
|
195
|
+
const previouslyPinnedServers = new Set(
|
|
196
|
+
Object.values(lock.tools || {})
|
|
197
|
+
.map((e) => e && e.server)
|
|
198
|
+
.filter(Boolean)
|
|
199
|
+
);
|
|
200
|
+
let dirty = false;
|
|
201
|
+
const approved = [];
|
|
202
|
+
const quarantined = [];
|
|
203
|
+
|
|
204
|
+
for (const t of discoveredTools || []) {
|
|
205
|
+
const key = t.fullName || `mcp.${t.server}.${t.name}`;
|
|
206
|
+
const schemaHash = computeSchemaHash({ name: key, description: t.description, parameters: t.parameters });
|
|
207
|
+
const descHash = computeDescHash(t.description || '');
|
|
208
|
+
const enriched = { ...t, fullName: key, schemaHash, descHash };
|
|
209
|
+
|
|
210
|
+
const pinned = lock.tools[key];
|
|
211
|
+
if (!pinned) {
|
|
212
|
+
if (autoPin && !previouslyPinnedServers.has(t.server)) {
|
|
213
|
+
lock.tools[key] = {
|
|
214
|
+
server: t.server,
|
|
215
|
+
cmdHash: t.cmdHash || null,
|
|
216
|
+
tool: t.name,
|
|
217
|
+
schemaHash,
|
|
218
|
+
descHash,
|
|
219
|
+
risk: t.risk || null,
|
|
220
|
+
ground: Array.isArray(t.ground) ? t.ground : [],
|
|
221
|
+
short_description: t.shortDescription || null,
|
|
222
|
+
pinnedBy,
|
|
223
|
+
pinnedAt: new Date().toISOString(),
|
|
224
|
+
};
|
|
225
|
+
dirty = true;
|
|
226
|
+
approved.push({ ...enriched, lockStatus: 'pinned_new' });
|
|
227
|
+
} else {
|
|
228
|
+
quarantined.push({
|
|
229
|
+
...enriched,
|
|
230
|
+
lockStatus: 'unpinned',
|
|
231
|
+
reason: previouslyPinnedServers.has(t.server)
|
|
232
|
+
? 'mcp_unpinned_tool_on_locked_server'
|
|
233
|
+
: 'mcp_tool_not_pinned',
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const cmdDrifted = Boolean(
|
|
240
|
+
(pinned.cmdHash && t.cmdHash !== pinned.cmdHash)
|
|
241
|
+
|| (!pinned.cmdHash && t.cmdHash)
|
|
242
|
+
);
|
|
243
|
+
const riskDrifted = Boolean(pinned.risk && t.risk && pinned.risk !== t.risk);
|
|
244
|
+
const pinnedGround = JSON.stringify(Array.isArray(pinned.ground) ? [...pinned.ground].sort() : []);
|
|
245
|
+
const actualGround = JSON.stringify(Array.isArray(t.ground) ? [...t.ground].sort() : []);
|
|
246
|
+
const groundDrifted = Boolean(Array.isArray(pinned.ground) && pinned.ground.length && pinnedGround !== actualGround);
|
|
247
|
+
if (pinned.schemaHash !== schemaHash || pinned.descHash !== descHash || cmdDrifted || riskDrifted || groundDrifted) {
|
|
248
|
+
quarantined.push({
|
|
249
|
+
...enriched,
|
|
250
|
+
lockStatus: 'quarantined_drift',
|
|
251
|
+
reason: cmdDrifted
|
|
252
|
+
? 'mcp_server_command_drifted_asi04'
|
|
253
|
+
: (riskDrifted || groundDrifted ? 'mcp_governance_metadata_drifted_asi04' : 'mcp_schema_or_description_mutated_asi04'),
|
|
254
|
+
expectedSchemaHash: pinned.schemaHash,
|
|
255
|
+
expectedDescHash: pinned.descHash,
|
|
256
|
+
expectedCmdHash: pinned.cmdHash || null,
|
|
257
|
+
});
|
|
258
|
+
} else {
|
|
259
|
+
approved.push({
|
|
260
|
+
...enriched,
|
|
261
|
+
shortDescription: pinned.short_description || enriched.shortDescription || null,
|
|
262
|
+
lockStatus: 'verified',
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
if (dirty) saveMcpLock(cwd, lock);
|
|
268
|
+
return { approved, quarantined, lockPath: mcpLockPath(cwd) };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export function approveMcpLock(cwd = process.cwd(), toolsToApprove = [], { pinnedBy = 'operator' } = {}) {
|
|
272
|
+
const lock = loadMcpLock(cwd);
|
|
273
|
+
let count = 0;
|
|
274
|
+
for (const t of toolsToApprove || []) {
|
|
275
|
+
const key = t.fullName || `mcp.${t.server}.${t.name}`;
|
|
276
|
+
lock.tools[key] = {
|
|
277
|
+
server: t.server,
|
|
278
|
+
cmdHash: t.cmdHash || null,
|
|
279
|
+
tool: t.name,
|
|
280
|
+
schemaHash: t.schemaHash || computeSchemaHash({ name: key, description: t.description, parameters: t.parameters }),
|
|
281
|
+
descHash: t.descHash || computeDescHash(t.description || ''),
|
|
282
|
+
risk: t.risk || null,
|
|
283
|
+
ground: Array.isArray(t.ground) ? t.ground : [],
|
|
284
|
+
short_description: t.shortDescription || null,
|
|
285
|
+
pinnedBy,
|
|
286
|
+
pinnedAt: new Date().toISOString(),
|
|
287
|
+
};
|
|
288
|
+
count++;
|
|
289
|
+
}
|
|
290
|
+
const lockFile = saveMcpLock(cwd, lock);
|
|
291
|
+
return { ok: true, approved: count, lockPath: lockFile };
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// ── Transport 1: Zero-Dep MCP stdio JSON-RPC 2.0 Client ───────────────────────
|
|
295
|
+
export function createMcpStdioClient({
|
|
296
|
+
name = 'mcp',
|
|
297
|
+
command,
|
|
298
|
+
args = [],
|
|
299
|
+
cwd = process.cwd(),
|
|
300
|
+
env = {},
|
|
301
|
+
allowEnv = null,
|
|
302
|
+
baseEnv = process.env,
|
|
303
|
+
timeoutMs = 30_000,
|
|
304
|
+
onToolsChanged = null,
|
|
305
|
+
clientInfo = { name: 'scroll-mcp-client', version: '2.5.0' },
|
|
306
|
+
} = {}) {
|
|
307
|
+
if (!command) throw new Error(`createMcpStdioClient(${name}): command is required`);
|
|
308
|
+
let proc = null;
|
|
309
|
+
let rl = null;
|
|
310
|
+
let connected = false;
|
|
311
|
+
let closing = false;
|
|
312
|
+
let nextId = 1;
|
|
313
|
+
let serverInfo = null;
|
|
314
|
+
const pending = new Map();
|
|
315
|
+
|
|
316
|
+
function rejectPending(err) {
|
|
317
|
+
for (const [, p] of pending) {
|
|
318
|
+
clearTimeout(p.timer);
|
|
319
|
+
p.reject(err);
|
|
320
|
+
}
|
|
321
|
+
pending.clear();
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function sendRaw(obj) {
|
|
325
|
+
if (!proc || !proc.stdin || proc.stdin.destroyed) {
|
|
326
|
+
throw new Error(`mcp_not_connected:${name}`);
|
|
327
|
+
}
|
|
328
|
+
proc.stdin.write(JSON.stringify(obj) + '\n');
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function request(method, params = {}, { timeoutMs: reqTimeout = timeoutMs, signal = null } = {}) {
|
|
332
|
+
return new Promise((resolve, reject) => {
|
|
333
|
+
if (signal?.aborted) {
|
|
334
|
+
reject(new Error(`mcp_aborted:${name}:${method}`));
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
const id = nextId++;
|
|
338
|
+
const onAbort = () => {
|
|
339
|
+
if (pending.has(id)) {
|
|
340
|
+
pending.delete(id);
|
|
341
|
+
clearTimeout(timer);
|
|
342
|
+
reject(new Error(`mcp_aborted:${name}:${method}`));
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
const timer = setTimeout(() => {
|
|
346
|
+
if (pending.has(id)) {
|
|
347
|
+
pending.delete(id);
|
|
348
|
+
if (signal) signal.removeEventListener('abort', onAbort);
|
|
349
|
+
reject(new Error(`mcp_timeout:${name}:${method}:${reqTimeout}ms`));
|
|
350
|
+
}
|
|
351
|
+
}, reqTimeout);
|
|
352
|
+
if (signal) signal.addEventListener('abort', onAbort, { once: true });
|
|
353
|
+
pending.set(id, {
|
|
354
|
+
resolve: (v) => { if (signal) signal.removeEventListener('abort', onAbort); resolve(v); },
|
|
355
|
+
reject: (e) => { if (signal) signal.removeEventListener('abort', onAbort); reject(e); },
|
|
356
|
+
timer,
|
|
357
|
+
});
|
|
358
|
+
try {
|
|
359
|
+
sendRaw({ jsonrpc: '2.0', id, method, params });
|
|
360
|
+
} catch (err) {
|
|
361
|
+
pending.delete(id);
|
|
362
|
+
clearTimeout(timer);
|
|
363
|
+
if (signal) signal.removeEventListener('abort', onAbort);
|
|
364
|
+
reject(err);
|
|
365
|
+
}
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function notify(method, params = {}) {
|
|
370
|
+
sendRaw({ jsonrpc: '2.0', method, params });
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
async function connect() {
|
|
374
|
+
if (connected && proc && proc.exitCode === null) return serverInfo;
|
|
375
|
+
closing = false;
|
|
376
|
+
// Sanitized env: NEVER inherit ambient OPENAI_API_KEY / ANTHROPIC_API_KEY / bot tokens!
|
|
377
|
+
const sanitizedEnv = buildSanitizedEnv({
|
|
378
|
+
allowEnv: allowEnv || undefined,
|
|
379
|
+
extraEnv: env,
|
|
380
|
+
baseEnv,
|
|
381
|
+
});
|
|
382
|
+
proc = spawn(command, args, {
|
|
383
|
+
cwd,
|
|
384
|
+
env: sanitizedEnv,
|
|
385
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
386
|
+
});
|
|
387
|
+
// Drain stderr into a bounded ring buffer so verbose MCP servers NEVER deadlock on full 64KB OS pipe
|
|
388
|
+
let stderrTail = '';
|
|
389
|
+
proc.stderr?.on('data', (chunk) => {
|
|
390
|
+
stderrTail += chunk.toString('utf8');
|
|
391
|
+
if (stderrTail.length > 16_384) stderrTail = stderrTail.slice(-16_384);
|
|
392
|
+
});
|
|
393
|
+
// Prevent unhandled EPIPE error event from crashing the host when child exits mid-write
|
|
394
|
+
proc.stdin?.on('error', (err) => {
|
|
395
|
+
connected = false;
|
|
396
|
+
if (!closing) rejectPending(err);
|
|
397
|
+
});
|
|
398
|
+
rl = readline.createInterface({ input: proc.stdout });
|
|
399
|
+
rl.on('line', (line) => {
|
|
400
|
+
const trimmed = line.trim();
|
|
401
|
+
if (!trimmed.startsWith('{')) return;
|
|
402
|
+
let msg;
|
|
403
|
+
try { msg = JSON.parse(trimmed); } catch { return; }
|
|
404
|
+
// Distinguish JSON-RPC response (id present, NO method) from server-initiated request (id AND method)
|
|
405
|
+
if (msg.id !== undefined && !msg.method && pending.has(msg.id)) {
|
|
406
|
+
const entry = pending.get(msg.id);
|
|
407
|
+
pending.delete(msg.id);
|
|
408
|
+
clearTimeout(entry.timer);
|
|
409
|
+
if (msg.error) {
|
|
410
|
+
const e = new Error(msg.error.message || JSON.stringify(msg.error));
|
|
411
|
+
e.code = msg.error.code;
|
|
412
|
+
entry.reject(e);
|
|
413
|
+
} else {
|
|
414
|
+
entry.resolve(msg.result);
|
|
415
|
+
}
|
|
416
|
+
} else if (msg.method === 'notifications/tools/list_changed' && typeof onToolsChanged === 'function') {
|
|
417
|
+
try { onToolsChanged(name); } catch { /* isolate callback */ }
|
|
418
|
+
}
|
|
419
|
+
});
|
|
420
|
+
proc.once('exit', (code, sig) => {
|
|
421
|
+
connected = false;
|
|
422
|
+
if (rl) { try { rl.close(); } catch { /* ignore */ } rl = null; }
|
|
423
|
+
proc = null;
|
|
424
|
+
if (!closing) rejectPending(new Error(`mcp_server_exited:${name}:${code ?? sig}`));
|
|
425
|
+
});
|
|
426
|
+
proc.once('error', (err) => {
|
|
427
|
+
connected = false;
|
|
428
|
+
rejectPending(err);
|
|
429
|
+
});
|
|
430
|
+
try {
|
|
431
|
+
const res = await request('initialize', {
|
|
432
|
+
protocolVersion: '2025-03-26',
|
|
433
|
+
capabilities: {},
|
|
434
|
+
clientInfo,
|
|
435
|
+
});
|
|
436
|
+
notify('notifications/initialized', {});
|
|
437
|
+
connected = true;
|
|
438
|
+
serverInfo = res;
|
|
439
|
+
return res;
|
|
440
|
+
} catch (err) {
|
|
441
|
+
// Never leak orphan child processes when initialize fails or times out!
|
|
442
|
+
closing = true;
|
|
443
|
+
connected = false;
|
|
444
|
+
if (rl) { try { rl.close(); } catch { /* ignore */ } rl = null; }
|
|
445
|
+
if (proc && proc.exitCode === null) {
|
|
446
|
+
try { proc.kill('SIGKILL'); } catch { /* ignore */ }
|
|
447
|
+
}
|
|
448
|
+
proc = null;
|
|
449
|
+
rejectPending(err);
|
|
450
|
+
throw err;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
async function listTools() {
|
|
455
|
+
if (!connected) await connect();
|
|
456
|
+
const out = [];
|
|
457
|
+
let cursor = undefined;
|
|
458
|
+
for (let page = 0; page < 20; page++) {
|
|
459
|
+
const res = await request('tools/list', cursor ? { cursor } : {});
|
|
460
|
+
if (Array.isArray(res?.tools)) out.push(...res.tools);
|
|
461
|
+
cursor = res?.nextCursor || null;
|
|
462
|
+
if (!cursor) break;
|
|
463
|
+
}
|
|
464
|
+
return out;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
async function callTool(toolName, argsObj = {}, { timeoutMs: callTimeout = timeoutMs, signal = null } = {}) {
|
|
468
|
+
if (!connected) await connect();
|
|
469
|
+
const res = await request('tools/call', { name: toolName, arguments: argsObj || {} }, { timeoutMs: callTimeout, signal });
|
|
470
|
+
const content = Array.isArray(res?.content) ? res.content : [];
|
|
471
|
+
const text = content.filter((c) => c && c.type === 'text').map((c) => c.text).join('\n').trim();
|
|
472
|
+
return {
|
|
473
|
+
ok: !res?.isError,
|
|
474
|
+
isError: Boolean(res?.isError),
|
|
475
|
+
text: text || (content.length ? JSON.stringify(content) : JSON.stringify(res ?? {})),
|
|
476
|
+
content,
|
|
477
|
+
raw: res,
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
async function close() {
|
|
482
|
+
closing = true;
|
|
483
|
+
connected = false;
|
|
484
|
+
rejectPending(new Error(`mcp_closed:${name}`));
|
|
485
|
+
if (rl) { try { rl.close(); } catch { /* ignore */ } rl = null; }
|
|
486
|
+
const child = proc;
|
|
487
|
+
proc = null;
|
|
488
|
+
if (!child) return;
|
|
489
|
+
await new Promise((resolve) => {
|
|
490
|
+
let done = false;
|
|
491
|
+
const fin = () => { if (!done) { done = true; resolve(); } };
|
|
492
|
+
child.once('exit', fin);
|
|
493
|
+
try { child.kill('SIGTERM'); } catch { fin(); }
|
|
494
|
+
setTimeout(() => {
|
|
495
|
+
if (!done) {
|
|
496
|
+
try { child.kill('SIGKILL'); } catch { /* ignore */ }
|
|
497
|
+
fin();
|
|
498
|
+
}
|
|
499
|
+
}, 1500).unref();
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
return {
|
|
504
|
+
name,
|
|
505
|
+
transport: 'stdio',
|
|
506
|
+
get connected() { return connected; },
|
|
507
|
+
connect,
|
|
508
|
+
listTools,
|
|
509
|
+
callTool,
|
|
510
|
+
close,
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
// ── Transport 2: Zero-Dep MCP Streamable HTTP Client (MCP 2025-03 / 2025-06) ───
|
|
515
|
+
async function parseMcpHttpResponse(res, expectedId, onNotification, onEventId = null) {
|
|
516
|
+
const ct = res.headers && typeof res.headers.get === 'function' ? (res.headers.get('content-type') || '') : '';
|
|
517
|
+
if (!ct.includes('text/event-stream')) {
|
|
518
|
+
const text = await res.text();
|
|
519
|
+
if (!text.trim()) return null;
|
|
520
|
+
const json = JSON.parse(text);
|
|
521
|
+
if (json.error) {
|
|
522
|
+
const e = new Error(json.error.message || JSON.stringify(json.error));
|
|
523
|
+
e.code = json.error.code;
|
|
524
|
+
throw e;
|
|
525
|
+
}
|
|
526
|
+
return json.result;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
// Proper SSE framing (`\n\n` event boundaries, multi-line `data:`, `id:` tracking, EOF flush)
|
|
530
|
+
const raw = res.body && typeof res.body.getReader === 'function'
|
|
531
|
+
? await (async () => {
|
|
532
|
+
const reader = res.body.getReader();
|
|
533
|
+
const decoder = new TextDecoder();
|
|
534
|
+
let acc = '';
|
|
535
|
+
while (true) {
|
|
536
|
+
const { done, value } = await reader.read();
|
|
537
|
+
if (done) break;
|
|
538
|
+
acc += decoder.decode(value, { stream: true });
|
|
539
|
+
}
|
|
540
|
+
acc += decoder.decode();
|
|
541
|
+
return acc;
|
|
542
|
+
})()
|
|
543
|
+
: await res.text();
|
|
544
|
+
|
|
545
|
+
let matchedResult = undefined;
|
|
546
|
+
const normalized = String(raw || '').replace(/\r\n/g, '\n');
|
|
547
|
+
const blocks = normalized.split('\n\n');
|
|
548
|
+
for (const block of blocks) {
|
|
549
|
+
if (!block.trim()) continue;
|
|
550
|
+
const dataLines = [];
|
|
551
|
+
for (const line of block.split('\n')) {
|
|
552
|
+
if (line.startsWith('id:')) {
|
|
553
|
+
const evId = line.slice(3).trim();
|
|
554
|
+
if (evId && typeof onEventId === 'function') onEventId(evId);
|
|
555
|
+
} else if (line.startsWith('data:')) {
|
|
556
|
+
dataLines.push(line.slice(5).replace(/^ /, ''));
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
const payload = dataLines.join('\n').trim();
|
|
560
|
+
if (!payload || payload === '[DONE]') continue;
|
|
561
|
+
let msg;
|
|
562
|
+
try { msg = JSON.parse(payload); } catch { continue; }
|
|
563
|
+
if (msg.method && msg.id === undefined) {
|
|
564
|
+
if (typeof onNotification === 'function') onNotification(msg);
|
|
565
|
+
continue;
|
|
566
|
+
}
|
|
567
|
+
// Ignore server-initiated requests (both `id` AND `method`) when waiting for our RPC response
|
|
568
|
+
if (msg.method && msg.id !== undefined) {
|
|
569
|
+
continue;
|
|
570
|
+
}
|
|
571
|
+
if (expectedId === undefined || msg.id === expectedId) {
|
|
572
|
+
if (msg.error) {
|
|
573
|
+
const e = new Error(msg.error.message || JSON.stringify(msg.error));
|
|
574
|
+
e.code = msg.error.code;
|
|
575
|
+
throw e;
|
|
576
|
+
}
|
|
577
|
+
matchedResult = msg.result;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
return matchedResult;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
export function createMcpHttpClient({
|
|
584
|
+
name = 'mcp-http',
|
|
585
|
+
url,
|
|
586
|
+
headers = {},
|
|
587
|
+
timeoutMs = 30_000,
|
|
588
|
+
fetchImpl = globalThis.fetch,
|
|
589
|
+
onToolsChanged = null,
|
|
590
|
+
clientInfo = { name: 'scroll-mcp-client', version: '2.5.0' },
|
|
591
|
+
} = {}) {
|
|
592
|
+
if (!url) throw new Error(`createMcpHttpClient(${name}): url is required`);
|
|
593
|
+
const safeUrl = assertSafeMcpHttpUrl(url);
|
|
594
|
+
let sessionId = null;
|
|
595
|
+
let negotiatedProtocol = SUPPORTED_MCP_PROTOCOLS[1]; // default 2025-03-26
|
|
596
|
+
let lastEventId = null;
|
|
597
|
+
let connected = false;
|
|
598
|
+
let nextId = 1;
|
|
599
|
+
let serverInfo = null;
|
|
600
|
+
|
|
601
|
+
async function rpc(method, params = {}, { isNotification = false, timeoutMs: reqTimeout = timeoutMs, signal = null, allowReinit = true } = {}) {
|
|
602
|
+
const id = isNotification ? undefined : nextId++;
|
|
603
|
+
const body = isNotification
|
|
604
|
+
? { jsonrpc: '2.0', method, params }
|
|
605
|
+
: { jsonrpc: '2.0', id, method, params };
|
|
606
|
+
const reqHeaders = {
|
|
607
|
+
'Content-Type': 'application/json',
|
|
608
|
+
Accept: 'application/json, text/event-stream',
|
|
609
|
+
'Mcp-Protocol-Version': negotiatedProtocol,
|
|
610
|
+
...headers,
|
|
611
|
+
};
|
|
612
|
+
if (sessionId) reqHeaders['Mcp-Session-Id'] = sessionId;
|
|
613
|
+
if (lastEventId) reqHeaders['Last-Event-ID'] = lastEventId;
|
|
614
|
+
|
|
615
|
+
const ctrl = new AbortController();
|
|
616
|
+
const timer = setTimeout(() => ctrl.abort(), reqTimeout);
|
|
617
|
+
const onExtAbort = () => ctrl.abort();
|
|
618
|
+
if (signal) {
|
|
619
|
+
if (signal.aborted) ctrl.abort();
|
|
620
|
+
else signal.addEventListener('abort', onExtAbort, { once: true });
|
|
621
|
+
}
|
|
622
|
+
try {
|
|
623
|
+
const res = await fetchImpl(safeUrl, {
|
|
624
|
+
method: 'POST',
|
|
625
|
+
headers: reqHeaders,
|
|
626
|
+
body: JSON.stringify(body),
|
|
627
|
+
signal: ctrl.signal,
|
|
628
|
+
});
|
|
629
|
+
|
|
630
|
+
// Streamable HTTP stale session recovery: HTTP 404 -> drop Mcp-Session-Id and re-initialize once
|
|
631
|
+
if (res.status === 404 && allowReinit && sessionId && method !== 'initialize') {
|
|
632
|
+
sessionId = null;
|
|
633
|
+
connected = false;
|
|
634
|
+
await connect();
|
|
635
|
+
return rpc(method, params, { isNotification, timeoutMs: reqTimeout, signal, allowReinit: false });
|
|
636
|
+
}
|
|
637
|
+
if (!res.ok) {
|
|
638
|
+
const errText = await res.text().catch(() => '');
|
|
639
|
+
const err = new Error(`mcp_http_${res.status}:${name}:${errText.slice(0, 200)}`);
|
|
640
|
+
err.status = res.status;
|
|
641
|
+
throw err;
|
|
642
|
+
}
|
|
643
|
+
const newSid = res.headers && typeof res.headers.get === 'function'
|
|
644
|
+
? (res.headers.get('mcp-session-id') || res.headers.get('Mcp-Session-Id'))
|
|
645
|
+
: null;
|
|
646
|
+
if (newSid) sessionId = newSid;
|
|
647
|
+
if (isNotification || res.status === 202) return null;
|
|
648
|
+
|
|
649
|
+
return await parseMcpHttpResponse(
|
|
650
|
+
res,
|
|
651
|
+
id,
|
|
652
|
+
(notif) => {
|
|
653
|
+
if (notif.method === 'notifications/tools/list_changed' && typeof onToolsChanged === 'function') {
|
|
654
|
+
try { onToolsChanged(name); } catch { /* ignore */ }
|
|
655
|
+
}
|
|
656
|
+
},
|
|
657
|
+
(evId) => { lastEventId = evId; },
|
|
658
|
+
);
|
|
659
|
+
} finally {
|
|
660
|
+
clearTimeout(timer);
|
|
661
|
+
if (signal) signal.removeEventListener('abort', onExtAbort);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
async function connect() {
|
|
666
|
+
if (connected) return serverInfo;
|
|
667
|
+
const res = await rpc('initialize', {
|
|
668
|
+
protocolVersion: negotiatedProtocol,
|
|
669
|
+
capabilities: {},
|
|
670
|
+
clientInfo,
|
|
671
|
+
}, { allowReinit: false });
|
|
672
|
+
if (res && typeof res.protocolVersion === 'string') {
|
|
673
|
+
if (!SUPPORTED_MCP_PROTOCOLS.includes(res.protocolVersion)) {
|
|
674
|
+
// Keep negotiated version if server speaks a newer compatible 2025-* revision; reject obviously invalid
|
|
675
|
+
if (!/^202[4-9]-\d{2}-\d{2}$/.test(res.protocolVersion)) {
|
|
676
|
+
throw new Error(`mcp_unsupported_protocol_version:${name}:${res.protocolVersion}`);
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
negotiatedProtocol = res.protocolVersion;
|
|
680
|
+
}
|
|
681
|
+
await rpc('notifications/initialized', {}, { isNotification: true, allowReinit: false }).catch(() => {});
|
|
682
|
+
connected = true;
|
|
683
|
+
serverInfo = res;
|
|
684
|
+
return res;
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
async function listTools() {
|
|
688
|
+
if (!connected) await connect();
|
|
689
|
+
const out = [];
|
|
690
|
+
let cursor = undefined;
|
|
691
|
+
for (let page = 0; page < 20; page++) {
|
|
692
|
+
const res = await rpc('tools/list', cursor ? { cursor } : {});
|
|
693
|
+
if (Array.isArray(res?.tools)) out.push(...res.tools);
|
|
694
|
+
cursor = res?.nextCursor || null;
|
|
695
|
+
if (!cursor) break;
|
|
696
|
+
}
|
|
697
|
+
return out;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
async function callTool(toolName, argsObj = {}, { timeoutMs: callTimeout = timeoutMs, signal = null } = {}) {
|
|
701
|
+
if (!connected) await connect();
|
|
702
|
+
const res = await rpc('tools/call', { name: toolName, arguments: argsObj || {} }, { timeoutMs: callTimeout, signal });
|
|
703
|
+
const content = Array.isArray(res?.content) ? res.content : [];
|
|
704
|
+
const text = content.filter((c) => c && c.type === 'text').map((c) => c.text).join('\n').trim();
|
|
705
|
+
return {
|
|
706
|
+
ok: !res?.isError,
|
|
707
|
+
isError: Boolean(res?.isError),
|
|
708
|
+
text: text || (content.length ? JSON.stringify(content) : JSON.stringify(res ?? {})),
|
|
709
|
+
content,
|
|
710
|
+
raw: res,
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
async function close() {
|
|
715
|
+
const sid = sessionId;
|
|
716
|
+
connected = false;
|
|
717
|
+
sessionId = null;
|
|
718
|
+
// Streamable HTTP session termination (best-effort DELETE per MCP spec)
|
|
719
|
+
if (sid) {
|
|
720
|
+
try {
|
|
721
|
+
await fetchImpl(safeUrl, {
|
|
722
|
+
method: 'DELETE',
|
|
723
|
+
headers: { 'Mcp-Session-Id': sid, 'Mcp-Protocol-Version': negotiatedProtocol, ...headers },
|
|
724
|
+
});
|
|
725
|
+
} catch { /* ignore best-effort session termination */ }
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
return {
|
|
730
|
+
name,
|
|
731
|
+
transport: 'http',
|
|
732
|
+
get connected() { return connected; },
|
|
733
|
+
get sessionId() { return sessionId; },
|
|
734
|
+
get protocolVersion() { return negotiatedProtocol; },
|
|
735
|
+
connect,
|
|
736
|
+
listTools,
|
|
737
|
+
callTool,
|
|
738
|
+
close,
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
// ── Multi-Server MCP Manager (Fault-Isolated + TOFU Lockfile Pinning ON by default) ──
|
|
743
|
+
export function createMcpManager({
|
|
744
|
+
cwd = process.cwd(),
|
|
745
|
+
agentDir = null,
|
|
746
|
+
env = process.env,
|
|
747
|
+
vault = null,
|
|
748
|
+
failClosedVault = true,
|
|
749
|
+
isolateConfigErrors = true,
|
|
750
|
+
timeoutMs = 30_000,
|
|
751
|
+
fetchImpl = globalThis.fetch,
|
|
752
|
+
enforceLock = true,
|
|
753
|
+
autoPinLock = true,
|
|
754
|
+
onToolsChanged = null,
|
|
755
|
+
} = {}) {
|
|
756
|
+
const configErrors = [];
|
|
757
|
+
const configs = loadMcpConfig({
|
|
758
|
+
cwd,
|
|
759
|
+
agentDir,
|
|
760
|
+
env,
|
|
761
|
+
vault,
|
|
762
|
+
failClosed: failClosedVault,
|
|
763
|
+
isolateErrors: isolateConfigErrors,
|
|
764
|
+
onServerError: (e) => configErrors.push(e),
|
|
765
|
+
});
|
|
766
|
+
const clients = new Map();
|
|
767
|
+
const failedServers = [...configErrors];
|
|
768
|
+
let quarantinedTools = [];
|
|
769
|
+
let quarantinedKeySet = new Set();
|
|
770
|
+
let approvedKeySet = new Set();
|
|
771
|
+
let lockVerifiedOnce = false;
|
|
772
|
+
|
|
773
|
+
async function refreshServer(name) {
|
|
774
|
+
const entry = clients.get(name);
|
|
775
|
+
if (!entry) return null;
|
|
776
|
+
const tools = await entry.client.listTools();
|
|
777
|
+
entry.tools = tools;
|
|
778
|
+
// Re-verify lockfile immediately on `tools/list_changed` so mid-session rug-pull deltas are quarantined!
|
|
779
|
+
if (enforceLock) {
|
|
780
|
+
listDiscoveredTools();
|
|
781
|
+
}
|
|
782
|
+
if (typeof onToolsChanged === 'function') {
|
|
783
|
+
try { onToolsChanged({ server: name, count: tools.length, quarantined: quarantinedTools.length }); } catch { /* ignore */ }
|
|
784
|
+
}
|
|
785
|
+
return tools;
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
async function connectOne(name, cfg) {
|
|
789
|
+
// R2-P0-2: Verify pinned server `cmdHash` BEFORE spawning any stdio child process or connecting to HTTP endpoint!
|
|
790
|
+
if (enforceLock) {
|
|
791
|
+
const pre = verifyServerConfigAgainstLock(name, cfg, { cwd });
|
|
792
|
+
if (!pre.ok) {
|
|
793
|
+
throw new Error(`${pre.reason}:${name}`);
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
if (cfg.transport === 'stdio') {
|
|
797
|
+
if (!cfg.command) throw new Error(`mcp_stdio_missing_command:${name}`);
|
|
798
|
+
const client = createMcpStdioClient({
|
|
799
|
+
name,
|
|
800
|
+
command: cfg.command,
|
|
801
|
+
args: cfg.args,
|
|
802
|
+
cwd: cfg.cwd,
|
|
803
|
+
env: cfg.env,
|
|
804
|
+
allowEnv: cfg.allowEnv,
|
|
805
|
+
baseEnv: env,
|
|
806
|
+
timeoutMs,
|
|
807
|
+
onToolsChanged: () => { refreshServer(name).catch(() => {}); },
|
|
808
|
+
});
|
|
809
|
+
await client.connect();
|
|
810
|
+
const tools = await client.listTools();
|
|
811
|
+
clients.set(name, { client, cfg, tools });
|
|
812
|
+
return { server: name, transport: 'stdio', tools: tools.map((t) => t.name) };
|
|
813
|
+
}
|
|
814
|
+
if (cfg.transport === 'http') {
|
|
815
|
+
if (!cfg.url) throw new Error(`mcp_http_missing_url:${name}`);
|
|
816
|
+
const client = createMcpHttpClient({
|
|
817
|
+
name,
|
|
818
|
+
url: cfg.url,
|
|
819
|
+
headers: cfg.headers,
|
|
820
|
+
timeoutMs,
|
|
821
|
+
fetchImpl,
|
|
822
|
+
onToolsChanged: () => { refreshServer(name).catch(() => {}); },
|
|
823
|
+
});
|
|
824
|
+
await client.connect();
|
|
825
|
+
const tools = await client.listTools();
|
|
826
|
+
clients.set(name, { client, cfg, tools });
|
|
827
|
+
return { server: name, transport: 'http', tools: tools.map((t) => t.name) };
|
|
828
|
+
}
|
|
829
|
+
throw new Error(`mcp_unsupported_transport:${name}:${cfg.transport}`);
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
async function connectAll() {
|
|
833
|
+
failedServers.length = 0;
|
|
834
|
+
failedServers.push(...configErrors);
|
|
835
|
+
const entries = Object.entries(configs);
|
|
836
|
+
const settled = await Promise.allSettled(entries.map(([name, cfg]) => connectOne(name, cfg)));
|
|
837
|
+
const summary = [];
|
|
838
|
+
for (let i = 0; i < settled.length; i++) {
|
|
839
|
+
const [name] = entries[i];
|
|
840
|
+
const r = settled[i];
|
|
841
|
+
if (r.status === 'fulfilled') {
|
|
842
|
+
summary.push(r.value);
|
|
843
|
+
} else {
|
|
844
|
+
failedServers.push({ server: name, error: String(r.reason?.message || r.reason) });
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
return summary;
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
function listDiscoveredTools() {
|
|
851
|
+
const raw = [];
|
|
852
|
+
for (const [server, entry] of clients.entries()) {
|
|
853
|
+
for (const t of entry.tools) {
|
|
854
|
+
const meta = entry.cfg.tools?.[t.name] || {};
|
|
855
|
+
raw.push({
|
|
856
|
+
server,
|
|
857
|
+
namespace: `mcp.${server}`,
|
|
858
|
+
cmdHash: entry.cfg.cmdHash,
|
|
859
|
+
name: t.name,
|
|
860
|
+
fullName: `mcp.${server}.${t.name}`,
|
|
861
|
+
description: t.description || `MCP tool ${t.name} from ${server}`,
|
|
862
|
+
shortDescription: meta.short_description || null,
|
|
863
|
+
serverDescription: entry.cfg.description || '',
|
|
864
|
+
parameters: t.inputSchema || { type: 'object', properties: {} },
|
|
865
|
+
risk: meta.risk || null,
|
|
866
|
+
ground: Array.isArray(meta.ground) ? meta.ground : [],
|
|
867
|
+
confirm: meta.confirm || null,
|
|
868
|
+
deferLoading: meta.defer_loading !== undefined ? Boolean(meta.defer_loading) : entry.cfg.deferLoading,
|
|
869
|
+
tags: [...(entry.cfg.tags || []), ...(Array.isArray(meta.tags) ? meta.tags : [])],
|
|
870
|
+
examples: Array.isArray(meta.examples) ? meta.examples : [],
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
if (enforceLock) {
|
|
875
|
+
const res = verifyAndPinTools(raw, { cwd, autoPin: autoPinLock });
|
|
876
|
+
quarantinedTools = res.quarantined;
|
|
877
|
+
quarantinedKeySet = new Set(res.quarantined.map((t) => t.fullName));
|
|
878
|
+
approvedKeySet = new Set(res.approved.map((t) => t.fullName));
|
|
879
|
+
lockVerifiedOnce = true;
|
|
880
|
+
return res.approved;
|
|
881
|
+
}
|
|
882
|
+
quarantinedTools = [];
|
|
883
|
+
quarantinedKeySet = new Set();
|
|
884
|
+
approvedKeySet = new Set(raw.map((t) => t.fullName));
|
|
885
|
+
lockVerifiedOnce = true;
|
|
886
|
+
return raw.map((t) => ({
|
|
887
|
+
...t,
|
|
888
|
+
schemaHash: computeSchemaHash({ name: t.fullName, description: t.description, parameters: t.parameters }),
|
|
889
|
+
descHash: computeDescHash(t.description),
|
|
890
|
+
}));
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
async function callTool(server, toolName, argsObj = {}, opts = {}) {
|
|
894
|
+
const entry = clients.get(server);
|
|
895
|
+
if (!entry) throw new Error(`mcp_server_not_connected:${server}`);
|
|
896
|
+
if (enforceLock) {
|
|
897
|
+
const fullName = `mcp.${server}.${toolName}`;
|
|
898
|
+
if (!lockVerifiedOnce) {
|
|
899
|
+
listDiscoveredTools();
|
|
900
|
+
}
|
|
901
|
+
if (quarantinedKeySet.has(fullName) || !approvedKeySet.has(fullName)) {
|
|
902
|
+
throw new Error(`mcp_tool_quarantined:${fullName}`);
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
return entry.client.callTool(toolName, argsObj, opts);
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
async function closeAll() {
|
|
909
|
+
const closing = [...clients.values()].map((e) => e.client.close().catch(() => {}));
|
|
910
|
+
clients.clear();
|
|
911
|
+
await Promise.all(closing);
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
return {
|
|
915
|
+
configs,
|
|
916
|
+
listConfiguredServers: () => Object.keys(configs),
|
|
917
|
+
connectAll,
|
|
918
|
+
refreshServer,
|
|
919
|
+
listDiscoveredTools,
|
|
920
|
+
listQuarantinedTools: () => [...quarantinedTools],
|
|
921
|
+
getFailedServers: () => [...failedServers],
|
|
922
|
+
getQuarantinedTools: () => [...quarantinedTools],
|
|
923
|
+
callTool,
|
|
924
|
+
closeAll,
|
|
925
|
+
};
|
|
926
|
+
}
|