@strixgov/mcp-proxy 0.2.4 → 0.3.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.
Files changed (50) hide show
  1. package/CHANGELOG.md +92 -1
  2. package/README.md +277 -38
  3. package/bin/strix-mcp-proxy.mjs +100 -5
  4. package/examples/controlled-launcher/README.md +33 -0
  5. package/examples/controlled-launcher/acceptance.mjs +337 -0
  6. package/examples/controlled-launcher/agent-client.mjs +18 -0
  7. package/examples/controlled-launcher/approval-relay.mjs +19 -0
  8. package/examples/controlled-launcher/approver.mjs +27 -0
  9. package/examples/controlled-launcher/authorizer.mjs +73 -0
  10. package/examples/controlled-launcher/bridge-client.mjs +8 -0
  11. package/examples/controlled-launcher/destination.mjs +18 -0
  12. package/examples/controlled-launcher/executor.mjs +74 -0
  13. package/examples/controlled-launcher/kernel-authority/acceptance.mjs +627 -0
  14. package/examples/controlled-launcher/kernel-authority/broker.mjs +83 -0
  15. package/examples/controlled-launcher/kernel-authority/derive.mjs +12 -0
  16. package/examples/controlled-launcher/kernel-authority/executor.mjs +105 -0
  17. package/examples/controlled-launcher/kernel-authority/reconcile.mjs +43 -0
  18. package/examples/controlled-launcher/kernel-authority/shim.mjs +38 -0
  19. package/examples/controlled-launcher/kernel-authority/signing-provider.mjs +137 -0
  20. package/examples/controlled-launcher/kernel-authority/strix-approver.mjs +73 -0
  21. package/examples/controlled-launcher/lib.mjs +63 -0
  22. package/examples/controlled-launcher/make-config.mjs +16 -0
  23. package/examples/controlled-launcher/proxy-host.mjs +19 -0
  24. package/examples/controlled-launcher/reconcile.mjs +30 -0
  25. package/examples/controlled-launcher/shim.mjs +32 -0
  26. package/examples/github-reference/README.md +1 -1
  27. package/examples/github-reference/acceptance.mjs +10 -3
  28. package/examples/github-reference/claims-matrix.md +3 -3
  29. package/examples/github-reference/package-lock.json +48 -44
  30. package/examples/github-reference/package.json +4 -4
  31. package/examples/github-reference/reuse-inventory.md +4 -4
  32. package/examples/synthetic-server/proxy-config.json +16 -0
  33. package/examples/synthetic-server/quickstart.mjs +98 -0
  34. package/examples/synthetic-server/server.mjs +54 -0
  35. package/package.json +5 -4
  36. package/src/config.mjs +152 -2
  37. package/src/content-guard.mjs +432 -0
  38. package/src/http-upstream.mjs +431 -0
  39. package/src/index.mjs +11 -2
  40. package/src/proxy.mjs +241 -33
  41. package/src/tool-guard.mjs +183 -0
  42. package/src/types.d.ts +83 -1
  43. package/test/content-guard-hardening.test.mjs +159 -0
  44. package/test/content-guard.test.mjs +387 -0
  45. package/test/http-upstream-config.test.mjs +115 -0
  46. package/test/http-upstream-e2e.test.mjs +279 -0
  47. package/test/http-upstream.test.mjs +304 -0
  48. package/test/synthetic-quickstart.test.mjs +44 -0
  49. package/test/tool-guard.test.mjs +243 -0
  50. package/test/validate-cli.test.mjs +171 -0
package/src/proxy.mjs CHANGED
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Architectural shape:
5
5
  *
6
- * MCP Client ──stdio──▶ [Strix Proxy: server] ──governMCPServer──▶ [client] ──stdio──▶ Upstream MCP Server
6
+ * MCP Client ──stdio──▶ [Strix Proxy: server] ──governMCPServer──▶ [client] ──stdio or HTTP──▶ Upstream MCP Server
7
7
  *
8
8
  * The proxy IS an MCP server (toward the consumer's client) AND an MCP
9
9
  * client (toward the upstream tool). Every callTool entering the proxy
@@ -11,11 +11,13 @@
11
11
  * which applies policy, fires the approval gate when needed, executes
12
12
  * via the upstream client, and emits a signed Ed25519 receipt.
13
13
  *
14
- * Today (v0.1.0) — Mode 1 (Observed) and Mode 2 (Approval-Gated).
14
+ * Shipped: Mode 1 (Observed) and Mode 2 (Approval-Gated). The upstream
15
+ * can be a child process (stdio) or a hosted server (Streamable HTTP,
16
+ * see ./http-upstream.mjs).
15
17
  *
16
- * Designed for Mode 3 upgrade. The downstream-call seam at
17
- * `buildUpstreamIface()` is the single place where Mode 3 enforcement
18
- * will attach in v0.2.0: a future option (`mode: "enforced"`) wraps
18
+ * Designed for Mode 3 upgrade, which has not shipped in any release and
19
+ * carries no date. The downstream-call seam at `buildUpstreamIface()` is
20
+ * the single place where Mode 3 enforcement would attach: a future option (`mode: "enforced"`) wraps
19
21
  * every outbound call with the `execution_authorization_v1` token
20
22
  * mint + transport step from
21
23
  * `docs/architecture/mcp-mode-3-enforcement-v1.md` §6, without
@@ -29,12 +31,17 @@
29
31
  * maximum coverage of the actual MCP-call surface.
30
32
  */
31
33
 
34
+ import fs from "node:fs";
32
35
  import path from "node:path";
33
36
  import os from "node:os";
34
37
  import { governMCPServer } from "@strixgov/mcp-adapter";
35
38
  import { loadOrCreateSigningKey, fileApprover } from "@strixgov/tool-gateway";
36
39
  import { webhookApprover } from "./webhook-approver.mjs";
37
40
  import { createShadowDiscovery } from "./shadow-discovery.mjs";
41
+ import { createHttpUpstreamTransport, redact, UPSTREAM_OUTCOME_UNKNOWN } from "./http-upstream.mjs";
42
+ import { createToolPinStore, createCapabilityResolver, TOOL_DEFINITION_CHANGED } from "./tool-guard.mjs";
43
+ import { createContentGuard } from "./content-guard.mjs";
44
+ import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
38
45
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
39
46
  import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
40
47
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
@@ -49,7 +56,10 @@ import {
49
56
  * (CLI, tests) can shut it down cleanly.
50
57
  *
51
58
  * @param {{
52
- * upstream: { command: string, args?: string[], env?: Record<string, string> },
59
+ * upstream:
60
+ * | { command: string, args?: string[], env?: Record<string, string> }
61
+ * | { url: string, headers?: Record<string, string | { fromEnv: string, prefix?: string }>,
62
+ * allowedOrigins?: string[], allowPrivateNetwork?: boolean, timeoutMs?: number },
53
63
  * serverId?: string,
54
64
  * capabilities?: Array<object>,
55
65
  * policy?: object,
@@ -61,6 +71,12 @@ import {
61
71
  * onReceipt?: (receipt: object) => void,
62
72
  * onAudit?: (event: { kind: string, detail: object }) => void,
63
73
  * shadowDiscovery?: boolean,
74
+ * toolPinning?: "block" | "warn" | "off",
75
+ * repinTools?: boolean,
76
+ * hideDeniedTools?: boolean,
77
+ * rateLimits?: Record<string, { windowMs: number, max: number, perActor?: boolean }>,
78
+ * secretScanning?: false | { arguments?: "block" | "warn" | "off", results?: "redact" | "warn" | "off" },
79
+ * argumentRules?: Record<string, Array<object>>,
64
80
  * transport?: { kind: "stdio" } | { kind: "test", server: object, client: object },
65
81
  * }} opts
66
82
  * @returns {Promise<{
@@ -76,12 +92,25 @@ export async function startProxy(opts) {
76
92
  throw new TypeError("startProxy: opts is required");
77
93
  }
78
94
  const serverId = opts.serverId ?? "proxy";
95
+ // Content guard: credential scanning of arguments and results, and argument
96
+ // rules. Built here so a bad option fails at startup, before anything connects.
97
+ const contentGuard = createContentGuard({
98
+ secretScanning: opts.secretScanning,
99
+ argumentRules: opts.argumentRules,
100
+ });
101
+
79
102
  const transportKind = opts.transport?.kind ?? "stdio";
80
103
  // In real (stdio) mode opts.upstream.command is required; in test mode the
81
104
  // caller supplies a pre-connected upstream client instead.
105
+ // The upstream is either a child process (`command`) or a remote MCP
106
+ // server reached over Streamable HTTP (`url`). Exactly one.
107
+ const upstreamIsHttp = typeof opts.upstream?.url === "string";
82
108
  if (transportKind === "stdio") {
83
- if (!opts.upstream || typeof opts.upstream.command !== "string") {
84
- throw new TypeError("startProxy: opts.upstream.command is required for stdio mode");
109
+ const hasCommand = typeof opts.upstream?.command === "string";
110
+ if (!opts.upstream || hasCommand === upstreamIsHttp) {
111
+ throw new TypeError(
112
+ "startProxy: opts.upstream.command is required for stdio mode, or opts.upstream.url for an HTTP upstream (exactly one)",
113
+ );
85
114
  }
86
115
  }
87
116
 
@@ -148,11 +177,32 @@ export async function startProxy(opts) {
148
177
  ? null
149
178
  : opts.storagePath ?? path.join(os.homedir(), ".strix-mcp-proxy", serverId);
150
179
 
180
+ // Optional append-only JSONL audit log: one line per audit event, readable by any log shipper.
181
+ // Events never carry a credential (the guard scrubs them), so the file needs no extra care beyond 0600.
182
+ if (opts.auditLog) {
183
+ let file;
184
+ if (typeof opts.auditLog === "string") {
185
+ const raw = opts.auditLog;
186
+ file = raw === "~" ? null : /^~[\\/]/.test(raw) ? path.join(os.homedir(), raw.slice(2)) : raw;
187
+ if (file === null || !path.isAbsolute(file)) {
188
+ throw new TypeError("startProxy: auditLog must be true, an absolute file path, or a path starting with ~/ (a relative path would depend on where the client launched the proxy)");
189
+ }
190
+ } else if (resolvedStoragePath) {
191
+ file = path.join(resolvedStoragePath, "audit.jsonl");
192
+ } else {
193
+ throw new TypeError("startProxy: auditLog: true needs a storagePath; pass a file path instead");
194
+ }
195
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
196
+ opts = { ...opts, __auditFile: file };
197
+ }
198
+
151
199
  // ─── 1. Connect to the upstream MCP server ─────────────────────────────────
152
200
  // Test mode lets callers pre-build the upstream client (e.g. with an
153
201
  // InMemoryTransport pair) so the proxy can be exercised end-to-end
154
202
  // without spawning a real subprocess.
155
203
  let upstreamClient;
204
+ let upstreamSecrets = [];
205
+ let upstreamTimeoutMs = null;
156
206
  if (transportKind === "test" && opts.transport.upstreamClient) {
157
207
  upstreamClient = opts.transport.upstreamClient;
158
208
  audit(opts, { kind: "upstream.connected", detail: { command: "(test mode)" } });
@@ -161,17 +211,44 @@ export async function startProxy(opts) {
161
211
  { name: `strix-proxy:${serverId}`, version: "0.1.0" },
162
212
  { capabilities: {} },
163
213
  );
164
- const upstreamTransport = new StdioClientTransport({
165
- command: opts.upstream.command,
166
- args: opts.upstream.args ?? [],
167
- env: resolvedUpstreamEnv ?? process.env,
168
- });
169
- await upstreamClient.connect(upstreamTransport);
170
- audit(opts, { kind: "upstream.connected", detail: { command: opts.upstream.command } });
214
+ if (upstreamIsHttp) {
215
+ // HTTP upstream: header credentials are read from the environment
216
+ // (process env, plus anything upstreamCredentials resolved). The
217
+ // values never enter a receipt, an audit event or an error message.
218
+ const { transport, origin, secrets } = await createHttpUpstreamTransport(opts.upstream, {
219
+ env: { ...process.env, ...(resolvedUpstreamEnv ?? {}) },
220
+ onAudit: (event) => audit(opts, event),
221
+ fetchImpl: opts.upstream.fetchImpl, // programmatic/test seam; not JSON-configurable
222
+ lookup: opts.upstream.lookup, // programmatic/test seam; not JSON-configurable
223
+ });
224
+ upstreamSecrets = secrets;
225
+ upstreamTimeoutMs = opts.upstream.timeoutMs ?? 60_000;
226
+ try {
227
+ await upstreamClient.connect(transport);
228
+ } catch (err) {
229
+ throw new Error(`startProxy: could not connect to HTTP upstream ${origin}: ${redact(err?.message, secrets)}`);
230
+ }
231
+ // The upstream's origin is recorded here, in the unsigned audit stream,
232
+ // and deliberately NOT in any receipt: the receipt and outcome payloads
233
+ // are frozen (ADR-002) and carry no transport field.
234
+ audit(opts, { kind: "upstream.connected", detail: { transport: "http", origin } });
235
+ } else {
236
+ const upstreamTransport = new StdioClientTransport({
237
+ command: opts.upstream.command,
238
+ args: opts.upstream.args ?? [],
239
+ env: resolvedUpstreamEnv ?? process.env,
240
+ });
241
+ await upstreamClient.connect(upstreamTransport);
242
+ audit(opts, { kind: "upstream.connected", detail: { transport: "stdio", command: opts.upstream.command } });
243
+ }
171
244
  }
172
245
 
173
246
  // ─── 2. Build the iface mcp-adapter expects ───────────────────────────────
174
- const upstreamIface = buildUpstreamIface(upstreamClient, serverId);
247
+ const upstreamIface = buildUpstreamIface(upstreamClient, serverId, {
248
+ secrets: upstreamSecrets,
249
+ timeoutMs: upstreamTimeoutMs,
250
+ onAudit: (event) => audit(opts, event),
251
+ });
175
252
 
176
253
  // ─── 3a. Resolve a persistent signing key when storagePath is set ──────────
177
254
  // Without this, governMCPServer falls back to an in-memory ephemeral key
@@ -251,13 +328,50 @@ export async function startProxy(opts) {
251
328
  const governed = governMCPServer(upstreamIface, {
252
329
  serverId,
253
330
  capabilities: opts.capabilities,
254
- policy: opts.policy ?? { default: "DENY" },
331
+ // Rate limits travel inside the policy object: the gateway reads
332
+ // `policy.rateLimits` and ignores a top-level `rateLimits` option, which
333
+ // is what @strixgov/mcp-adapter 0.1.5 passes. (Not part of the policy
334
+ // version hash, so receipts' policyVersion is unchanged by them.)
335
+ policy: opts.rateLimits
336
+ ? { ...(opts.policy ?? { default: "DENY" }), rateLimits: opts.rateLimits }
337
+ : opts.policy ?? { default: "DENY" },
255
338
  approval: resolvedApproval,
256
339
  storagePath: resolvedStoragePath,
257
340
  signingKey: resolvedSigningKey,
258
341
  connectedMode: opts.connectedMode,
259
342
  });
260
343
 
344
+ // ─── 3c'. Tool-definition pinning + discovery filtering (see tool-guard.mjs)
345
+ const toolPins = createToolPinStore({
346
+ mode: opts.toolPinning ?? "block",
347
+ storagePath: resolvedStoragePath,
348
+ repin: opts.repinTools === true,
349
+ onAudit: (event) => audit(opts, event),
350
+ });
351
+ // Opt-in: the existing contract (pinned by test) is that tools/list
352
+ // returns the upstream's tools unreshaped.
353
+ const hideDeniedTools = opts.hideDeniedTools === true;
354
+ const resolveCap = createCapabilityResolver(opts.capabilities, serverId);
355
+ const alwaysDenied = (tool) => {
356
+ const cap = resolveCap(tool);
357
+ governed.gateway.registerCapability(cap);
358
+ return governed.gateway.evaluate({ capabilityId: cap.id }).decision === "DENY";
359
+ };
360
+
361
+ // Refuse a call before it reaches the upstream, with a signed DENY. `args` must
362
+ // already be safe to record (a credential is redacted before it gets here).
363
+ const refuseBeforeUpstream = async ({ name, tool, args, code, message }) => {
364
+ const capability = resolveCap(tool ?? { name });
365
+ governed.gateway.registerCapability(capability);
366
+ await governed.gateway.recordDenial({
367
+ invocation: { capabilityId: capability.id, action: `mcp.callTool:${name}`, args: args ?? {} },
368
+ capability,
369
+ reason: code,
370
+ });
371
+ audit(opts, { kind: "call.denied", detail: { name, code } });
372
+ throw new McpError(ErrorCode.InvalidRequest, message);
373
+ };
374
+
261
375
  if (typeof opts.onReceipt === "function") {
262
376
  governed.gateway.on("receipt", opts.onReceipt);
263
377
  }
@@ -286,12 +400,12 @@ export async function startProxy(opts) {
286
400
  // upstream's surface. Best-effort: a slow/broken upstream listTools
287
401
  // must not fail proxy startup — the same call will be retried on the
288
402
  // consumer's first tools/list anyway.
289
- if (shadowDiscovery) {
290
- try {
291
- const seed = await upstreamClient.listTools();
292
- shadowDiscovery.recordToolList(seed.tools ?? []);
293
- } catch { /* best-effort seed; consumer-driven listTools re-records */ }
294
- }
403
+ // The same seed pins the tool definitions the proxy starts with.
404
+ try {
405
+ const seed = await upstreamClient.listTools();
406
+ shadowDiscovery?.recordToolList(seed.tools ?? []);
407
+ toolPins.observe(seed.tools ?? []);
408
+ } catch { /* best-effort seed; consumer-driven listTools re-records and re-pins */ }
295
409
 
296
410
  // ─── 4. Expose the proxy as an MCP server toward the consumer ──────────────
297
411
  const proxyServer = new Server(
@@ -307,10 +421,18 @@ export async function startProxy(opts) {
307
421
  // the original argument shapes — governance doesn't reshape tools.
308
422
  const upstream = await upstreamClient.listTools();
309
423
  shadowDiscovery?.recordToolList(upstream.tools ?? []);
424
+ toolPins.observe(upstream.tools ?? []);
310
425
  const upstreamByName = new Map(upstream.tools.map((t) => [t.name, t]));
311
- return {
312
- tools: tools.map((t) => upstreamByName.get(t.name) ?? { name: t.name }),
313
- };
426
+ const visible = [];
427
+ for (const t of tools) {
428
+ const full = upstreamByName.get(t.name) ?? { name: t.name };
429
+ // A drifted tool is not offered: its new description is model input
430
+ // nobody approved. Hidden here and refused at call time.
431
+ if (toolPins.isBlocked(t.name)) continue;
432
+ if (hideDeniedTools && alwaysDenied(full)) continue;
433
+ visible.push(full);
434
+ }
435
+ return { tools: visible };
314
436
  });
315
437
 
316
438
  proxyServer.setRequestHandler(CallToolRequestSchema, async (request) => {
@@ -318,6 +440,42 @@ export async function startProxy(opts) {
318
440
  // Shadow discovery counts the call BEFORE governance evaluates —
319
441
  // a denied call is still an observed action surface.
320
442
  shadowDiscovery?.recordCall(name);
443
+ // Re-read the upstream's current definitions before every call: a rug
444
+ // pull does not wait for the client to list tools again.
445
+ if (toolPins.mode !== "off") {
446
+ let current = null;
447
+ try { current = await upstreamClient.listTools(); } catch { /* the call itself will surface it */ }
448
+ if (current) toolPins.observe(current.tools ?? []);
449
+ if (toolPins.isBlocked(name)) {
450
+ const tool = current?.tools?.find((t) => t.name === name) ?? { name };
451
+ const detail = toolPins.driftDetail(name);
452
+ await refuseBeforeUpstream({
453
+ name,
454
+ tool,
455
+ args: contentGuard.checkCall(name, args).safeArgs,
456
+ code: TOOL_DEFINITION_CHANGED,
457
+ message:
458
+ `${TOOL_DEFINITION_CHANGED}: the upstream changed the definition of '${name}' since it was pinned ` +
459
+ `(pinned ${detail?.pinned?.slice(0, 12)}…, now ${detail?.seen?.slice(0, 12)}…). ` +
460
+ "The call was refused and not sent. An operator can accept the change by restarting the proxy with repinTools.",
461
+ });
462
+ }
463
+ }
464
+ // Content guard, before anything is sent: credentials in the arguments, and
465
+ // argument rules. Every refusal is a signed DENY; the matched text is never
466
+ // recorded (the receipt sees the arguments with credentials redacted).
467
+ {
468
+ const check = contentGuard.checkCall(name, args);
469
+ for (const event of check.report) audit(opts, event);
470
+ if (check.refuse) {
471
+ let tool = { name };
472
+ try {
473
+ const listed = await upstreamClient.listTools();
474
+ tool = listed.tools?.find((t) => t.name === name) ?? tool;
475
+ } catch { /* classify by name alone */ }
476
+ await refuseBeforeUpstream({ name, tool, args: check.safeArgs, ...check.refuse });
477
+ }
478
+ }
321
479
  // Forward actor context if the client put it in _meta — this is how
322
480
  // mcp-aware clients attribute calls to a specific agent identity.
323
481
  const ctx = {
@@ -326,9 +484,18 @@ export async function startProxy(opts) {
326
484
  };
327
485
  try {
328
486
  const result = await governed.callTool(name, args, ctx);
329
- return result;
487
+ // The signed outcome was recorded over the upstream's answer as received;
488
+ // only what the client sees is rewritten, and only in `redact` mode.
489
+ const checked = contentGuard.checkResult(name, result);
490
+ for (const event of checked.report) audit(opts, event);
491
+ return checked.result;
330
492
  } catch (err) {
331
- audit(opts, { kind: "call.denied", detail: { name, code: err?.code, message: err?.message } });
493
+ // An error message can echo a credential the upstream was given or holds.
494
+ const scrubbed = contentGuard.scrubError(err?.message);
495
+ audit(opts, { kind: "call.denied", detail: { name, code: err?.code, message: scrubbed.message } });
496
+ if (scrubbed.changed && contentGuard.resultsMode === "redact") {
497
+ try { err.message = scrubbed.message; } catch { /* read-only message: leave as is */ }
498
+ }
332
499
  // Re-throw as an MCP-shaped error so the consumer's client sees
333
500
  // a structured failure rather than a generic exception.
334
501
  throw err;
@@ -371,15 +538,19 @@ export async function startProxy(opts) {
371
538
 
372
539
  // ─── internal ─────────────────────────────────────────────────────────
373
540
 
541
+ /** JSON-RPC error code the MCP SDK uses when its own request timer fires. */
542
+ const MCP_REQUEST_TIMEOUT = -32001;
543
+
374
544
  /**
375
- * The single seam where Mode 3 enforcement will attach in v0.2.0.
376
- * Today this just forwards to the upstream client. In v0.2.0 a
377
- * `mode: "enforced"` option will mint an execution_authorization_v1
545
+ * The single seam where Mode 3 enforcement would attach (not shipped).
546
+ * Today this forwards to the upstream client, scrubbing credentials from
547
+ * errors and mapping a timed-out HTTP call to UPSTREAM_OUTCOME_UNKNOWN.
548
+ * A future `mode: "enforced"` option would mint an execution_authorization_v1
378
549
  * token at this layer and attach it via the chosen transport
379
550
  * (header for HTTP upstream, _meta for stdio first-party MCP) per
380
551
  * docs/architecture/mcp-mode-3-enforcement-v1.md §6.
381
552
  */
382
- function buildUpstreamIface(client, serverId) {
553
+ function buildUpstreamIface(client, serverId, { secrets = [], timeoutMs = null, onAudit } = {}) {
383
554
  return {
384
555
  serverId,
385
556
  listTools: async () => {
@@ -387,12 +558,49 @@ function buildUpstreamIface(client, serverId) {
387
558
  return out.tools.map((t) => ({ name: t.name, description: t.description }));
388
559
  },
389
560
  handler: async (name, args) => {
390
- return await client.callTool({ name, arguments: args ?? {} });
561
+ try {
562
+ // For an HTTP upstream the deadline is enforced twice: by the guarded
563
+ // fetch (no response headers in time) and by the SDK request timer
564
+ // (headers arrived, e.g. an SSE stream, but no result in time).
565
+ // Either way the request was sent, so the outcome is unknown.
566
+ const requestOptions = timeoutMs ? { timeout: timeoutMs } : undefined;
567
+ return await client.callTool({ name, arguments: args ?? {} }, undefined, requestOptions);
568
+ } catch (err) {
569
+ // Never let a resolved credential ride an error message back to the
570
+ // client or into the gateway's error event.
571
+ const timedOut =
572
+ timeoutMs !== null &&
573
+ (err?.code === UPSTREAM_OUTCOME_UNKNOWN || err?.code === MCP_REQUEST_TIMEOUT);
574
+ if (timedOut) {
575
+ if (typeof onAudit === "function") {
576
+ onAudit({ kind: "upstream.outcome_unknown", detail: { tool: name, timeoutMs } });
577
+ }
578
+ const unknown = new Error(
579
+ `${UPSTREAM_OUTCOME_UNKNOWN}: upstream did not answer '${name}' within ${timeoutMs} ms. ` +
580
+ "The request was sent, so the upstream may have acted. Not retried; check the upstream before calling again.",
581
+ );
582
+ unknown.code = UPSTREAM_OUTCOME_UNKNOWN;
583
+ throw unknown;
584
+ }
585
+ const scrubbed = new Error(redact(err?.message ?? String(err), secrets));
586
+ scrubbed.code = err?.code;
587
+ throw scrubbed;
588
+ }
391
589
  },
392
590
  };
393
591
  }
394
592
 
395
593
  function audit(opts, event) {
594
+ if (opts.__auditFile) {
595
+ try {
596
+ fs.appendFileSync(opts.__auditFile, JSON.stringify({ ts: new Date().toISOString(), ...event }) + "\n", { mode: 0o600 });
597
+ } catch (err) {
598
+ if (!opts.__auditWarned) {
599
+ opts.__auditWarned = true;
600
+ console.error(`[strix-proxy] warning: cannot write the audit log ${opts.__auditFile}: ${err?.message}`);
601
+ }
602
+ }
603
+ }
396
604
  if (typeof opts.onAudit === "function") {
397
605
  try { opts.onAudit(event); } catch { /* swallow audit-handler errors */ }
398
606
  }
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Tool-definition pinning ("rug-pull" protection) and discovery filtering.
3
+ *
4
+ * Pinning: the first time the proxy sees a tool, it records a SHA-256 over
5
+ * the tool's name, description, input schema and annotations. If a later
6
+ * `tools/list` from the upstream returns a different definition for the
7
+ * same name, the tool is "drifted". In `block` mode (the default) a drifted
8
+ * tool is hidden from the client's `tools/list` and every call to it is
9
+ * refused with a signed DENY receipt (reason TOOL_DEFINITION_CHANGED) before
10
+ * the upstream is contacted. In `warn` mode the drift is reported in the
11
+ * audit stream and the call proceeds. `off` disables pinning.
12
+ *
13
+ * Why: an MCP server can serve a harmless description when a person reviews
14
+ * it and a different one later. The description is model input, so a changed
15
+ * description is a changed instruction even if the tool's code is the same.
16
+ * OWASP's MCP guidance recommends this control; none of the ten gateways we
17
+ * surveyed on 2026-11-29 documents it.
18
+ *
19
+ * Accepting a change is a deliberate operator act: start the proxy with
20
+ * `repinTools: true` (CLI `--repin-tools`), or edit/delete the pin file.
21
+ * The pin file (`<storagePath>/tool-pins.json`) is an unsigned local record,
22
+ * not proof; with no storagePath the pins live only for the process.
23
+ *
24
+ * Discovery filtering: tools whose calls policy would always DENY are left
25
+ * out of `tools/list` when `hideDeniedTools: true` (opt-in; the default keeps
26
+ * the existing contract that the list is passed through unreshaped). The policy engine
27
+ * decides on capability and risk only, never on arguments, so "always
28
+ * denied" is an exact answer, not a guess. Hiding is not the control — the
29
+ * call is still refused if a client calls the tool by name.
30
+ */
31
+
32
+ import fs from "node:fs";
33
+ import path from "node:path";
34
+ import crypto from "node:crypto";
35
+ import { canonicalJSON } from "@strixgov/tool-gateway";
36
+ import { classifyMcpTool } from "@strixgov/mcp-adapter";
37
+
38
+ export const TOOL_PINS_BASENAME = "tool-pins.json";
39
+ export const TOOL_DEFINITION_CHANGED = "TOOL_DEFINITION_CHANGED";
40
+ export const PIN_MODES = Object.freeze(["block", "warn", "off"]);
41
+
42
+ /** SHA-256 over the parts of a tool definition a model reads. */
43
+ export function toolDefinitionHash(tool) {
44
+ const material = {
45
+ name: tool?.name ?? null,
46
+ description: tool?.description ?? null,
47
+ inputSchema: tool?.inputSchema ?? null,
48
+ annotations: tool?.annotations ?? null,
49
+ };
50
+ return crypto.createHash("sha256").update(canonicalJSON(stripUndefined(material))).digest("hex");
51
+ }
52
+
53
+ function stripUndefined(value) {
54
+ if (Array.isArray(value)) return value.map(stripUndefined);
55
+ if (value && typeof value === "object") {
56
+ const out = {};
57
+ for (const [k, v] of Object.entries(value)) if (v !== undefined) out[k] = stripUndefined(v);
58
+ return out;
59
+ }
60
+ return value;
61
+ }
62
+
63
+ /**
64
+ * @param {{ mode?: "block"|"warn"|"off", storagePath?: string|null, repin?: boolean,
65
+ * onAudit?: (e: object) => void }} opts
66
+ */
67
+ export function createToolPinStore(opts = {}) {
68
+ const mode = opts.mode ?? "block";
69
+ if (!PIN_MODES.includes(mode)) {
70
+ throw new Error(`toolPinning must be one of ${PIN_MODES.join(", ")}; got '${mode}'`);
71
+ }
72
+ const audit = (event) => {
73
+ try { opts.onAudit?.(event); } catch { /* audit handlers cannot break pinning */ }
74
+ };
75
+ const filePath = opts.storagePath ? path.join(opts.storagePath, TOOL_PINS_BASENAME) : null;
76
+ /** @type {Map<string, string>} */
77
+ const pins = new Map();
78
+ /** @type {Map<string, { pinned: string, seen: string }>} */
79
+ const drifted = new Map();
80
+
81
+ if (filePath && !opts.repin && mode !== "off") {
82
+ let raw = null;
83
+ try { raw = fs.readFileSync(filePath, "utf-8"); } catch { /* first run */ }
84
+ if (raw !== null) {
85
+ let parsed;
86
+ try { parsed = JSON.parse(raw); } catch {
87
+ throw new Error(`tool pin file ${filePath} is not valid JSON; fix or delete it (or start with repinTools)`);
88
+ }
89
+ for (const [name, hash] of Object.entries(parsed?.pins ?? {})) {
90
+ if (typeof hash === "string" && /^[0-9a-f]{64}$/.test(hash)) pins.set(name, hash);
91
+ }
92
+ }
93
+ }
94
+ if (opts.repin) audit({ kind: "tools.repinned", detail: { mode } });
95
+
96
+ function persist() {
97
+ if (!filePath) return;
98
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
99
+ const tmp = `${filePath}.${process.pid}.tmp`;
100
+ fs.writeFileSync(
101
+ tmp,
102
+ JSON.stringify(
103
+ {
104
+ note: "Unsigned local record of tool-definition hashes pinned by @strixgov/mcp-proxy. Not proof.",
105
+ pins: Object.fromEntries([...pins.entries()].sort(([a], [b]) => a.localeCompare(b))),
106
+ },
107
+ null,
108
+ 2,
109
+ ) + "\n",
110
+ );
111
+ fs.renameSync(tmp, filePath);
112
+ }
113
+
114
+ return {
115
+ mode,
116
+ filePath,
117
+ /** Record a tools/list. Returns the names that are drifted after this observation. */
118
+ observe(tools) {
119
+ if (mode === "off") return new Set();
120
+ let added = false;
121
+ for (const tool of tools ?? []) {
122
+ if (!tool || typeof tool.name !== "string") continue;
123
+ const hash = toolDefinitionHash(tool);
124
+ const pinned = pins.get(tool.name);
125
+ if (pinned === undefined) {
126
+ pins.set(tool.name, hash);
127
+ added = true;
128
+ continue;
129
+ }
130
+ if (pinned === hash) {
131
+ if (drifted.delete(tool.name)) {
132
+ audit({ kind: "tools.definition_restored", detail: { tool: tool.name } });
133
+ }
134
+ continue;
135
+ }
136
+ const previous = drifted.get(tool.name);
137
+ if (!previous || previous.seen !== hash) {
138
+ drifted.set(tool.name, { pinned, seen: hash });
139
+ audit({
140
+ kind: "tools.definition_changed",
141
+ detail: { tool: tool.name, pinnedHash: pinned, seenHash: hash, mode },
142
+ });
143
+ }
144
+ }
145
+ if (added) {
146
+ try { persist(); } catch (err) {
147
+ audit({ kind: "tools.pin_persist_failed", detail: { message: err?.message } });
148
+ }
149
+ }
150
+ return new Set(drifted.keys());
151
+ },
152
+ /** True when calls to this tool must be refused. */
153
+ isBlocked(name) {
154
+ return mode === "block" && drifted.has(name);
155
+ },
156
+ isDrifted(name) {
157
+ return drifted.has(name);
158
+ },
159
+ driftDetail(name) {
160
+ return drifted.get(name) ?? null;
161
+ },
162
+ };
163
+ }
164
+
165
+ /**
166
+ * Resolve the capability for a tool exactly the way @strixgov/mcp-adapter
167
+ * does (pack id, then bare name, then heuristic), so the proxy's preview and
168
+ * denial receipts name the same capability a real call would.
169
+ */
170
+ export function createCapabilityResolver(capabilities, serverId) {
171
+ const byFullId = new Map();
172
+ const byName = new Map();
173
+ for (const cap of Array.isArray(capabilities) ? capabilities : []) {
174
+ byFullId.set(cap.id, cap);
175
+ const bare = cap.id.replace(/^mcp\.[^.]+\./, "");
176
+ byName.set(bare, cap);
177
+ if (typeof cap.name === "string" && cap.name !== bare) byName.set(cap.name, cap);
178
+ }
179
+ return (tool) =>
180
+ byFullId.get(`mcp.${serverId}.${tool.name}`) ??
181
+ byName.get(tool.name) ??
182
+ classifyMcpTool({ ...tool, serverId });
183
+ }