Skip to content

MCP tool-authorization gateway lab

A policy gateway between an agent runtime and a mock MCP-style stdio server, tested against a deliberately compromised stand-in agent for allowlists, scoped identity, taint, approval gates, descriptor pinning, output validation and tamper-evident audit.

AI Security 5 min read

Implementation

gateway.js JavaScript · 391 lines
labs/mcp-tool-authorization/gateway.js
1"use strict";
2 
3/**
4 * Policy gateway between an agent runtime and an MCP-style tool server.
5 *
6 * It is the single enforcement point: the model proposes, the gateway decides, and the
7 * upstream server only ever sees a call that passed every check. It is written so that its
8 * decisions hold even if the model is fully compromised (see agent-sim.js, which is that
9 * worst case on purpose).
10 *
11 * Order of checks - cheap and structural first, effects last:
12 *   context -> allowlist -> advertised and pinned -> schema -> resource validity -> authority
13 *   (user AND agent) -> destination allowlist -> rate limit -> risk gating (allow / approval / deny)
14 *   -> approval verification -> audit the decision -> execute with a timeout -> validate output
15 *   -> taint the session -> audit the outcome.
16 *
17 * Every result carries a stable reason code. No path through this file executes an upstream
18 * call without first writing an "allow" decision to the audit log (fail closed if that write fails).
19 *
20 * This is a teaching model. It validates a lab context object; it does not authenticate users or
21 * agents, verify tokens, or protect the approval surface from a compromised runtime process.
22 */
23 
24const { spawn } = require("node:child_process");
25const crypto = require("node:crypto");
26const readline = require("node:readline");
27const { hashJson } = require("./lib/canonical");
28const { validate } = require("./lib/schema");
29const { ResourceError, allows, emailDomain, validatePath } = require("./lib/scope");
30 
31const RISKS = new Set(["read", "write_internal", "egress", "destructive"]);
32// eslint-disable-next-line no-control-regex
33const BAD_CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
34const INJECTION_HINT = /(ignore (all |any |the )?(previous|prior) instructions|system note to assistant|\bCALL\s+\w+\s*\{)/i;
35 
36class Deny extends Error {
37  constructor(reason, detail = "") {
38    super(`${reason}${detail ? `: ${detail}` : ""}`);
39    this.reason = reason;
40    this.detail = detail;
41  }
42}
43 
44function isRecord(v) { return v !== null && typeof v === "object" && !Array.isArray(v); }
45 
46function validatePolicy(policy) {
47  const bad = (m) => { throw new Deny("POLICY_INVALID", m); };
48  if (!isRecord(policy) || typeof policy.version !== "string" || !isRecord(policy.tools)) bad("missing version or tools");
49  for (const [name, t] of Object.entries(policy.tools)) {
50    if (!RISKS.has(t.risk)) bad(`${name}: unknown risk class ${JSON.stringify(t.risk)}`);
51    if (!/^[0-9a-f]{64}$/.test(t.pinnedHash || "")) bad(`${name}: pinnedHash must be a SHA-256`);
52    if (!t.capability || !t.verb) bad(`${name}: capability and verb required`);
53    if (t.resourceKind && !["path", "email_domain", "none"].includes(t.resourceKind)) bad(`${name}: unknown resourceKind`);
54    if (t.resourceKind && t.resourceKind !== "none" && !t.resourceArg) bad(`${name}: resourceArg required`);
55  }
56  if (!Array.isArray(policy.approvers)) bad("approvers must be a list of human principal ids");
57  if (!isRecord(policy.output) || !Number.isInteger(policy.output.maxBytes)) bad("output.maxBytes required");
58  if (!isRecord(policy.egress) || !Array.isArray(policy.egress.allowedRecipientDomains)) bad("egress.allowedRecipientDomains required");
59  return policy;
60}
61 
62/** Minimal newline-delimited JSON-RPC 2.0 client over a child process's stdio. */
63class StdioClient {
64  constructor(command, args, env, timeoutMs, onNotification, onStderrLine) {
65    this.timeoutMs = timeoutMs;
66    this.pending = new Map();
67    this.nextId = 1;
68    this.closed = false;
69    this.child = spawn(command, args, { stdio: ["pipe", "pipe", onStderrLine ? "pipe" : "ignore"], env: { ...process.env, ...env } });
70    this.observesStderr = Boolean(onStderrLine);
71    this.barriers = new Map();
72    this.barrierSeq = 0;
73    this.stderrClosed = Promise.resolve();
74    if (onStderrLine) {
75      const stderrLines = readline.createInterface({ input: this.child.stderr });
76      this.stderrClosed = new Promise((resolve) => stderrLines.on("close", resolve));
77      stderrLines.on("line", (line) => {
78        if (line.startsWith("BARRIER ")) {
79          const release = this.barriers.get(line.slice(8));
80          if (release) { this.barriers.delete(line.slice(8)); release(); }
81          return;
82        }
83        onStderrLine(line);
84      });
85    }
86    this.child.on("exit", () => {
87      this.closed = true;
88      for (const { reject, timer } of this.pending.values()) { clearTimeout(timer); reject(new Deny("UPSTREAM_FAILURE", "server exited")); }
89      this.pending.clear();
90    });
91    this.child.stdin.on("error", () => {});
92    readline.createInterface({ input: this.child.stdout }).on("line", (line) => {
93      let message;
94      try { message = JSON.parse(line); } catch { return; }
95      if (message.id !== undefined && this.pending.has(message.id)) {
96        const { resolve, reject, timer } = this.pending.get(message.id);
97        clearTimeout(timer);
98        this.pending.delete(message.id);
99        if (message.error) reject(new Deny("UPSTREAM_FAILURE", message.error.message));
100        else resolve(message.result);
101      } else if (message.method && onNotification) onNotification(message.method);
102    });
103  }
104 
105  request(method, params) {
106    if (this.closed) return Promise.reject(new Deny("UPSTREAM_FAILURE", "server not running"));
107    const id = this.nextId++;
108    return new Promise((resolve, reject) => {
109      const timer = setTimeout(() => { this.pending.delete(id); reject(new Deny("UPSTREAM_TIMEOUT", `${method} exceeded ${this.timeoutMs} ms`)); }, this.timeoutMs);
110      this.pending.set(id, { resolve, reject, timer });
111      this.child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`);
112    });
113  }
114 
115  notify(method, params) { this.child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`); }
116  stop() { this.child.kill(); }
117 
118  /**
119   * Test seam. Resolves once every stderr line the upstream wrote before this call has been delivered
120   * to the stderr observer. Responses (stdout) and side-effect reports (stderr) are separate pipes with
121   * no ordering guarantee between them, so "the response arrived" does not mean "its effect line has".
122   * A positive assertion would flake; worse, a negative one ("nothing happened") would pass vacuously.
123   * The barrier is a marker on the single ordered stderr pipe, so it is a proof, not a delay.
124   */
125  async barrier(timeoutMs = this.timeoutMs) {
126    if (!this.observesStderr) return;
127    if (this.closed) return this.stderrClosed;
128    const token = `b${this.barrierSeq++}`;
129    const seen = new Promise((resolve) => this.barriers.set(token, resolve));
130    this.child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: `barrier-${token}`, method: "lab/barrier", params: { token } })}\n`);
131    let timer;
132    const expired = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`stderr barrier not observed within ${timeoutMs} ms`)), timeoutMs); });
133    try { await Promise.race([seen, this.stderrClosed, expired]); } finally { clearTimeout(timer); this.barriers.delete(token); }
134  }
135}
136 
137class Gateway {
138  #policy; #audit; #now; #client = null; #descriptors = new Map(); #status = new Map();
139  #approvals = new Map(); #calls = new Map(); #command; #args; #env; #timeoutMs; #onStderr;
140 
141  constructor({ policy, audit, command = process.execPath, args = [], env = {}, now = () => Date.now(), timeoutMs = 1500, onUpstreamStderr = null }) {
142    this.#policy = validatePolicy(policy);
143    this.#audit = audit;
144    this.#command = command; this.#args = args; this.#env = env; this.#now = now; this.#timeoutMs = timeoutMs; this.#onStderr = onUpstreamStderr;
145  }
146 
147  get toolStatus() { return Object.fromEntries(this.#status); }
148 
149  async start() {
150    this.#client = new StdioClient(this.#command, this.#args, this.#env, this.#timeoutMs, (method) => {
151      if (method === "notifications/tools/list_changed") this.#refresh().catch(() => {});
152    }, this.#onStderr);
153    await this.#client.request("initialize", { protocolVersion: "2025-11-25", capabilities: {}, clientInfo: { name: "gateway", version: "0.0.1" } });
154    this.#client.notify("notifications/initialized");
155    await this.#refresh();
156  }
157 
158  stop() { if (this.#client) this.#client.stop(); }
159 
160  /** Test seam, not reachable from an agent: see StdioClient.barrier. A no-op unless a stderr observer is configured. */
161  upstreamStderrBarrier() { return this.#client ? this.#client.barrier() : Promise.resolve(); }
162 
163  /** Re-read tools/list and compare each descriptor with its pin. Unreviewed or changed tools are not callable. */
164  async #refresh() {
165    const { tools } = await this.#client.request("tools/list", {});
166    this.#descriptors.clear(); this.#status.clear();
167    for (const tool of tools) {
168      const pinned = this.#policy.tools[tool.name];
169      if (!pinned) this.#status.set(tool.name, "unreviewed");
170      else if (hashJson(tool) !== pinned.pinnedHash) this.#status.set(tool.name, "drifted");
171      else { this.#status.set(tool.name, "ok"); this.#descriptors.set(tool.name, tool); }
172    }
173    for (const name of Object.keys(this.#policy.tools)) if (!this.#status.has(name)) this.#status.set(name, "not advertised");
174    this.#log({ event: "tools_refreshed", status: this.toolStatus });
175  }
176 
177  /** What the model is shown: only pinned tools the user AND agent could ever use. Hiding is hygiene, not enforcement. */
178  visibleTools(ctx) {
179    const out = [];
180    for (const [name, tool] of this.#descriptors) {
181      const entry = this.#policy.tools[name];
182      const mayUse = (scopes) => scopes.some((s) => s.startsWith(`${entry.capability}:${entry.verb}:`));
183      if (isRecord(ctx) && ctx.user && ctx.agent && mayUse(ctx.user.scopes || []) && mayUse(ctx.agent.scopes || [])) {
184        out.push({ name, description: tool.description, inputSchema: tool.inputSchema });
185      }
186    }
187    return out;
188  }
189 
190  #log(fields) {
191    return this.#audit.append({ policyVersion: this.#policy.version, ...fields });
192  }
193 
194  #validateContext(ctx) {
195    const ok = isRecord(ctx) && isRecord(ctx.user) && isRecord(ctx.agent) && isRecord(ctx.session)
196      && typeof ctx.user.id === "string" && ctx.user.id && typeof ctx.user.tenant === "string" && Array.isArray(ctx.user.scopes)
197      && typeof ctx.agent.id === "string" && ctx.agent.id && Array.isArray(ctx.agent.scopes)
198      && typeof ctx.session.id === "string" && typeof ctx.session.tainted === "boolean";
199    if (!ok) throw new Deny("INVALID_CONTEXT", "user, agent and session identity are required and are never taken from the model");
200  }
201 
202  static #redact(args, redactKeys) {
203    const preview = {};
204    for (const [k, v] of Object.entries(isRecord(args) ? args : {})) {
205      if (typeof v === "string") preview[k] = redactKeys.includes(k) ? `<redacted ${v.length} chars>` : v.slice(0, 60);
206      else preview[k] = `<${Array.isArray(v) ? "array" : typeof v}>`;
207    }
208    return preview;
209  }
210 
211  #summary(tool, args) {
212    const clean = (s) => String(s).replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 80);
213    if (tool === "send_email") return `Send email to ${clean(args.to)}, subject "${clean(args.subject)}", body ${String(args.body).length} characters`;
214    return `${tool} ${JSON.stringify(Gateway.#redact(args, this.#policy.redactKeys || []))}`;
215  }
216 
217  /** Decide and, if allowed, execute. Never throws for a denial; returns a structured outcome. */
218  async callTool(ctx, name, args, { approvalId = null } = {}) {
219    let toolName = typeof name === "string" ? name : "<invalid>";
220    const meta = () => ({
221      userId: isRecord(ctx?.user) ? ctx.user.id : "<invalid>", tenant: isRecord(ctx?.user) ? ctx.user.tenant : "<invalid>",
222      agentId: isRecord(ctx?.agent) ? ctx.agent.id : "<invalid>", sessionId: isRecord(ctx?.session) ? ctx.session.id : "<invalid>",
223      tainted: isRecord(ctx?.session) ? ctx.session.tainted === true : null, tool: toolName,
224      argsHash: (() => { try { return hashJson(args); } catch { return "<unhashable>"; } })(),
225      argsPreview: Gateway.#redact(args, this.#policy.redactKeys || []),
226    });
227    let descriptorHash = null;
228    try {
229      this.#validateContext(ctx);
230      const entry = this.#policy.tools[toolName];
231      if (!entry || !Object.hasOwn(this.#policy.tools, toolName)) throw new Deny("TOOL_NOT_ALLOWLISTED");
232      const status = this.#status.get(toolName);
233      if (status === "drifted") throw new Deny("DESCRIPTOR_DRIFT", "the server's descriptor no longer matches the reviewed pin");
234      if (status !== "ok") throw new Deny("TOOL_NOT_ADVERTISED");
235      const descriptor = this.#descriptors.get(toolName);
236      descriptorHash = hashJson(descriptor);
237 
238      // Structure: arguments must be a plain object that matches the PINNED schema, closed.
239      if (!isRecord(args)) throw new Deny("SCHEMA_VIOLATION", "arguments must be an object");
240      const schemaErrors = validate(descriptor.inputSchema, args);
241      if (schemaErrors.length) throw new Deny("SCHEMA_VIOLATION", schemaErrors.slice(0, 3).join("; "));
242 
243      // Resource: validated, never repaired.
244      let resource = "*";
245      try {
246        if (entry.resourceKind === "path") resource = validatePath(args[entry.resourceArg]);
247        else if (entry.resourceKind === "email_domain") resource = emailDomain(args[entry.resourceArg]);
248      } catch (e) {
249        if (e instanceof ResourceError) throw new Deny(entry.resourceKind === "path" ? "PATH_INVALID" : "RECIPIENT_INVALID", e.message);
250        throw e;
251      }
252 
253      // Authority is the INTERSECTION of the user's and the agent's scopes.
254      if (!allows(ctx.user.scopes, entry.capability, entry.verb, resource)) throw new Deny("USER_SCOPE_DENIED", `${entry.capability}:${entry.verb}`);
255      if (!allows(ctx.agent.scopes, entry.capability, entry.verb, resource)) throw new Deny("AGENT_SCOPE_DENIED", `${entry.capability}:${entry.verb}`);
256      if (entry.risk === "egress" && !this.#policy.egress.allowedRecipientDomains.includes(resource)) {
257        throw new Deny("RECIPIENT_NOT_ALLOWED", "approval cannot widen the destination allowlist");
258      }
259 
260      // Risk gating.
261      let needsApproval = false;
262      if (entry.risk === "write_internal") needsApproval = ctx.session.tainted;
263      else if (entry.risk === "egress") needsApproval = true;
264      else if (entry.risk === "destructive") {
265        if (ctx.session.tainted) throw new Deny("TAINTED_SESSION_DESTRUCTIVE", "untrusted content is in the model's context");
266        needsApproval = true;
267      }
268 
269      let approvalToConsume = null;
270      const actionHash = hashJson({ user: ctx.user.id, agent: ctx.agent.id, tool: toolName, args, descriptor: descriptorHash });
271      if (needsApproval) {
272        if (!approvalId) {
273          // Bound the work an agent can push onto human reviewers.
274          const pending = [...this.#approvals.values()].filter((a) => a.agentId === ctx.agent.id && ["pending", "approved"].includes(a.state) && this.#now() <= a.expiresAt).length;
275          if (pending >= (this.#policy.maxPendingApprovals || 3)) throw new Deny("TOO_MANY_PENDING_APPROVALS", `${pending} requests already waiting for a human`);
276          const id = `apr-${crypto.randomBytes(6).toString("hex")}`;
277          const request = { id, actionHash, state: "pending", userId: ctx.user.id, agentId: ctx.agent.id, tool: toolName, summary: this.#summary(toolName, args), expiresAt: this.#now() + (this.#policy.approvalTtlSeconds || 120) * 1000, approverId: null };
278          this.#approvals.set(id, request);
279          const rec = this.#log({ event: "decision", decision: "approval_required", reason: "APPROVAL_REQUIRED", executed: false, approvalId: id, descriptorHash, ...meta() });
280          return { decision: "approval_required", reason: "APPROVAL_REQUIRED", executed: false, approvalId: id, summary: request.summary, auditSeq: rec.seq };
281        }
282        const approval = this.#approvals.get(approvalId);
283        if (!approval) throw new Deny("APPROVAL_INVALID", "unknown approval id");
284        if (approval.state === "consumed") throw new Deny("APPROVAL_CONSUMED", "single use");
285        if (approval.state === "denied") throw new Deny("APPROVAL_DENIED");
286        if (approval.state !== "approved") throw new Deny("APPROVAL_INVALID", "not approved yet");
287        if (this.#now() > approval.expiresAt) throw new Deny("APPROVAL_EXPIRED");
288        if (approval.actionHash !== actionHash) throw new Deny("APPROVAL_MISMATCH", "approval is bound to different arguments, identity or tool descriptor");
289        approvalToConsume = approval;
290      }
291 
292      // Rate limit EXECUTIONS per agent and tool. Checked before the approval is consumed, so a
293      // limited call does not waste a human's decision; denied probes do not consume budget (they are audited instead).
294      if (entry.rate) {
295        const key = `${ctx.agent.id}|${toolName}`;
296        const window = (this.#calls.get(key) || []).filter((t) => this.#now() - t < entry.rate.windowSeconds * 1000);
297        if (window.length >= entry.rate.max) { this.#calls.set(key, window); throw new Deny("RATE_LIMITED", `${entry.rate.max} per ${entry.rate.windowSeconds}s`); }
298        window.push(this.#now()); this.#calls.set(key, window);
299      }
300      // Consumed before the call: a failed call must not leave a reusable approval.
301      if (approvalToConsume) approvalToConsume.state = "consumed";
302 
303      // Audit the decision BEFORE executing. If this write fails, nothing runs.
304      let allowSeq = null;
305      try {
306        allowSeq = this.#log({ event: "decision", decision: "allow", reason: needsApproval ? "ALLOWED_WITH_APPROVAL" : "ALLOWED", executed: false, approvalId: approvalId || null, descriptorHash, ...meta() }).seq;
307      } catch {
308        throw new Deny("AUDIT_UNAVAILABLE", "the decision could not be recorded, so the call was not made");
309      }
310 
311      let raw;
312      try {
313        raw = await this.#client.request("tools/call", { name: toolName, arguments: args });
314      } catch (e) {
315        if (e instanceof Deny) {
316          const rec = this.#safeLog({ event: "outcome", outcome: e.reason, executed: false, ...meta() });
317          return { decision: "allow", reason: e.reason, executed: false, upstreamFailed: true, auditSeq: rec ? rec.seq : allowSeq };
318        }
319        throw e;
320      }
321 
322      const checked = this.#validateOutput(descriptor, raw);
323      if (!checked.ok) {
324        const rec = this.#safeLog({ event: "outcome", outcome: "OUTPUT_INVALID", detail: checked.error, executed: true, ...meta() });
325        return { decision: "allow", reason: "OUTPUT_INVALID", executed: true, outputWithheld: true, detail: checked.error, auditSeq: rec ? rec.seq : allowSeq };
326      }
327      if (entry.taintsSession) ctx.session.tainted = true; // content from outside the trust boundary is now in the model's context
328      if (checked.flags.includes("instruction_like_content")) ctx.session.tainted = true;
329      const rec = this.#safeLog({ event: "outcome", outcome: "OK", executed: true, flags: checked.flags, taintedAfter: ctx.session.tainted, ...meta() });
330      return { decision: "allow", reason: needsApproval ? "ALLOWED_WITH_APPROVAL" : "ALLOWED", executed: true, result: checked.result, auditSeq: rec ? rec.seq : allowSeq };
331    } catch (e) {
332      if (!(e instanceof Deny)) throw e;
333      let auditFailed = false; let auditSeq = null;
334      try { auditSeq = this.#log({ event: "decision", decision: "deny", reason: e.reason, detail: e.detail.slice(0, 200), executed: false, descriptorHash, ...meta() }).seq; } catch { auditFailed = true; }
335      return { decision: "deny", reason: e.reason, detail: e.detail, executed: false, auditFailed, auditSeq };
336    }
337  }
338 
339  #safeLog(fields) {
340    try { return this.#log(fields); } catch { return null; /* the decision record already exists; an outcome record can be lost */ }
341  }
342 
343  /** The human decision surface. Not reachable from the agent: approver ids come from policy, never from the model. */
344  approve(approvalId, approverId, verdict = "approve") {
345    const approval = this.#approvals.get(approvalId);
346    let outcome;
347    if (!approval) outcome = { ok: false, reason: "APPROVAL_INVALID" };
348    else if (!this.#policy.approvers.includes(approverId) || approverId === approval.agentId) outcome = { ok: false, reason: "APPROVER_NOT_AUTHORIZED" };
349    else if (approval.state !== "pending") outcome = { ok: false, reason: approval.state === "consumed" ? "APPROVAL_CONSUMED" : "APPROVAL_INVALID" };
350    else if (this.#now() > approval.expiresAt) outcome = { ok: false, reason: "APPROVAL_EXPIRED" };
351    else { approval.state = verdict === "approve" ? "approved" : "denied"; approval.approverId = approverId; outcome = { ok: true, reason: approval.state === "approved" ? "APPROVED" : "APPROVAL_DENIED" }; }
352    this.#safeLog({ event: "approval", approvalId, approverId: String(approverId).slice(0, 64), reason: outcome.reason, ok: outcome.ok, tool: approval?.tool || "<unknown>" });
353    return outcome;
354  }
355 
356  #validateOutput(descriptor, raw) {
357    const out = this.#policy.output;
358    const fail = (error) => ({ ok: false, error });
359    if (!isRecord(raw) || !Array.isArray(raw.content) || raw.content.length > 8) return fail("content must be a short array");
360    if (raw.isError !== undefined && typeof raw.isError !== "boolean") return fail("isError must be boolean");
361    let bytes = 0;
362    const flags = [];
363    const content = [];
364    for (const item of raw.content) {
365      if (!isRecord(item) || item.type !== "text" || typeof item.text !== "string" || Object.keys(item).sort().join() !== "text,type") return fail("only plain text content is accepted");
366      if (BAD_CONTROL.test(item.text)) return fail("control characters in output");
367      bytes += Buffer.byteLength(item.text);
368      let text = item.text;
369      text = text.replace(/https?:\/\/([A-Za-z0-9.-]+)[^\s)"']*/g, (url, host) => {
370        if ((out.allowedHosts || []).includes(host.toLowerCase())) return url;
371        if (!flags.includes("links_removed")) flags.push("links_removed");
372        return "[link removed: host not allowed]";
373      });
374      if (INJECTION_HINT.test(text) && !flags.includes("instruction_like_content")) flags.push("instruction_like_content");
375      content.push({ type: "text", text });
376    }
377    if (bytes > out.maxBytes) return fail(`output ${bytes} bytes exceeds ${out.maxBytes}`);
378    const result = { content, isError: raw.isError === true, provenance: "tool_output", flags };
379    if (descriptor.outputSchema && !result.isError) {
380      if (raw.structuredContent === undefined) return fail("outputSchema declared but structuredContent missing");
381      const errors = validate(descriptor.outputSchema, raw.structuredContent);
382      if (errors.length) return fail(`structuredContent invalid: ${errors[0]}`);
383      result.structuredContent = raw.structuredContent;
384    } else if (raw.structuredContent !== undefined) {
385      return fail("structuredContent returned without an outputSchema");
386    }
387    return { ok: true, result, flags };
388  }
389}
390 
391module.exports = { Deny, Gateway, validatePolicy };

Run it

  • node --test labs/mcp-tool-authorization/tests/gateway.test.js
  • node labs/mcp-tool-authorization/scripts/run-scenarios.js

Status: partially tested. Dependency-free Node.js; the tests run in npm run validate. The analysis, diagrams and the mapping to the MCP specification are in the article: MCP Tool Authorization Lab.

There is no language model here. The "agent" is a deterministic stand-in that obeys any CALL tool {json} line found in a tool result: the worst case of a compromised planner. It shows that the gateway's decisions do not depend on model behaviour. It cannot show whether a real model is injectable or how often. No LLM API is contacted, no credential is used, and every tool effect is an in-memory array append in a local child process. The .test domains are reserved for testing; all data is synthetic.

Evidence labels: tested locally (executed here; output in evidence/), policy model (decision logic evaluated against a stand-in, not a real model or identity provider), source-reviewed, requires-review.

Scope

The authorization decision for an agent-proposed tool call: which tools exist, whose authority applies, when a human must decide, what the tool may return, and what is recorded. Out of scope: authenticating users or agents (the context is a trusted input here), token issuance and exchange, the MCP authorization flow, transport security, sandboxing the tool server, and any real model behaviour. This extends the AI-agent external tool-broker lab (action-bound approval, replay resistance) to an MCP-shaped server with taint, descriptor pinning, output validation and an audit chain; it does not replace it, and the SSRF lab covers URL-fetching tools.

What I built

Path Purpose
mock-server.js Newline-delimited JSON-RPC 2.0 over stdio: initialize, tools/list, tools/call; five tools on in-memory data; modes normal, rugpull, hostile_output, slow, crash; side effects reported on stderr so tests observe them independently; plus a lab-only lab/barrier method (not MCP) that orders stderr against stdout for the test harness
gateway.js The single enforcement point: allowlist, descriptor pin, closed-schema check, path/recipient validation, user-AND-agent scope intersection, destination allowlist, risk gating with taint, approval verification, execution rate limit, audit-before-execute, timeout, output validation
policy.json Deny-by-default policy; each tool's reviewed descriptor is pinned by SHA-256
audit.js Hash-chained append-only log with verifyChain
lib/ Canonical hashing, a closed JSON-Schema subset, strict scope and path matching
agent-sim.js NaiveAgent, the compromised-planner stand-in
tests/gateway.test.js 35 tests against a real spawned server process
scripts/run-scenarios.js 16 scenarios, expectations declared before each step, decision matrix written to JSON and Markdown
scripts/pin.js, scripts/run-lab.sh Pin check/update; run everything

Validation

Recorded run (evidence/versions.txt): Node.js v22.23.4, Linux 6.18.44, policy version 2026-11-05.1.

node --test labs/mcp-tool-authorization/tests/gateway.test.js     # 35 tests
node labs/mcp-tool-authorization/scripts/run-scenarios.js         # 16 scenarios, 31 proposed calls
bash labs/mcp-tool-authorization/scripts/run-lab.sh               # pins + tests + scenarios
Check Observed
Descriptor pins all five match the benign server
Mechanism tests 35 passed, 0 failed (includes a check that every reason code the gateway can emit was exercised)
Scenario matrix 16 scenarios, 31 proposed calls: 11 allow, 5 approval required, 15 deny; every expectation met; every audit chain verifies
Side effects observed on a channel separate from the protocol: nothing happened for any denied or unapproved call. Reads are ordered by a stderr barrier; without it the assertion could pass because a line was late (see the article, finding 8)
Reproducibility decisions, reasons, effect counts and audit sequence numbers are identical across runs. The audit-chain head hashes in decision-matrix.json are not: approval ids are random, so they change on every run and are not a regression signal

The matrix, with a read-across to reasons and audit sequence numbers, is in the article.

What was not tested

  • A real language model, real prompt injection, or any measure of how injectable a model is. The stand-in obeys every injected instruction by construction.
  • Authentication of the user, the agent or the approver; token validation; the MCP authorization specification; OAuth flows.
  • A conformant MCP server or client: the mock implements four MCP methods (initialize, notifications/initialized, tools/list, tools/call) plus the lab-only barrier, and no pagination, capabilities negotiation, resources, prompts or sampling.
  • Remote (HTTP) MCP transport; only stdio.
  • A compromised gateway host, a compromised approval UI, or an attacker with access to the audit store. The audit chain's tail-truncation gap is demonstrated, not closed.
  • Concurrency, performance and rate-limit behaviour under load; approval-fatigue effects on real reviewers.
  • Cloud, production data or credentials. None is used.

Production considerations

See the article: rollout (observe before enforce, onboard a tool by reviewing its pin), detection (alert on drift, repeated denials, approval floods), operability (audit outage is tool outage, by design), false positives (taint gating creates approval work), blast radius and rollback.

References

  • Model Context Protocol, specification revision 2025-11-25, source of Tools (message shapes, annotations untrusted, security considerations) and Transports (stdio framing).
  • Node.js version: the runtime's own output, in evidence/versions.txt.