bare-agent 0.56.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.
@@ -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,7 +597,9 @@ 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, Linux, tools/list only): PATH + HOME were enough for npx (barebrowse, baremobile), node (litectx) and sh-wrapped servers. Unmeasured: real tool calls (a tool that opens a window may also need DISPLAY/XDG_RUNTIME_DIR), TMPDIR/LANG, and Windows (suggested: SYSTEMROOT, APPDATA, USERPROFILE, TEMP). Bad shape throws `ValidationError`.
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).
601
603
 
602
604
  ### Per-caller governance with ctx (multi-user, multi-tenant)
603
605
 
@@ -1042,6 +1044,7 @@ const mcp = liteCtxMcpBridgeConfig({ root: './child-mem' }); // own-db isolati
1042
1044
  // cfg.mcp also accepts a directory-confined { bridgePath } pointing at a .mcp-bridge.json on disk.
1043
1045
  // cfg.mcp.passEnv (optional string[], F109) limits which parent env vars reach the mounted MCP servers
1044
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.
1045
1048
  ```
1046
1049
 
1047
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
@@ -76,7 +76,7 @@ async function runConfigMode(cfgPath) {
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
78
  // same policy as native tools. `cfg.mcp.passEnv` (string[], optional) restricts which parent env
79
- // vars reach the MCP servers (F109); invalid ⇒ the mount-failure exit below. The server `command` runs unsandboxed — same trust as `cfg.tools`.
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`.
80
80
  /** @type {{ tools: ToolDef[], close: Function } | null} */
81
81
  let mcpBridge = null;
82
82
  if (cfg.mcp) {
@@ -100,20 +100,28 @@ async function runConfigMode(cfgPath) {
100
100
  process.stderr.write('[cli] cfg.mcp must be an inline bridge config ({ servers }) or { bridgePath }\n');
101
101
  process.exit(1);
102
102
  }
103
+ let mountFailed = false;
104
+ let mountMsg;
103
105
  try {
104
106
  mcpBridge = await createMCPBridge({
105
107
  bridgePath,
106
108
  servers: cfg.mcp.servers ? Object.keys(cfg.mcp.servers) : undefined,
107
109
  timeout: cfg.mcp.timeout || 15000,
108
110
  ...(cfg.mcp.passEnv !== undefined ? { passEnv: cfg.mcp.passEnv } : {}),
111
+ ...(cfg.mcp.cwd !== undefined ? { cwd: cfg.mcp.cwd } : {}),
109
112
  });
110
113
  tools.push(...mcpBridge.tools);
111
114
  } catch (err) {
112
- process.stderr.write(`[cli] failed to mount MCP (cfg.mcp): ${err.message}\n`);
113
- process.exit(1);
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;
114
118
  } finally {
115
119
  if (tmpBridge) { try { fs.unlinkSync(tmpBridge); } catch { /* best-effort */ } }
116
120
  }
121
+ if (mountFailed) {
122
+ process.stderr.write(`[cli] failed to mount MCP (cfg.mcp): ${mountMsg}\n`);
123
+ process.exit(1);
124
+ }
117
125
  }
118
126
 
119
127
  // Bareguard Gate (optional but strongly recommended for spawn children).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bare-agent",
3
- "version": "0.56.0",
3
+ "version": "0.57.0",
4
4
  "files": [
5
5
  "index.js",
6
6
  "index.d.ts",
@@ -96,7 +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, Linux, tools/list only): PATH + HOME were enough for npx (barebrowse, baremobile), node (litectx) and sh-wrapped servers. Unmeasured: real tool calls (a tool that opens a window may also need DISPLAY/XDG_RUNTIME_DIR), TMPDIR/LANG, and Windows (suggested: SYSTEMROOT, APPDATA, USERPROFILE, TEMP). Bridge-level, one list for all servers. Invalid shape throws `ValidationError` (type only).
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).
100
101
  * @param {string[]} [opts.servers] - Limit to these server names (ignored when `allow` is given).
101
102
  * @param {number} [opts.timeout=15000] - Per-server handshake timeout in ms (initialize + tools/list).
102
103
  * @param {number} [opts.callTimeout=120000] - Per-invocation timeout in ms for tools/call. Bounds a
@@ -122,6 +123,7 @@ export function createMCPBridge(opts?: {
122
123
  includeProjectConfig?: boolean | undefined;
123
124
  allow?: Record<string, string[]> | undefined;
124
125
  passEnv?: string[] | undefined;
126
+ cwd?: string | undefined;
125
127
  servers?: string[] | undefined;
126
128
  timeout?: number | undefined;
127
129
  callTimeout?: number | undefined;
@@ -205,6 +207,7 @@ export function buildMetaTools(tools: ToolDef[], discoveredAt?: string, excluded
205
207
  * @param {(name: string, def: ServerDef) => boolean | Promise<boolean>} [opts.confirmServer] - Same semantics as createMCPBridge: `=== true` proceeds, a throw denies. Implies includeProjectConfig.
206
208
  * @param {boolean} [opts.includeProjectConfig=false] - Also scan `./.mcp.json` during default discovery.
207
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).
208
211
  * @param {number} [opts.timeout=15000] - Per-round-trip bound in ms (initialize and each tools/list page).
209
212
  * @returns {Promise<Array<{name: string, description: string, annotations?: Record<string, any>}>>}
210
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
@@ -218,6 +221,7 @@ export function listServerTools(opts: {
218
221
  confirmServer?: ((name: string, def: ServerDef) => boolean | Promise<boolean>) | undefined;
219
222
  includeProjectConfig?: boolean | undefined;
220
223
  passEnv?: string[] | undefined;
224
+ cwd?: string | undefined;
221
225
  timeout?: number | undefined;
222
226
  }): Promise<Array<{
223
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,14 +234,27 @@ 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 },
@@ -281,14 +294,36 @@ function validatePassEnv(passEnv, bad) {
281
294
  return passEnv;
282
295
  }
283
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
+
284
317
  /**
285
318
  * @param {string} name
286
319
  * @param {ServerDef} def
287
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).
288
322
  * @returns {RpcClient}
289
323
  */
290
- function createRpcClient(name, def, passEnv) {
291
- const { command, args = [], env, cwd } = def;
324
+ function createRpcClient(name, def, passEnv, bridgeCwd) {
325
+ const { command, args = [], env } = def;
326
+ const cwd = def.cwd || bridgeCwd;
292
327
  const mergedEnv = buildChildEnv(passEnv, resolveEnv(env));
293
328
 
294
329
  /** @type {import('node:child_process').ChildProcessWithoutNullStreams} */
@@ -305,7 +340,7 @@ function createRpcClient(name, def, passEnv) {
305
340
  // Dead client: rpc() rejects every call; notify() is a no-op; `child` is a minimal stand-in
306
341
  // that killServer() skips (exitCode !== null) — the simplest shape that needs no null-guards
307
342
  // in connectAndListTools / killServer / close().
308
- const dead = spawnFailure(name, command, err);
343
+ const dead = spawnFailure(name, command, err, cwd);
309
344
  return {
310
345
  rpc: () => Promise.reject(dead),
311
346
  notify: () => {},
@@ -375,7 +410,7 @@ function createRpcClient(name, def, passEnv) {
375
410
  // kill() or IPC send on a LIVE child; keep the listener (so it can't crash the host) but do
376
411
  // not mark the server failed — a live server's lifecycle belongs to the 'close' handler.
377
412
  if (child.pid !== undefined || spawnErr) return;
378
- spawnErr = spawnFailure(name, command, err);
413
+ spawnErr = spawnFailure(name, command, err, cwd);
379
414
  for (const id of [...pending.keys()]) settle(id, false, spawnErr);
380
415
  });
381
416
 
@@ -551,13 +586,13 @@ const MAX_LIST_PAGES = 100;
551
586
  * @param {string} name
552
587
  * @param {ServerDef} def
553
588
  * @param {number} [timeout] - Bound on EACH round-trip (initialize, every tools/list page).
554
- * @param {{ deadlineMs?: number, passEnv?: string[] }} [o] - `passEnv`: see createMCPBridge. 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
555
590
  * connect+list (internal; used by listServerTools). On trip the child is killed and a labelled
556
591
  * TimeoutError rejects. The timer is always cleared.
557
592
  * @returns {Promise<{mcpTools: McpTool[], client: RpcClient}>}
558
593
  */
559
594
  async function connectAndListTools(name, def, timeout = 15000, o = {}) {
560
- const client = createRpcClient(name, def, o.passEnv);
595
+ const client = createRpcClient(name, def, o.passEnv, o.cwd);
561
596
  /** @type {NodeJS.Timeout | undefined} */
562
597
  let deadlineTimer;
563
598
 
@@ -870,6 +905,7 @@ function validateAllow(allow) {
870
905
  * @param {number} o.timeout
871
906
  * @param {number} o.callTimeout
872
907
  * @param {string[]} [o.passEnv]
908
+ * @param {string} [o.cwd]
873
909
  * @param {(name: string, def: ServerDef) => Promise<boolean>} o.vetServer
874
910
  * @param {(specs: Array<{name: string, command: string, args?: string[]}>) => void} o.warnUnvettedSpawn
875
911
  */
@@ -902,7 +938,7 @@ async function createAllowBridge(allow, o) {
902
938
  await Promise.all(toConnect.map(async ([name, def]) => {
903
939
  try {
904
940
  if (!(await o.vetServer(name, def))) return;
905
- const { mcpTools, client } = await connectAndListTools(name, def, o.timeout, { passEnv: o.passEnv });
941
+ const { mcpTools, client } = await connectAndListTools(name, def, o.timeout, { passEnv: o.passEnv, cwd: o.cwd });
906
942
  // Track the child BEFORE any processing so close() reaps it even if what follows throws.
907
943
  children.push(client.child);
908
944
  const signed = new Set(allow.get(name));
@@ -971,7 +1007,8 @@ async function createAllowBridge(allow, o) {
971
1007
  * server was not found / failed / was rejected) come back in `missing`. `denied` is always `[]`, nothing is
972
1008
  * written to stdout, and `mcp_invoke` on a listed-but-unsigned name throws `context.denied === true`.
973
1009
  * Invalid shape throws `ValidationError` (type only, never values).
974
- * @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, Linux, tools/list only): PATH + HOME were enough for npx (barebrowse, baremobile), node (litectx) and sh-wrapped servers. Unmeasured: real tool calls (a tool that opens a window may also need DISPLAY/XDG_RUNTIME_DIR), TMPDIR/LANG, and Windows (suggested: SYSTEMROOT, APPDATA, USERPROFILE, TEMP). Bridge-level, one list for all servers. Invalid shape throws `ValidationError` (type only).
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).
975
1012
  * @param {string[]} [opts.servers] - Limit to these server names (ignored when `allow` is given).
976
1013
  * @param {number} [opts.timeout=15000] - Per-server handshake timeout in ms (initialize + tools/list).
977
1014
  * @param {number} [opts.callTimeout=120000] - Per-invocation timeout in ms for tools/call. Bounds a
@@ -999,8 +1036,10 @@ async function createMCPBridge(opts = {}) {
999
1036
  'The static allow/deny filter in .mcp-bridge.json is unchanged.'
1000
1037
  );
1001
1038
  }
1002
- const passEnv = validatePassEnv(opts.passEnv, (msg) =>
1003
- new ValidationError(`[MCP Bridge] ${msg}`, { context: { lib: 'bare-agent' } }));
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);
1004
1043
  const bridgePath = opts.bridgePath || DEFAULT_BRIDGE_PATH();
1005
1044
  const timeout = opts.timeout || 15000;
1006
1045
  // 0 is a valid explicit "unbounded"; only undefined falls back to the default.
@@ -1017,7 +1056,7 @@ async function createMCPBridge(opts = {}) {
1017
1056
  return createAllowBridge(allow, {
1018
1057
  configPaths: opts.configPaths,
1019
1058
  includeProjectConfig: opts.includeProjectConfig === true || !!confirmServer,
1020
- timeout, callTimeout, vetServer, warnUnvettedSpawn, passEnv,
1059
+ timeout, callTimeout, vetServer, warnUnvettedSpawn, passEnv, cwd,
1021
1060
  });
1022
1061
  }
1023
1062
 
@@ -1076,7 +1115,7 @@ async function createMCPBridge(opts = {}) {
1076
1115
  // Denied by confirmServer: skip silently — this is the caller's own
1077
1116
  // decision, not a connection failure, so it must not land in `errors`.
1078
1117
  if (!(await vetServer(name, def))) return;
1079
- const result = await connectAndListTools(name, def, timeout, { passEnv });
1118
+ const result = await connectAndListTools(name, def, timeout, { passEnv, cwd });
1080
1119
  connectResults.set(name, result.client);
1081
1120
  freshTools.set(name, result.mcpTools);
1082
1121
  } catch (err) {
@@ -1148,7 +1187,7 @@ async function createMCPBridge(opts = {}) {
1148
1187
  try {
1149
1188
  // Denied by confirmServer: skip silently (the caller's decision, not a failure).
1150
1189
  if (!(await vetServer(name, serverConf))) return;
1151
- const { mcpTools, client } = await connectAndListTools(name, serverConf, timeout, { passEnv });
1190
+ const { mcpTools, client } = await connectAndListTools(name, serverConf, timeout, { passEnv, cwd });
1152
1191
  // Track the child BEFORE any processing so close() reaps it even if what follows throws.
1153
1192
  children.push(client.child);
1154
1193
 
@@ -1221,6 +1260,7 @@ const listBad = (msg) => new ValidationError(`[MCP Bridge] listServerTools: ${ms
1221
1260
  * @param {(name: string, def: ServerDef) => boolean | Promise<boolean>} [opts.confirmServer] - Same semantics as createMCPBridge: `=== true` proceeds, a throw denies. Implies includeProjectConfig.
1222
1261
  * @param {boolean} [opts.includeProjectConfig=false] - Also scan `./.mcp.json` during default discovery.
1223
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).
1224
1264
  * @param {number} [opts.timeout=15000] - Per-round-trip bound in ms (initialize and each tools/list page).
1225
1265
  * @returns {Promise<Array<{name: string, description: string, annotations?: Record<string, any>}>>}
1226
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
@@ -1234,6 +1274,7 @@ async function listServerTools(opts) {
1234
1274
  }
1235
1275
  const { server, configPaths, confirmServer, includeProjectConfig, timeout = 15000 } = opts;
1236
1276
  const passEnv = validatePassEnv(opts.passEnv, listBad);
1277
+ const cwd = validateBridgeCwd(opts.cwd, listBad);
1237
1278
  if (typeof server !== 'string' || server === '') {
1238
1279
  throw listBad(`server must be a non-empty string (got ${server === '' ? 'empty string' : typeName(server)})`);
1239
1280
  }
@@ -1261,7 +1302,7 @@ async function listServerTools(opts) {
1261
1302
  throw new ToolError(`MCP server "${server}" was not approved by confirmServer`, { context: { server, denied: true } });
1262
1303
  }
1263
1304
 
1264
- const { mcpTools, client } = await connectAndListTools(server, def, timeout, { deadlineMs: timeout * LIST_DEADLINE_MULTIPLIER, passEnv });
1305
+ const { mcpTools, client } = await connectAndListTools(server, def, timeout, { deadlineMs: timeout * LIST_DEADLINE_MULTIPLIER, passEnv, cwd });
1265
1306
  try {
1266
1307
  return mcpTools.map(t => {
1267
1308
  if (t === null || typeof t !== 'object' || typeof t.name !== 'string' || t.name === '') {