bare-agent 0.55.0 → 0.57.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/bareagent.context.md +8 -1
- package/bin/cli.js +13 -3
- package/package.json +1 -1
- package/src/mcp-bridge.d.ts +8 -0
- package/src/mcp-bridge.js +97 -16
package/bareagent.context.md
CHANGED
|
@@ -441,7 +441,7 @@ a server that breaks its stdin pipe surfaces as a failed connection, never an un
|
|
|
441
441
|
crash; and a server whose `command` cannot start (ENOENT/EACCES, or a sync `spawn()` refusal such as an empty command or NUL byte) rejects with
|
|
442
442
|
`MCP server "s" failed to start: command "<cmd>" (<code>)`, `context: { spawnError: true, server, code }`
|
|
443
443
|
(`code` = Node error code if a string, else `'ESPAWN'`; command only with control chars escaped, never args/env) — `listServerTools` throws it, `allow` mode puts it in `errors` + `missing`,
|
|
444
|
-
bulk mode in `errors` — instead of crashing the host.
|
|
444
|
+
bulk mode in `errors` — instead of crashing the host. If a `cwd` (bridge-level or the server's own) was in effect and cannot be entered, the message is `MCP server "s" failed to start: working folder could not be used (<code>)` with `context.cwdFailed:true` added (no folder path, no command named); absent otherwise.
|
|
445
445
|
|
|
446
446
|
## Wiring with bareguard
|
|
447
447
|
|
|
@@ -597,6 +597,10 @@ Verified live against a real 0.19 Gate: `gate.check` ALLOWs `shell_run ["ls","/t
|
|
|
597
597
|
| throws | Treated as a deny. The thrown message becomes the reason. Loop continues. |
|
|
598
598
|
| omitted | Allow-all. Useful for development; never in production — that's what bareguard is for. |
|
|
599
599
|
|
|
600
|
+
**Keep provider keys out of MCP servers (`passEnv`, F109).** By default every stdio server is spawned with your full environment, so `DEEPSEEK_API_KEY` etc. are visible to it. Pass `passEnv: ['PATH', 'HOME']` to `createMCPBridge` (or `listServerTools`) and the child gets only those vars plus the server's own `env` (own wins on a clash; its `${VAR}` refs still resolve from your full env, so you can hand one key over deliberately). `[]` = own env only. Applies to every server, every mode. Suggested starting list: PATH, HOME. Measured (fwdloop F111/F111b, Linux, passEnv ['PATH','HOME']): tools/list worked for npx (barebrowse, baremobile), node (litectx) and sh-wrapped servers, and real tool calls worked too (litectx.recall via node; a HEADLESS barebrowse browse); adding DISPLAY, XDG_RUNTIME_DIR, TMPDIR or LANG changed nothing, so PATH + HOME is the measured minimum on Linux. Unmeasured: a headed (windowed) browser, and Windows (suggested: SYSTEMROOT, APPDATA, USERPROFILE, TEMP). Bad shape throws `ValidationError`.
|
|
601
|
+
|
|
602
|
+
**Start folder for MCP servers (`cwd`).** `createMCPBridge({ cwd: '/abs/dir' })` (or `listServerTools`, or `cfg.mcp.cwd` in `--config`) starts every spawned server in that folder; a server's own `cwd` still wins; unset = your process cwd. It applies only at spawn: it is not saved into `.mcp-bridge.json` and does not move config discovery. It must be an absolute path to an existing directory (no `~`, no relative path) or the whole bridge throws `ValidationError` before anything spawns (the value is never echoed in the message).
|
|
603
|
+
|
|
600
604
|
### Per-caller governance with ctx (multi-user, multi-tenant)
|
|
601
605
|
|
|
602
606
|
The policy signature accepts a third arg `ctx` — an opaque blob you pass per-call via `loop.run(msgs, tools, { ctx })`. `wireGate` forwards it as `_ctx` on every `gate.check({ type, args, _ctx })`, and you can branch on it inside bareguard's `humanChannel` callback or via custom primitives.
|
|
@@ -1038,6 +1042,9 @@ const mcp = liteCtxMcpBridgeConfig({ root: './child-mem' }); // own-db isolati
|
|
|
1038
1042
|
// In the spawn child config (bin/cli.js --config): { provider, model, tools, mcp, gate }
|
|
1039
1043
|
// mcp: <the config above> → child's MCPBridge mounts litectx-mcp; tools join BEFORE gating
|
|
1040
1044
|
// cfg.mcp also accepts a directory-confined { bridgePath } pointing at a .mcp-bridge.json on disk.
|
|
1045
|
+
// cfg.mcp.passEnv (optional string[], F109) limits which parent env vars reach the mounted MCP servers
|
|
1046
|
+
// (default: they inherit the child's full env incl. API keys); a bad value exits 1 via the mount error.
|
|
1047
|
+
// cfg.mcp.cwd (optional absolute dir) sets the mounted MCP servers' start folder; a bad value exits 1 the same way.
|
|
1041
1048
|
```
|
|
1042
1049
|
|
|
1043
1050
|
Requires litectx's `litectx-mcp` binary on PATH. Isolation is **physical** (each child a distinct `--root` db) — promotion to the parent is an explicit parent-side `recall`→`remember`, never automatic. See `examples/litectx-mcp-child.mjs`. bareagent imports nothing from litectx; the helper is pure config curation.
|
package/bin/cli.js
CHANGED
|
@@ -75,7 +75,8 @@ async function runConfigMode(cfgPath) {
|
|
|
75
75
|
// its own db) via `cfg.mcp`. Accepts an inline bridge config (`{ servers, ttl }`, as built by
|
|
76
76
|
// `liteCtxMcpBridgeConfig`) or `{ bridgePath }` pointing at one (confined to the config directory,
|
|
77
77
|
// same rule as gate.humanChannel). Mounted tools join the set BEFORE gating, so they traverse the
|
|
78
|
-
// same policy as native tools.
|
|
78
|
+
// same policy as native tools. `cfg.mcp.passEnv` (string[], optional) restricts which parent env
|
|
79
|
+
// vars reach the MCP servers (F109); `cfg.mcp.cwd` (absolute dir) sets the servers' start folder; invalid ⇒ the mount-failure exit below. The server `command` runs unsandboxed — same trust as `cfg.tools`.
|
|
79
80
|
/** @type {{ tools: ToolDef[], close: Function } | null} */
|
|
80
81
|
let mcpBridge = null;
|
|
81
82
|
if (cfg.mcp) {
|
|
@@ -99,19 +100,28 @@ async function runConfigMode(cfgPath) {
|
|
|
99
100
|
process.stderr.write('[cli] cfg.mcp must be an inline bridge config ({ servers }) or { bridgePath }\n');
|
|
100
101
|
process.exit(1);
|
|
101
102
|
}
|
|
103
|
+
let mountFailed = false;
|
|
104
|
+
let mountMsg;
|
|
102
105
|
try {
|
|
103
106
|
mcpBridge = await createMCPBridge({
|
|
104
107
|
bridgePath,
|
|
105
108
|
servers: cfg.mcp.servers ? Object.keys(cfg.mcp.servers) : undefined,
|
|
106
109
|
timeout: cfg.mcp.timeout || 15000,
|
|
110
|
+
...(cfg.mcp.passEnv !== undefined ? { passEnv: cfg.mcp.passEnv } : {}),
|
|
111
|
+
...(cfg.mcp.cwd !== undefined ? { cwd: cfg.mcp.cwd } : {}),
|
|
107
112
|
});
|
|
108
113
|
tools.push(...mcpBridge.tools);
|
|
109
114
|
} catch (err) {
|
|
110
|
-
process.
|
|
111
|
-
|
|
115
|
+
// Exit AFTER the finally: process.exit() inside the catch would skip it and leak the temp file.
|
|
116
|
+
mountFailed = true;
|
|
117
|
+
mountMsg = err.message;
|
|
112
118
|
} finally {
|
|
113
119
|
if (tmpBridge) { try { fs.unlinkSync(tmpBridge); } catch { /* best-effort */ } }
|
|
114
120
|
}
|
|
121
|
+
if (mountFailed) {
|
|
122
|
+
process.stderr.write(`[cli] failed to mount MCP (cfg.mcp): ${mountMsg}\n`);
|
|
123
|
+
process.exit(1);
|
|
124
|
+
}
|
|
115
125
|
}
|
|
116
126
|
|
|
117
127
|
// Bareguard Gate (optional but strongly recommended for spawn children).
|
package/package.json
CHANGED
package/src/mcp-bridge.d.ts
CHANGED
|
@@ -96,6 +96,8 @@ export type RpcClient = {
|
|
|
96
96
|
* server was not found / failed / was rejected) come back in `missing`. `denied` is always `[]`, nothing is
|
|
97
97
|
* written to stdout, and `mcp_invoke` on a listed-but-unsigned name throws `context.denied === true`.
|
|
98
98
|
* Invalid shape throws `ValidationError` (type only, never values).
|
|
99
|
+
* @param {string[]} [opts.passEnv] - Parent env var NAMES to hand to every spawned server. Unset (default) = the child inherits the FULL parent env (all API keys). Set = the child gets ONLY these vars (those present in process.env) plus the server's own `env` (which wins on a name clash; its `${VAR}` refs still resolve from the full process.env). `[]` = own env only. Measured (fwdloop F111/F111b, Linux, passEnv ['PATH','HOME']): tools/list worked for npx (barebrowse, baremobile), node (litectx) and sh-wrapped servers, and real tool calls worked too (litectx.recall via node; a HEADLESS barebrowse browse); adding DISPLAY, XDG_RUNTIME_DIR, TMPDIR or LANG changed nothing, so PATH + HOME is the measured minimum on Linux. Unmeasured: a headed (windowed) browser, and Windows (suggested: SYSTEMROOT, APPDATA, USERPROFILE, TEMP). Bridge-level, one list for all servers. Invalid shape throws `ValidationError` (type only).
|
|
100
|
+
* @param {string} [opts.cwd] - Start folder for every spawned server (sibling of `passEnv`, bridge-level, opt-in). Unset (default) = the child starts in `process.cwd()`, byte-identical to before. A server's own `cwd` wins. Applied ONLY at spawn: never written to `.mcp-bridge.json`, and it does not move discovery (`./.mcp.json`, the default bridge path stay on `process.cwd()`). Validated once, before anything spawns: must be a non-empty ABSOLUTE path to an existing directory (no `~` expansion, no relative path), else `ValidationError` naming the reason only, never the value; this throws for the whole bridge. A folder deleted after validation, or a bad per-server `cwd`, is not validated up front: the server fails to start / lands in `errors`, labelled `working folder could not be used` with `context.cwdFailed:true` (the folder path is never named).
|
|
99
101
|
* @param {string[]} [opts.servers] - Limit to these server names (ignored when `allow` is given).
|
|
100
102
|
* @param {number} [opts.timeout=15000] - Per-server handshake timeout in ms (initialize + tools/list).
|
|
101
103
|
* @param {number} [opts.callTimeout=120000] - Per-invocation timeout in ms for tools/call. Bounds a
|
|
@@ -120,6 +122,8 @@ export function createMCPBridge(opts?: {
|
|
|
120
122
|
configPaths?: string[] | undefined;
|
|
121
123
|
includeProjectConfig?: boolean | undefined;
|
|
122
124
|
allow?: Record<string, string[]> | undefined;
|
|
125
|
+
passEnv?: string[] | undefined;
|
|
126
|
+
cwd?: string | undefined;
|
|
123
127
|
servers?: string[] | undefined;
|
|
124
128
|
timeout?: number | undefined;
|
|
125
129
|
callTimeout?: number | undefined;
|
|
@@ -202,6 +206,8 @@ export function buildMetaTools(tools: ToolDef[], discoveredAt?: string, excluded
|
|
|
202
206
|
* @param {string[]} [opts.configPaths] - Explicit config paths; omitted ⇒ trusted $HOME/IDE defaults.
|
|
203
207
|
* @param {(name: string, def: ServerDef) => boolean | Promise<boolean>} [opts.confirmServer] - Same semantics as createMCPBridge: `=== true` proceeds, a throw denies. Implies includeProjectConfig.
|
|
204
208
|
* @param {boolean} [opts.includeProjectConfig=false] - Also scan `./.mcp.json` during default discovery.
|
|
209
|
+
* @param {string[]} [opts.passEnv] - Same as createMCPBridge: restrict the spawned server's inherited env to these parent var names (unset = full inherit). Bad shape throws `ValidationError`.
|
|
210
|
+
* @param {string} [opts.cwd] - Same as createMCPBridge: start folder for the spawned server (a server's own `cwd` wins). Absolute existing directory, else `ValidationError` (reason only).
|
|
205
211
|
* @param {number} [opts.timeout=15000] - Per-round-trip bound in ms (initialize and each tools/list page).
|
|
206
212
|
* @returns {Promise<Array<{name: string, description: string, annotations?: Record<string, any>}>>}
|
|
207
213
|
* @when you want to list one MCP server's tools and their annotation hints before deciding what to allow — no bridge, no cache file, no tools kept alive
|
|
@@ -214,6 +220,8 @@ export function listServerTools(opts: {
|
|
|
214
220
|
configPaths?: string[] | undefined;
|
|
215
221
|
confirmServer?: ((name: string, def: ServerDef) => boolean | Promise<boolean>) | undefined;
|
|
216
222
|
includeProjectConfig?: boolean | undefined;
|
|
223
|
+
passEnv?: string[] | undefined;
|
|
224
|
+
cwd?: string | undefined;
|
|
217
225
|
timeout?: number | undefined;
|
|
218
226
|
}): Promise<Array<{
|
|
219
227
|
name: string;
|
package/src/mcp-bridge.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
const { spawn } = require('node:child_process');
|
|
4
|
-
const { readFileSync, writeFileSync, existsSync } = require('node:fs');
|
|
5
|
-
const { join } = require('node:path');
|
|
4
|
+
const { readFileSync, writeFileSync, existsSync, statSync, accessSync, constants: fsConstants } = require('node:fs');
|
|
5
|
+
const { join, isAbsolute } = require('node:path');
|
|
6
6
|
const { homedir } = require('node:os');
|
|
7
7
|
const { ToolError, ValidationError, TimeoutError } = require('./errors');
|
|
8
8
|
|
|
@@ -234,28 +234,97 @@ function resolveEnv(env) {
|
|
|
234
234
|
/**
|
|
235
235
|
* Labelled spawn-failure error. Names the command ONLY (args/env can carry tokens); control
|
|
236
236
|
* characters in the command are escaped so a NUL/newline can't corrupt logs. `code` is the Node
|
|
237
|
-
* error code when it is a string, else 'ESPAWN'.
|
|
237
|
+
* error code when it is a string, else 'ESPAWN'. Node reports a bad start folder exactly like a
|
|
238
|
+
* missing command (ENOENT/EACCES/ENOTDIR), so when a `cwd` was in effect and it cannot be entered
|
|
239
|
+
* the label says the working folder is the problem instead (`context.cwdFailed:true`, key absent
|
|
240
|
+
* otherwise); neither the folder path nor the command is named then. The check never throws.
|
|
238
241
|
* @param {string} name
|
|
239
242
|
* @param {any} command
|
|
240
243
|
* @param {any} err
|
|
244
|
+
* @param {string} [cwd] - the start folder in effect for this spawn, if any
|
|
241
245
|
* @returns {ToolError}
|
|
242
246
|
*/
|
|
243
|
-
function spawnFailure(name, command, err) {
|
|
247
|
+
function spawnFailure(name, command, err, cwd) {
|
|
244
248
|
const code = typeof err?.code === 'string' ? err.code : 'ESPAWN';
|
|
249
|
+
if (cwd) {
|
|
250
|
+
let usable = false;
|
|
251
|
+
try { accessSync(cwd, fsConstants.X_OK); usable = statSync(cwd).isDirectory(); } catch { /* unusable */ }
|
|
252
|
+
if (!usable) {
|
|
253
|
+
return new ToolError(`MCP server "${name}" failed to start: working folder could not be used (${code})`, {
|
|
254
|
+
context: { spawnError: true, server: name, code, cwdFailed: true },
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
}
|
|
245
258
|
const shown = String(command).replace(/[\u0000-\u001f\u007f]/g, c => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
|
|
246
259
|
return new ToolError(`MCP server "${name}" failed to start: command "${shown}" (${code})`, {
|
|
247
260
|
context: { spawnError: true, server: name, code },
|
|
248
261
|
});
|
|
249
262
|
}
|
|
250
263
|
|
|
264
|
+
/**
|
|
265
|
+
* Child process env. `passEnv` undefined => full inherit (historic behavior). Otherwise ONLY the
|
|
266
|
+
* named parent vars that exist (own-property) pass through, overlaid by the server's own resolved
|
|
267
|
+
* env (which wins). `${VAR}` in the server's own env was already resolved from the full process.env.
|
|
268
|
+
* @param {string[] | undefined} passEnv
|
|
269
|
+
* @param {Record<string, string>} own
|
|
270
|
+
* @returns {NodeJS.ProcessEnv}
|
|
271
|
+
*/
|
|
272
|
+
function buildChildEnv(passEnv, own) {
|
|
273
|
+
if (passEnv === undefined) return { ...process.env, ...own };
|
|
274
|
+
/** @type {Record<string, string>} */
|
|
275
|
+
const base = {};
|
|
276
|
+
for (const k of passEnv) {
|
|
277
|
+
if (Object.prototype.hasOwnProperty.call(process.env, k)) base[k] = /** @type {string} */ (process.env[k]);
|
|
278
|
+
}
|
|
279
|
+
return { ...base, ...own };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Validate `passEnv`. Messages name the TYPE only — never echo a value.
|
|
284
|
+
* @param {any} passEnv
|
|
285
|
+
* @param {(msg: string) => Error} bad
|
|
286
|
+
* @returns {string[] | undefined}
|
|
287
|
+
*/
|
|
288
|
+
function validatePassEnv(passEnv, bad) {
|
|
289
|
+
if (passEnv === undefined) return undefined;
|
|
290
|
+
if (!Array.isArray(passEnv)) throw bad(`passEnv must be an array of non-empty strings (got ${typeName(passEnv)})`);
|
|
291
|
+
for (const k of passEnv) {
|
|
292
|
+
if (typeof k !== 'string' || k === '') throw bad(`passEnv entries must be non-empty strings (got ${k === '' ? 'empty string' : typeName(k)})`);
|
|
293
|
+
}
|
|
294
|
+
return passEnv;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Validate the bridge-level `cwd` (the child's start folder). Once, up front, before anything
|
|
299
|
+
* spawns. Messages give the reason/type only — never echo the value. No `~` expansion: a relative
|
|
300
|
+
* or `~/x` path is rejected. Any stat failure is the same loud ValidationError.
|
|
301
|
+
* @param {any} cwd
|
|
302
|
+
* @param {(msg: string) => Error} bad
|
|
303
|
+
* @returns {string | undefined}
|
|
304
|
+
*/
|
|
305
|
+
function validateBridgeCwd(cwd, bad) {
|
|
306
|
+
if (cwd === undefined) return undefined;
|
|
307
|
+
if (typeof cwd !== 'string' || cwd === '') {
|
|
308
|
+
throw bad(`cwd must be a non-empty absolute path string (got ${cwd === '' ? 'empty string' : typeName(cwd)})`);
|
|
309
|
+
}
|
|
310
|
+
if (!isAbsolute(cwd)) throw bad('cwd must be an absolute path (no relative path, no ~ expansion)');
|
|
311
|
+
let isDir;
|
|
312
|
+
try { isDir = statSync(cwd).isDirectory(); } catch { throw bad('cwd must be an existing directory (it could not be read)'); }
|
|
313
|
+
if (!isDir) throw bad('cwd must be an existing directory (it is not a directory)');
|
|
314
|
+
return cwd;
|
|
315
|
+
}
|
|
316
|
+
|
|
251
317
|
/**
|
|
252
318
|
* @param {string} name
|
|
253
319
|
* @param {ServerDef} def
|
|
320
|
+
* @param {string[]} [passEnv]
|
|
321
|
+
* @param {string} [bridgeCwd] - bridge-level start folder; the server's own `def.cwd` wins. Resolved here at spawn, never merged into `def` (which is persisted).
|
|
254
322
|
* @returns {RpcClient}
|
|
255
323
|
*/
|
|
256
|
-
function createRpcClient(name, def) {
|
|
257
|
-
const { command, args = [], env
|
|
258
|
-
const
|
|
324
|
+
function createRpcClient(name, def, passEnv, bridgeCwd) {
|
|
325
|
+
const { command, args = [], env } = def;
|
|
326
|
+
const cwd = def.cwd || bridgeCwd;
|
|
327
|
+
const mergedEnv = buildChildEnv(passEnv, resolveEnv(env));
|
|
259
328
|
|
|
260
329
|
/** @type {import('node:child_process').ChildProcessWithoutNullStreams} */
|
|
261
330
|
let child;
|
|
@@ -271,7 +340,7 @@ function createRpcClient(name, def) {
|
|
|
271
340
|
// Dead client: rpc() rejects every call; notify() is a no-op; `child` is a minimal stand-in
|
|
272
341
|
// that killServer() skips (exitCode !== null) — the simplest shape that needs no null-guards
|
|
273
342
|
// in connectAndListTools / killServer / close().
|
|
274
|
-
const dead = spawnFailure(name, command, err);
|
|
343
|
+
const dead = spawnFailure(name, command, err, cwd);
|
|
275
344
|
return {
|
|
276
345
|
rpc: () => Promise.reject(dead),
|
|
277
346
|
notify: () => {},
|
|
@@ -341,7 +410,7 @@ function createRpcClient(name, def) {
|
|
|
341
410
|
// kill() or IPC send on a LIVE child; keep the listener (so it can't crash the host) but do
|
|
342
411
|
// not mark the server failed — a live server's lifecycle belongs to the 'close' handler.
|
|
343
412
|
if (child.pid !== undefined || spawnErr) return;
|
|
344
|
-
spawnErr = spawnFailure(name, command, err);
|
|
413
|
+
spawnErr = spawnFailure(name, command, err, cwd);
|
|
345
414
|
for (const id of [...pending.keys()]) settle(id, false, spawnErr);
|
|
346
415
|
});
|
|
347
416
|
|
|
@@ -517,13 +586,13 @@ const MAX_LIST_PAGES = 100;
|
|
|
517
586
|
* @param {string} name
|
|
518
587
|
* @param {ServerDef} def
|
|
519
588
|
* @param {number} [timeout] - Bound on EACH round-trip (initialize, every tools/list page).
|
|
520
|
-
* @param {{ deadlineMs?: number }} [o] - Optional ONE total wall-clock ceiling over the whole
|
|
589
|
+
* @param {{ deadlineMs?: number, passEnv?: string[], cwd?: string }} [o] - `passEnv`/`cwd`: see createMCPBridge. Optional ONE total wall-clock ceiling over the whole
|
|
521
590
|
* connect+list (internal; used by listServerTools). On trip the child is killed and a labelled
|
|
522
591
|
* TimeoutError rejects. The timer is always cleared.
|
|
523
592
|
* @returns {Promise<{mcpTools: McpTool[], client: RpcClient}>}
|
|
524
593
|
*/
|
|
525
594
|
async function connectAndListTools(name, def, timeout = 15000, o = {}) {
|
|
526
|
-
const client = createRpcClient(name, def);
|
|
595
|
+
const client = createRpcClient(name, def, o.passEnv, o.cwd);
|
|
527
596
|
/** @type {NodeJS.Timeout | undefined} */
|
|
528
597
|
let deadlineTimer;
|
|
529
598
|
|
|
@@ -835,6 +904,8 @@ function validateAllow(allow) {
|
|
|
835
904
|
* @param {boolean} o.includeProjectConfig
|
|
836
905
|
* @param {number} o.timeout
|
|
837
906
|
* @param {number} o.callTimeout
|
|
907
|
+
* @param {string[]} [o.passEnv]
|
|
908
|
+
* @param {string} [o.cwd]
|
|
838
909
|
* @param {(name: string, def: ServerDef) => Promise<boolean>} o.vetServer
|
|
839
910
|
* @param {(specs: Array<{name: string, command: string, args?: string[]}>) => void} o.warnUnvettedSpawn
|
|
840
911
|
*/
|
|
@@ -867,7 +938,7 @@ async function createAllowBridge(allow, o) {
|
|
|
867
938
|
await Promise.all(toConnect.map(async ([name, def]) => {
|
|
868
939
|
try {
|
|
869
940
|
if (!(await o.vetServer(name, def))) return;
|
|
870
|
-
const { mcpTools, client } = await connectAndListTools(name, def, o.timeout);
|
|
941
|
+
const { mcpTools, client } = await connectAndListTools(name, def, o.timeout, { passEnv: o.passEnv, cwd: o.cwd });
|
|
871
942
|
// Track the child BEFORE any processing so close() reaps it even if what follows throws.
|
|
872
943
|
children.push(client.child);
|
|
873
944
|
const signed = new Set(allow.get(name));
|
|
@@ -936,6 +1007,8 @@ async function createAllowBridge(allow, o) {
|
|
|
936
1007
|
* server was not found / failed / was rejected) come back in `missing`. `denied` is always `[]`, nothing is
|
|
937
1008
|
* written to stdout, and `mcp_invoke` on a listed-but-unsigned name throws `context.denied === true`.
|
|
938
1009
|
* Invalid shape throws `ValidationError` (type only, never values).
|
|
1010
|
+
* @param {string[]} [opts.passEnv] - Parent env var NAMES to hand to every spawned server. Unset (default) = the child inherits the FULL parent env (all API keys). Set = the child gets ONLY these vars (those present in process.env) plus the server's own `env` (which wins on a name clash; its `${VAR}` refs still resolve from the full process.env). `[]` = own env only. Measured (fwdloop F111/F111b, Linux, passEnv ['PATH','HOME']): tools/list worked for npx (barebrowse, baremobile), node (litectx) and sh-wrapped servers, and real tool calls worked too (litectx.recall via node; a HEADLESS barebrowse browse); adding DISPLAY, XDG_RUNTIME_DIR, TMPDIR or LANG changed nothing, so PATH + HOME is the measured minimum on Linux. Unmeasured: a headed (windowed) browser, and Windows (suggested: SYSTEMROOT, APPDATA, USERPROFILE, TEMP). Bridge-level, one list for all servers. Invalid shape throws `ValidationError` (type only).
|
|
1011
|
+
* @param {string} [opts.cwd] - Start folder for every spawned server (sibling of `passEnv`, bridge-level, opt-in). Unset (default) = the child starts in `process.cwd()`, byte-identical to before. A server's own `cwd` wins. Applied ONLY at spawn: never written to `.mcp-bridge.json`, and it does not move discovery (`./.mcp.json`, the default bridge path stay on `process.cwd()`). Validated once, before anything spawns: must be a non-empty ABSOLUTE path to an existing directory (no `~` expansion, no relative path), else `ValidationError` naming the reason only, never the value; this throws for the whole bridge. A folder deleted after validation, or a bad per-server `cwd`, is not validated up front: the server fails to start / lands in `errors`, labelled `working folder could not be used` with `context.cwdFailed:true` (the folder path is never named).
|
|
939
1012
|
* @param {string[]} [opts.servers] - Limit to these server names (ignored when `allow` is given).
|
|
940
1013
|
* @param {number} [opts.timeout=15000] - Per-server handshake timeout in ms (initialize + tools/list).
|
|
941
1014
|
* @param {number} [opts.callTimeout=120000] - Per-invocation timeout in ms for tools/call. Bounds a
|
|
@@ -963,6 +1036,10 @@ async function createMCPBridge(opts = {}) {
|
|
|
963
1036
|
'The static allow/deny filter in .mcp-bridge.json is unchanged.'
|
|
964
1037
|
);
|
|
965
1038
|
}
|
|
1039
|
+
const bridgeBad = (/** @type {string} */ msg) =>
|
|
1040
|
+
new ValidationError(`[MCP Bridge] ${msg}`, { context: { lib: 'bare-agent' } });
|
|
1041
|
+
const passEnv = validatePassEnv(opts.passEnv, bridgeBad);
|
|
1042
|
+
const cwd = validateBridgeCwd(opts.cwd, bridgeBad);
|
|
966
1043
|
const bridgePath = opts.bridgePath || DEFAULT_BRIDGE_PATH();
|
|
967
1044
|
const timeout = opts.timeout || 15000;
|
|
968
1045
|
// 0 is a valid explicit "unbounded"; only undefined falls back to the default.
|
|
@@ -979,7 +1056,7 @@ async function createMCPBridge(opts = {}) {
|
|
|
979
1056
|
return createAllowBridge(allow, {
|
|
980
1057
|
configPaths: opts.configPaths,
|
|
981
1058
|
includeProjectConfig: opts.includeProjectConfig === true || !!confirmServer,
|
|
982
|
-
timeout, callTimeout, vetServer, warnUnvettedSpawn,
|
|
1059
|
+
timeout, callTimeout, vetServer, warnUnvettedSpawn, passEnv, cwd,
|
|
983
1060
|
});
|
|
984
1061
|
}
|
|
985
1062
|
|
|
@@ -1038,7 +1115,7 @@ async function createMCPBridge(opts = {}) {
|
|
|
1038
1115
|
// Denied by confirmServer: skip silently — this is the caller's own
|
|
1039
1116
|
// decision, not a connection failure, so it must not land in `errors`.
|
|
1040
1117
|
if (!(await vetServer(name, def))) return;
|
|
1041
|
-
const result = await connectAndListTools(name, def, timeout);
|
|
1118
|
+
const result = await connectAndListTools(name, def, timeout, { passEnv, cwd });
|
|
1042
1119
|
connectResults.set(name, result.client);
|
|
1043
1120
|
freshTools.set(name, result.mcpTools);
|
|
1044
1121
|
} catch (err) {
|
|
@@ -1110,7 +1187,7 @@ async function createMCPBridge(opts = {}) {
|
|
|
1110
1187
|
try {
|
|
1111
1188
|
// Denied by confirmServer: skip silently (the caller's decision, not a failure).
|
|
1112
1189
|
if (!(await vetServer(name, serverConf))) return;
|
|
1113
|
-
const { mcpTools, client } = await connectAndListTools(name, serverConf, timeout);
|
|
1190
|
+
const { mcpTools, client } = await connectAndListTools(name, serverConf, timeout, { passEnv, cwd });
|
|
1114
1191
|
// Track the child BEFORE any processing so close() reaps it even if what follows throws.
|
|
1115
1192
|
children.push(client.child);
|
|
1116
1193
|
|
|
@@ -1182,6 +1259,8 @@ const listBad = (msg) => new ValidationError(`[MCP Bridge] listServerTools: ${ms
|
|
|
1182
1259
|
* @param {string[]} [opts.configPaths] - Explicit config paths; omitted ⇒ trusted $HOME/IDE defaults.
|
|
1183
1260
|
* @param {(name: string, def: ServerDef) => boolean | Promise<boolean>} [opts.confirmServer] - Same semantics as createMCPBridge: `=== true` proceeds, a throw denies. Implies includeProjectConfig.
|
|
1184
1261
|
* @param {boolean} [opts.includeProjectConfig=false] - Also scan `./.mcp.json` during default discovery.
|
|
1262
|
+
* @param {string[]} [opts.passEnv] - Same as createMCPBridge: restrict the spawned server's inherited env to these parent var names (unset = full inherit). Bad shape throws `ValidationError`.
|
|
1263
|
+
* @param {string} [opts.cwd] - Same as createMCPBridge: start folder for the spawned server (a server's own `cwd` wins). Absolute existing directory, else `ValidationError` (reason only).
|
|
1185
1264
|
* @param {number} [opts.timeout=15000] - Per-round-trip bound in ms (initialize and each tools/list page).
|
|
1186
1265
|
* @returns {Promise<Array<{name: string, description: string, annotations?: Record<string, any>}>>}
|
|
1187
1266
|
* @when you want to list one MCP server's tools and their annotation hints before deciding what to allow — no bridge, no cache file, no tools kept alive
|
|
@@ -1194,6 +1273,8 @@ async function listServerTools(opts) {
|
|
|
1194
1273
|
throw listBad(`opts must be an object (got ${typeName(opts)})`);
|
|
1195
1274
|
}
|
|
1196
1275
|
const { server, configPaths, confirmServer, includeProjectConfig, timeout = 15000 } = opts;
|
|
1276
|
+
const passEnv = validatePassEnv(opts.passEnv, listBad);
|
|
1277
|
+
const cwd = validateBridgeCwd(opts.cwd, listBad);
|
|
1197
1278
|
if (typeof server !== 'string' || server === '') {
|
|
1198
1279
|
throw listBad(`server must be a non-empty string (got ${server === '' ? 'empty string' : typeName(server)})`);
|
|
1199
1280
|
}
|
|
@@ -1221,7 +1302,7 @@ async function listServerTools(opts) {
|
|
|
1221
1302
|
throw new ToolError(`MCP server "${server}" was not approved by confirmServer`, { context: { server, denied: true } });
|
|
1222
1303
|
}
|
|
1223
1304
|
|
|
1224
|
-
const { mcpTools, client } = await connectAndListTools(server, def, timeout, { deadlineMs: timeout * LIST_DEADLINE_MULTIPLIER });
|
|
1305
|
+
const { mcpTools, client } = await connectAndListTools(server, def, timeout, { deadlineMs: timeout * LIST_DEADLINE_MULTIPLIER, passEnv, cwd });
|
|
1225
1306
|
try {
|
|
1226
1307
|
return mcpTools.map(t => {
|
|
1227
1308
|
if (t === null || typeof t !== 'object' || typeof t.name !== 'string' || t.name === '') {
|