@intentrax/sdk 1.7.0 → 1.8.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 (43) hide show
  1. package/README.md +17 -2
  2. package/cli/intentrax.mjs +45 -1
  3. package/mcp/README.md +138 -0
  4. package/mcp/canonical.d.ts +12 -0
  5. package/mcp/canonical.mjs +70 -0
  6. package/mcp/cli.d.ts +16 -0
  7. package/mcp/cli.mjs +214 -0
  8. package/mcp/client.d.ts +131 -0
  9. package/mcp/client.mjs +955 -0
  10. package/mcp/commands.d.ts +113 -0
  11. package/mcp/commands.mjs +575 -0
  12. package/mcp/index.d.ts +12 -0
  13. package/mcp/index.mjs +12 -0
  14. package/mcp/proxy.d.ts +47 -0
  15. package/mcp/proxy.mjs +434 -0
  16. package/mcp/receipt-meta.d.ts +59 -0
  17. package/mcp/receipt-meta.mjs +178 -0
  18. package/mcp/tool-manifest.d.ts +74 -0
  19. package/mcp/tool-manifest.mjs +154 -0
  20. package/package.json +16 -1
  21. package/readback/README.md +352 -0
  22. package/readback/bridge.mjs +71 -0
  23. package/readback/cli.mjs +150 -0
  24. package/readback/confirm.mjs +404 -0
  25. package/readback/index.mjs +12 -0
  26. package/readback/recipe-worker.mjs +33 -0
  27. package/readback/recipes/_shared.mjs +126 -0
  28. package/readback/recipes/email-delivery.mjs +136 -0
  29. package/readback/recipes/github-issue.mjs +88 -0
  30. package/readback/recipes/http-json.mjs +109 -0
  31. package/readback/recipes/sql-row.mjs +96 -0
  32. package/readback/recipes/stripe-refund.mjs +73 -0
  33. package/readback/redact.mjs +68 -0
  34. package/scan/README.md +211 -0
  35. package/scan/classify.mjs +276 -0
  36. package/scan/cli.mjs +102 -0
  37. package/scan/configs.mjs +261 -0
  38. package/scan/credentials.mjs +121 -0
  39. package/scan/extract.mjs +323 -0
  40. package/scan/gates.mjs +94 -0
  41. package/scan/report.mjs +58 -0
  42. package/scan/scan.mjs +571 -0
  43. package/scan/text.mjs +186 -0
package/mcp/index.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ // Types for @intentrax/sdk/mcp (R1b): MCP tool-manifest pinning, drift checks, an
2
+ // enforcing stdio proxy, and receipt `_meta` helpers. Dependency-free.
3
+ //
4
+ // Covers tool definitions only. It does not show that the server's code or
5
+ // behaviour is unchanged.
6
+
7
+ export * from "./canonical.js";
8
+ export * from "./tool-manifest.js";
9
+ export * from "./receipt-meta.js";
10
+ export * from "./client.js";
11
+ export * from "./commands.js";
12
+ export * from "./proxy.js";
package/mcp/index.mjs ADDED
@@ -0,0 +1,12 @@
1
+ // @intentrax/sdk/mcp (R1b): MCP tool-manifest pinning, drift checks, an
2
+ // enforcing stdio proxy, and receipt `_meta` helpers. Dependency-free.
3
+ //
4
+ // Covers tool definitions only. It does not show that the server's code or
5
+ // behaviour is unchanged.
6
+
7
+ export * from "./canonical.mjs";
8
+ export * from "./tool-manifest.mjs";
9
+ export * from "./receipt-meta.mjs";
10
+ export * from "./client.mjs";
11
+ export * from "./commands.mjs";
12
+ export * from "./proxy.mjs";
package/mcp/proxy.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ // Types for proxy.mjs: the stdio MCP proxy that enforces a tool pin.
2
+
3
+ import type { ServerInput } from "./client.js";
4
+
5
+ /** JSON-RPC error code the proxy uses when it refuses a tools/call. */
6
+ export const PROXY_BLOCKED_CODE: -32090;
7
+ export const ON_DRIFT_MODES: readonly ["block", "warn"];
8
+
9
+ export interface ProxyOptions {
10
+ /** Pin file (default .intentrax/mcp-pins.json, relative to cwd). */
11
+ pins?: string;
12
+ /** Pin entry name; optional when the file has one server. */
13
+ name?: string;
14
+ /** Upstream override; defaults to the pinned server spec. */
15
+ server?: ServerInput;
16
+ cwd?: string;
17
+ /** "block" (default): hide changed/new tools and refuse calls to them. "warn": log only. */
18
+ onDrift?: "block" | "warn";
19
+ input?: NodeJS.ReadableStream;
20
+ output?: NodeJS.WritableStream;
21
+ /** Logs go here only (default process.stderr), never to `output`. */
22
+ errorOutput?: { write(chunk: string | Uint8Array): unknown };
23
+ env?: Record<string, string | undefined>;
24
+ timeoutMs?: number;
25
+ allowInsecureHttp?: boolean;
26
+ }
27
+
28
+ export interface ProxyState {
29
+ onDrift: "block" | "warn";
30
+ /** Latest definition seen on this connection per tool: matches the pin, or not. */
31
+ observed: Map<string, "match" | "drift">;
32
+ checks: number;
33
+ lastCheck: "MATCH" | "CHANGED" | "UNCHECKED" | null;
34
+ blockedCalls: string[];
35
+ hostEra: "modern" | "legacy" | null;
36
+ }
37
+
38
+ export interface ProxyHandle {
39
+ /** Resolves with the exit code: 0 when the host closes stdin, 2 when the pin or upstream is unusable, 1 on usage errors. */
40
+ done: Promise<number>;
41
+ state: ProxyState | null;
42
+ close(): Promise<void>;
43
+ recheck?(reason: string): Promise<void>;
44
+ }
45
+
46
+ export function startProxy(options?: ProxyOptions): Promise<ProxyHandle>;
47
+ export function runProxy(options?: ProxyOptions): Promise<number>;
package/mcp/proxy.mjs ADDED
@@ -0,0 +1,434 @@
1
+ // `intentrax mcp proxy`: a stdio MCP proxy that enforces a tool pin (R1b).
2
+ //
3
+ // host (stdio) <-> proxy <-> upstream server (stdio command or Streamable HTTP)
4
+ //
5
+ // It forwards JSON-RPC both ways and:
6
+ // - re-checks the upstream tool list on connect (once the host's handshake
7
+ // is done, on the host's own session, so it sees what the host is sent)
8
+ // and on every `notifications/tools/list_changed`;
9
+ // - compares every `tools/list` response the HOST receives, tool by tool,
10
+ // against the pin. This is what defeats cloaking: the decision is made on
11
+ // the exact definitions the host is about to show its model;
12
+ // - onDrift "block": changed and new tools are removed from the host's
13
+ // `tools/list`, and `tools/call` to any tool whose latest observed
14
+ // definition is not the pinned one is refused with a clear JSON-RPC error.
15
+ // While a re-check is running, calls wait for it. If the tools cannot be
16
+ // listed, calls are refused (fail closed);
17
+ // - onDrift "warn": forwards everything unchanged and only logs.
18
+ //
19
+ // Logs go to stderr only (`errorOutput`), never to the protocol stream.
20
+ // Messages from the host are re-serialized after parsing, so the upstream sees
21
+ // exactly what the proxy evaluated (no duplicate-key smuggling).
22
+ //
23
+ // Covers tool definitions only. It does not show that the server's code or
24
+ // behaviour is unchanged.
25
+
26
+ import { randomBytes } from "node:crypto";
27
+ import { resolve } from "node:path";
28
+ import { createLineSplitter, describeServer, listAllTools, McpClientError, META_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION, openTransport, parseServerSpec } from "./client.mjs";
29
+ import { DEFAULT_PINS_PATH, EXIT_UNCHECKED, EXIT_USAGE, LIMITATION, loadPinnedServer, summarizeDiff } from "./commands.mjs";
30
+ import { diffToolManifests, toolDefinitionDigest } from "./tool-manifest.mjs";
31
+
32
+ export const PROXY_BLOCKED_CODE = -32090;
33
+ export const ON_DRIFT_MODES = Object.freeze(["block", "warn"]);
34
+ const DEFAULT_TIMEOUT_MS = 15_000;
35
+ const MAX_QUEUED_CALLS = 256;
36
+
37
+ function isPlainObject(value) {
38
+ return value !== null && typeof value === "object" && !Array.isArray(value);
39
+ }
40
+
41
+ function isResponse(message) {
42
+ return isPlainObject(message) && typeof message.method !== "string" && Object.hasOwn(message, "id") && (Object.hasOwn(message, "result") || Object.hasOwn(message, "error"));
43
+ }
44
+
45
+ function isRequest(message) {
46
+ return isPlainObject(message) && typeof message.method === "string" && Object.hasOwn(message, "id");
47
+ }
48
+
49
+ function idKey(id) {
50
+ return typeof id + ":" + String(id);
51
+ }
52
+
53
+ function safeDigest(tool) {
54
+ try {
55
+ return toolDefinitionDigest(tool);
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ // startProxy(options) -> { done: Promise<exitCode>, state, close() }
62
+ // options: { pins?, name?, server?, cwd?, onDrift?, input?, output?,
63
+ // errorOutput?, env?, timeoutMs?, allowInsecureHttp? }
64
+ export async function startProxy(options = {}) {
65
+ const input = options.input ?? process.stdin;
66
+ const output = options.output ?? process.stdout;
67
+ const errorOutput = options.errorOutput ?? process.stderr;
68
+ const onDrift = options.onDrift ?? "block";
69
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
70
+ const cwd = options.cwd ?? process.cwd();
71
+ const pinsPath = resolve(cwd, options.pins ?? DEFAULT_PINS_PATH);
72
+ const log = (line) => errorOutput.write("intentrax mcp proxy: " + line + "\n");
73
+ const finished = (exitCode) => ({ done: Promise.resolve(exitCode), state: null, close: async () => {} });
74
+
75
+ if (!ON_DRIFT_MODES.includes(onDrift)) {
76
+ log("USAGE --on-drift must be block or warn");
77
+ return finished(EXIT_USAGE);
78
+ }
79
+
80
+ let pinned = null;
81
+ try {
82
+ pinned = loadPinnedServer(pinsPath, options.name);
83
+ } catch (error) {
84
+ if (onDrift === "block") {
85
+ log("UNCHECKED cannot enforce a pin: " + error.message + " (refusing to start in block mode)");
86
+ return finished(EXIT_UNCHECKED);
87
+ }
88
+ log("WARN no usable pin (" + error.message + "); forwarding everything and logging every tool as unpinned");
89
+ }
90
+ const pinName = pinned?.name ?? options.name ?? "server";
91
+ let spec;
92
+ try {
93
+ spec = parseServerSpec(options.server ?? pinned?.spec);
94
+ } catch (error) {
95
+ log("USAGE " + (options.server === undefined && !pinned ? "--server is required without a pin" : error.message));
96
+ return finished(EXIT_USAGE);
97
+ }
98
+ const pinnedDigests = new Map((pinned?.entry.tools ?? []).map((tool) => [tool.name, tool.digest]));
99
+ const pinnedDefinitions = pinned?.definitions ?? [];
100
+
101
+ let transport;
102
+ try {
103
+ transport = await openTransport(spec, {
104
+ env: options.env ?? process.env,
105
+ timeoutMs,
106
+ allowInsecureHttp: options.allowInsecureHttp,
107
+ stderr: (chunk) => errorOutput.write(chunk),
108
+ });
109
+ } catch (error) {
110
+ log("UNCHECKED cannot start upstream " + describeServer(spec) + ": " + (error instanceof McpClientError ? error.message : "error"));
111
+ return finished(EXIT_UNCHECKED);
112
+ }
113
+ log("proxying " + describeServer(spec) + " with pin " + JSON.stringify(pinName) + " (on drift: " + onDrift + ")");
114
+
115
+ const state = {
116
+ onDrift,
117
+ observed: new Map(), // tool name -> "match" | "drift" (latest definition seen on this connection)
118
+ checks: 0,
119
+ lastCheck: null, // "MATCH" | "CHANGED" | "UNCHECKED"
120
+ blockedCalls: [],
121
+ hostEra: null, // "modern" | "legacy"
122
+ hostMeta: null,
123
+ legacyReady: false,
124
+ };
125
+
126
+ const ownPrefix = "intentrax-proxy-" + randomBytes(6).toString("hex") + "-";
127
+ let ownNext = 1;
128
+ const ownPending = new Map();
129
+ const hostToolsList = new Set();
130
+ let checking = null;
131
+ let rerun = false;
132
+ let closed = false;
133
+ let resolveDone;
134
+ const done = new Promise((resolveFn) => {
135
+ resolveDone = resolveFn;
136
+ });
137
+
138
+ const writeHost = (message) => {
139
+ if (!closed) output.write(JSON.stringify(message) + "\n");
140
+ };
141
+ const hostError = (id, code, message, data) => {
142
+ const error = { code, message };
143
+ if (data !== undefined) error.data = data;
144
+ writeHost({ jsonrpc: "2.0", id, error });
145
+ };
146
+
147
+ // The proxy's own requests on the shared upstream connection.
148
+ const ownClient = {
149
+ request(method, params = {}) {
150
+ const id = ownPrefix + ownNext++;
151
+ const body = { ...params };
152
+ if (state.hostEra === "modern" && state.hostMeta) body._meta = { ...state.hostMeta };
153
+ return new Promise((resolveFn, reject) => {
154
+ const timer = setTimeout(() => {
155
+ ownPending.delete(id);
156
+ reject(new McpClientError("timeout", method + " got no answer within " + timeoutMs + " ms"));
157
+ }, timeoutMs);
158
+ ownPending.set(id, { resolve: resolveFn, reject, timer, method });
159
+ transport.send({ jsonrpc: "2.0", id, method, params: body }).catch((error) => {
160
+ if (!ownPending.has(id)) return;
161
+ ownPending.delete(id);
162
+ clearTimeout(timer);
163
+ reject(error instanceof McpClientError ? error : new McpClientError("transport_closed", "could not send " + method));
164
+ });
165
+ });
166
+ },
167
+ };
168
+
169
+ function applyFullList(tools) {
170
+ const observed = new Map();
171
+ for (const tool of tools) {
172
+ const digest = safeDigest(tool);
173
+ observed.set(tool.name, digest !== null && pinnedDigests.get(tool.name) === digest ? "match" : "drift");
174
+ }
175
+ state.observed = observed;
176
+ }
177
+
178
+ // recheck(reason, after?) — `after` is a promise the check waits for first
179
+ // (the forwarded notifications/initialized), so it is registered at once and
180
+ // a tool call that arrives meanwhile waits for it.
181
+ function recheck(reason, after = undefined) {
182
+ if (checking) {
183
+ rerun = true;
184
+ return checking;
185
+ }
186
+ state.checks += 1;
187
+ checking = (async () => {
188
+ try {
189
+ if (after) await after;
190
+ const { tools, pages } = await listAllTools(ownClient, { timeoutMs });
191
+ applyFullList(tools);
192
+ let diff;
193
+ try {
194
+ diff = diffToolManifests(pinnedDefinitions, tools);
195
+ } catch (error) {
196
+ state.lastCheck = "UNCHECKED";
197
+ state.observed = new Map();
198
+ log("UNCHECKED " + pinName + " (" + reason + "): server tools cannot be hashed: " + error.message);
199
+ return;
200
+ }
201
+ if (diff.drift) {
202
+ state.lastCheck = "CHANGED";
203
+ log("CHANGED " + pinName + " (" + reason + "): " + summarizeDiff(diff) + (onDrift === "block" ? " [changed and new tools are blocked]" : " [warn only]"));
204
+ } else {
205
+ state.lastCheck = "MATCH";
206
+ log("MATCH " + pinName + " (" + reason + "): " + tools.length + " tools on " + pages + " page" + (pages === 1 ? "" : "s") + " match the pin");
207
+ }
208
+ } catch (error) {
209
+ state.lastCheck = "UNCHECKED";
210
+ // Fail closed: nothing counts as observed-matching until a list succeeds.
211
+ state.observed = new Map();
212
+ log("UNCHECKED " + pinName + " (" + reason + "): could not list tools: " + (error instanceof McpClientError ? error.message : "error") + (onDrift === "block" ? " [tool calls are refused until a list succeeds]" : ""));
213
+ }
214
+ })().finally(() => {
215
+ checking = null;
216
+ if (rerun && !closed) {
217
+ rerun = false;
218
+ recheck("tools changed during check");
219
+ }
220
+ });
221
+ return checking;
222
+ }
223
+
224
+ async function settled() {
225
+ while (checking) await checking;
226
+ }
227
+
228
+ function callVerdict(name) {
229
+ if (!pinnedDigests.has(name)) return { allowed: false, reason: "not_pinned", text: "it is not in the pin" };
230
+ // Fail closed: a host's tools/list page cannot vouch for a tool until the
231
+ // proxy's own complete (all pages) listing has succeeded.
232
+ // (Block mode always waits for a check, so lastCheck is never null there.)
233
+ if (state.lastCheck === "UNCHECKED") {
234
+ return { allowed: false, reason: "unchecked", text: "the server's complete tool list could not be checked against the pin" };
235
+ }
236
+ const seen = state.observed.get(name);
237
+ if (seen === "match") return { allowed: true };
238
+ if (seen === "drift") return { allowed: false, reason: "changed", text: "its definition changed since it was pinned" };
239
+ return { allowed: false, reason: "unchecked", text: "its current definition has not been checked against the pin" };
240
+ }
241
+
242
+ let queuedCalls = 0;
243
+ async function gateCall(message) {
244
+ const name = isPlainObject(message.params) && typeof message.params.name === "string" ? message.params.name : "";
245
+ if (onDrift === "block") {
246
+ if (queuedCalls >= MAX_QUEUED_CALLS) {
247
+ hostError(message.id, PROXY_BLOCKED_CODE, "Intentrax proxy: too many tool calls waiting for a tool check");
248
+ return;
249
+ }
250
+ queuedCalls += 1;
251
+ try {
252
+ if (state.checks === 0) recheck("first tool call");
253
+ await settled();
254
+ } finally {
255
+ queuedCalls -= 1;
256
+ }
257
+ }
258
+ const verdict = callVerdict(name);
259
+ if (verdict.allowed) {
260
+ forward(message);
261
+ return;
262
+ }
263
+ if (onDrift === "warn") {
264
+ log("WARN tools/call " + JSON.stringify(name) + ": " + verdict.text + "; forwarded (warn mode)");
265
+ forward(message);
266
+ return;
267
+ }
268
+ state.blockedCalls.push(name);
269
+ log("BLOCKED tools/call " + JSON.stringify(name) + ": " + verdict.text);
270
+ hostError(
271
+ message.id,
272
+ PROXY_BLOCKED_CODE,
273
+ "Intentrax proxy blocked tools/call " + JSON.stringify(name) + ": " + verdict.text + ". " +
274
+ "A person can review the change and re-pin it with: intentrax mcp pin --name " + pinName + " --accept " + name,
275
+ { intentrax: { reason: verdict.reason, tool: name, pin: pinName } },
276
+ );
277
+ }
278
+
279
+ function forward(message) {
280
+ transport.send(message).catch((error) => {
281
+ if (isRequest(message)) {
282
+ hostError(message.id, -32603, "Intentrax proxy: upstream unavailable (" + (error instanceof McpClientError ? error.message : "error") + ")");
283
+ }
284
+ });
285
+ }
286
+
287
+ function filterToolsList(message) {
288
+ if (!isPlainObject(message.result) || !Array.isArray(message.result.tools)) return message;
289
+ const kept = [];
290
+ const hidden = [];
291
+ for (const tool of message.result.tools) {
292
+ const name = isPlainObject(tool) && typeof tool.name === "string" ? tool.name : null;
293
+ const digest = name === null ? null : safeDigest(tool);
294
+ const matches = digest !== null && pinnedDigests.get(name) === digest;
295
+ if (name !== null) state.observed.set(name, matches ? "match" : "drift");
296
+ if (matches) kept.push(tool);
297
+ else hidden.push((name === null ? "(unnamed)" : JSON.stringify(name)) + (name !== null && pinnedDigests.has(name) ? " changed" : " new"));
298
+ }
299
+ if (hidden.length === 0) return message;
300
+ if (onDrift === "warn") {
301
+ log("WARN tools/list sent to the host includes tools that differ from the pin: " + hidden.join(", "));
302
+ return message;
303
+ }
304
+ log("BLOCKED tools/list: hid " + hidden.join(", "));
305
+ return { ...message, result: { ...message.result, tools: kept } };
306
+ }
307
+
308
+ function onHostMessage(message) {
309
+ if (Array.isArray(message)) {
310
+ hostError(null, -32600, "Intentrax proxy: JSON-RPC batches are not supported");
311
+ return;
312
+ }
313
+ if (!isPlainObject(message) || message.jsonrpc !== "2.0") {
314
+ hostError(null, -32600, "Intentrax proxy: invalid JSON-RPC message");
315
+ return;
316
+ }
317
+ const params = isPlainObject(message.params) ? message.params : null;
318
+ const meta = params && isPlainObject(params._meta) ? params._meta : null;
319
+ let connectCheck = false;
320
+ if (meta && meta[META_PROTOCOL_VERSION] === MODERN_PROTOCOL_VERSION) {
321
+ const first = state.hostEra !== "modern";
322
+ state.hostEra = "modern";
323
+ const { progressToken, ...rest } = meta; // never reuse a host progress token
324
+ state.hostMeta = rest;
325
+ // A tools/call as the first message is gated (and starts the check) below.
326
+ connectCheck = first && message.method !== "tools/call";
327
+ }
328
+ if (isRequest(message)) {
329
+ if (message.method === "tools/call") {
330
+ gateCall(message);
331
+ return;
332
+ }
333
+ // Registered before forwarding, so the response is filtered even when
334
+ // tools/list is a modern host's first message.
335
+ if (message.method === "tools/list") hostToolsList.add(idKey(message.id));
336
+ forward(message);
337
+ if (connectCheck) recheck("connect");
338
+ return;
339
+ }
340
+ if (connectCheck) {
341
+ forward(message);
342
+ recheck("connect");
343
+ return;
344
+ }
345
+ if (message.method === "notifications/initialized" && state.hostEra !== "modern") {
346
+ state.hostEra = "legacy";
347
+ state.legacyReady = true;
348
+ const sent = transport.send(message).catch(() => {});
349
+ recheck("connect", sent);
350
+ sent.then(() => transport.openNotificationStream?.());
351
+ return;
352
+ }
353
+ forward(message);
354
+ }
355
+
356
+ function onUpstreamMessage(message) {
357
+ if (Array.isArray(message)) {
358
+ for (const item of message) onUpstreamMessage(item);
359
+ return;
360
+ }
361
+ if (isResponse(message) && typeof message.id === "string" && message.id.startsWith(ownPrefix)) {
362
+ const entry = ownPending.get(message.id);
363
+ if (!entry) return;
364
+ ownPending.delete(message.id);
365
+ clearTimeout(entry.timer);
366
+ if (Object.hasOwn(message, "error")) {
367
+ const error = isPlainObject(message.error) ? message.error : {};
368
+ entry.reject(new McpClientError("rpc_error", entry.method + " failed: " + (Number.isInteger(error.code) ? error.code + " " : "") + String(error.message ?? "error").slice(0, 200)));
369
+ } else {
370
+ entry.resolve(message.result);
371
+ }
372
+ return;
373
+ }
374
+ if (isResponse(message)) {
375
+ const key = idKey(message.id);
376
+ if (hostToolsList.delete(key)) {
377
+ writeHost(filterToolsList(message));
378
+ return;
379
+ }
380
+ writeHost(message);
381
+ return;
382
+ }
383
+ if (isPlainObject(message) && message.method === "notifications/tools/list_changed") {
384
+ writeHost(message);
385
+ if (state.hostEra !== null) recheck("list_changed");
386
+ return;
387
+ }
388
+ writeHost(message);
389
+ }
390
+
391
+ transport.onmessage = onUpstreamMessage;
392
+ transport.onnoise = (kind) => log("ignored " + kind.replace(/_/g, " ") + " from the upstream server");
393
+
394
+ async function close(exitCode = 0) {
395
+ if (closed) return;
396
+ closed = true;
397
+ for (const entry of ownPending.values()) {
398
+ clearTimeout(entry.timer);
399
+ entry.reject(new McpClientError("transport_closed", "proxy closed"));
400
+ }
401
+ ownPending.clear();
402
+ await transport.close().catch(() => {});
403
+ log("stopped (" + state.checks + " check" + (state.checks === 1 ? "" : "s") + ", " + state.blockedCalls.length + " blocked call" + (state.blockedCalls.length === 1 ? "" : "s") + "). " + LIMITATION);
404
+ resolveDone(exitCode);
405
+ }
406
+
407
+ transport.onclose = (info) => {
408
+ if (closed) return;
409
+ const detail = info && info.code !== null && info.code !== undefined ? " (exit code " + info.code + ")" : "";
410
+ log("upstream closed" + detail);
411
+ close(info && info.code ? EXIT_UNCHECKED : 0);
412
+ };
413
+
414
+ const split = createLineSplitter((line) => {
415
+ let message;
416
+ try {
417
+ message = JSON.parse(line);
418
+ } catch {
419
+ hostError(null, -32700, "Intentrax proxy: parse error");
420
+ return;
421
+ }
422
+ onHostMessage(message);
423
+ }, { onOverflow: () => hostError(null, -32600, "Intentrax proxy: message too large") });
424
+ input.on("data", split);
425
+ input.on("end", () => close(0));
426
+ input.on("close", () => close(0));
427
+
428
+ return { done, state, close: () => close(0), recheck };
429
+ }
430
+
431
+ export async function runProxy(options = {}) {
432
+ const proxy = await startProxy(options);
433
+ return proxy.done;
434
+ }
@@ -0,0 +1,59 @@
1
+ // Types for receipt-meta.mjs: unauthenticated receipt references in
2
+ // CallToolResult._meta["com.intentrax/receipt"]. A reference is a claim to
3
+ // check, never evidence.
4
+
5
+ import type { JsonValue } from "./canonical.js";
6
+ import type { Digest } from "./tool-manifest.js";
7
+
8
+ export const RECEIPT_META_KEY: "com.intentrax/receipt";
9
+ export const RECEIPT_REF_SCHEMA: "intentrax.mcp.receipt_ref/0.1";
10
+ export const ARGUMENTS_DIGEST_DOMAIN: "INTENTRAX_MCP_TOOL_ARGUMENTS_V0_1";
11
+ export const DEFAULT_VERIFY_HOSTS: readonly string[];
12
+ export const RECEIPT_LIMITATIONS: readonly string[];
13
+
14
+ export interface ReceiptRef {
15
+ schema: typeof RECEIPT_REF_SCHEMA;
16
+ proof_id: string;
17
+ verify_url: string;
18
+ record_kind: "decision_record";
19
+ tool_name: string;
20
+ arguments_digest: Digest;
21
+ tool_manifest_digest?: Digest;
22
+ limitations: string[];
23
+ }
24
+
25
+ export interface CallToolResultLike {
26
+ content: Array<{ [key: string]: JsonValue }>;
27
+ structuredContent?: { [key: string]: JsonValue };
28
+ isError?: boolean;
29
+ _meta?: { [key: string]: JsonValue };
30
+ [key: string]: JsonValue | undefined;
31
+ }
32
+
33
+ export type ReadReceiptResult =
34
+ | { status: "ABSENT" }
35
+ | { status: "MALFORMED"; reasons: string[] }
36
+ | { status: "UNVERIFIED_REFERENCE"; ref: ReceiptRef };
37
+
38
+ export function argumentsDigest(args: { [key: string]: JsonValue }): Digest;
39
+
40
+ export function buildReceiptRef(options: {
41
+ proofId: string;
42
+ verifyUrl: string;
43
+ toolName: string;
44
+ args: { [key: string]: JsonValue };
45
+ toolManifestDigest?: Digest;
46
+ allowedHosts?: readonly string[];
47
+ }): ReceiptRef;
48
+
49
+ /** Returns a NEW result; never changes content, structuredContent or isError; refuses to overwrite a receipt. */
50
+ export function attachReceiptMeta<T extends CallToolResultLike>(result: T, ref: ReceiptRef, options?: { resourceLink?: boolean }): T;
51
+
52
+ /** Client side. Never returns a "verified" state. */
53
+ export function readReceiptMeta(result: unknown, options?: { allowedHosts?: readonly string[] }): ReadReceiptResult;
54
+
55
+ /** Cheap local consistency check against the call the client made. A match proves nothing on its own. */
56
+ export function matchReceiptToCall(ref: ReceiptRef, call: { toolName: string; args: { [key: string]: JsonValue } }): {
57
+ consistent: boolean;
58
+ mismatches: Array<"tool_name" | "arguments_digest">;
59
+ };