@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/README.md CHANGED
@@ -9,8 +9,8 @@ npm install @intentrax/sdk
9
9
  The package is public on npm (Apache-2.0). Everything below that says
10
10
  "offline" or "local" runs today with no API key: `init --dry-run`,
11
11
  `check-init`, `verify-proof` (sandbox sample proofs, including tampered ones,
12
- are bundled at `examples/sandbox/`), `verify-pdf-receipt`, and `sandbox` (the
13
- local assurance sandbox below). Live execution
12
+ are bundled at `examples/sandbox/`), `verify-pdf-receipt`, `sandbox` (the
13
+ local assurance sandbox below), `scan`, `readback` and `mcp`. Live execution
14
14
  keys and your sandbox base URL are issued after an architectural review at
15
15
  <https://www.intentrax.com/request-architectural-review>.
16
16
 
@@ -37,6 +37,21 @@ Public surfaces:
37
37
  own) and offline verification with ephemeral local keys, no account and no
38
38
  network. Verdicts are capped at `LOCAL_NON_TRUST_BEARING`: never production
39
39
  assurance. See [sandbox/README.md](sandbox/README.md) for the limitations.
40
+ - `intentrax scan [dir]` (1.8.0) lists the destructive or consequential actions
41
+ an agent can reach in a project and flags broad credentials, missing gates
42
+ and success reported without a read-back. Heuristic and static: nothing is
43
+ run or sent. See [scan/README.md](scan/README.md).
44
+ - `intentrax readback` and `@intentrax/sdk/readback` (1.8.0): `confirmThenReport`
45
+ reads the system of record with your read-only check before anyone reports
46
+ success (`CONFIRMED`, `CAUGHT …`, `PENDING`, `UNKNOWN`). Results are
47
+ `SELF_REPORTED`, not an Intentrax attestation. See
48
+ [readback/README.md](readback/README.md).
49
+ - `intentrax mcp pin|check|proxy` and `@intentrax/sdk/mcp` (1.8.0) pin a
50
+ third-party MCP server's tool definitions, report changes (exit 10,
51
+ `CHANGED …`) and block changed or new tools in a stdio proxy. Offline; tool
52
+ descriptions never leave your machine. Covers tool definitions only. It does
53
+ not show that the server's code or behaviour is unchanged. See
54
+ [mcp/README.md](mcp/README.md).
40
55
 
41
56
  The published package exports Node-runnable `.js` modules with `.d.ts` type
42
57
  declarations and is gated on Node 20 and Node 24.
package/cli/intentrax.mjs CHANGED
@@ -5,7 +5,7 @@ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
5
5
  import { pathToFileURL } from "node:url";
6
6
  import { buildAgentGatewayAdmissionEnvelope, buildLegacyVerificationAssessment, compilePolicyDocument, evaluateCompiledPolicy, policyReevaluationMismatches } from "../index.js";
7
7
 
8
- const VERSION = "1.7.0";
8
+ const VERSION = "1.8.0";
9
9
  const ADMISSION_SCHEMA_VERSION = "intentrax.runtime.agent_admission_request/1.0";
10
10
  const INIT_SCHEMA_VERSION = "intentrax.onboarding.agent_adapter_init/1.0";
11
11
  const ACTION_RECEIPT_SCHEMA_VERSION = "intentrax.onboarding.agent_adapter_action_receipt/1.0";
@@ -255,6 +255,24 @@ async function main(argv) {
255
255
  const { sandboxMain } = await import("../sandbox/cli.mjs");
256
256
  return sandboxMain([subject, ...rest].filter((value) => value !== undefined));
257
257
  }
258
+ if (command === "mcp") {
259
+ // MCP tool pinning: pin a server's tool definitions, check them, or proxy
260
+ // with --on-drift block. Offline; no Intentrax account. See mcp/README.md.
261
+ const { mcpMain } = await import("../mcp/cli.mjs");
262
+ return mcpMain([subject, ...rest].filter((value) => value !== undefined));
263
+ }
264
+ if (command === "readback") {
265
+ // Read the outcome back before reporting success (SELF_REPORTED; not an
266
+ // Intentrax attestation). See readback/README.md.
267
+ const { readbackMain } = await import("../readback/cli.mjs");
268
+ return readbackMain([subject, ...rest].filter((value) => value !== undefined));
269
+ }
270
+ if (command === "scan") {
271
+ // Static, report-only scan for agent actions an agent can reach (exit 0
272
+ // none, 20 findings, 2 error). Nothing is run or sent. See scan/README.md.
273
+ const { scanMain } = await import("../scan/cli.mjs");
274
+ return scanMain([subject, ...rest].filter((value) => value !== undefined));
275
+ }
258
276
  if (command === "check-init") {
259
277
  const options = parseCheckInitOptions([subject, ...rest].filter((value) => value !== undefined));
260
278
  const output = await checkInitCommand(options);
@@ -3000,6 +3018,11 @@ Usage:
3000
3018
  intentrax verify-pdf-receipt <receipt.pdf> --pdf-hash <X-Intentrax-PDF-Hash> [--json] [--report-out <file>]
3001
3019
  intentrax sandbox [--scenario confirmed|contradicted] [--check <read-only-check.mjs>] [--dir <dir>] [--json]
3002
3020
  intentrax sandbox verify <bundle.json> [--keys <local-key-set.json>] [--issuer-keys <pinned-external-issuers.json>] [--require-external-issuer <issuer>]... [--json]
3021
+ intentrax readback --check <read-only-check.mjs> --expected <json> [--claimed <json>] [--retries N] [--json]
3022
+ intentrax scan [dir] [--json] [--include-tests] [--max-files N]
3023
+ intentrax mcp pin --server <cmd|url> [--name <name>] [--accept <tool,...> | --replace] [--json]
3024
+ intentrax mcp check [--pins <file>] [--name <name>] [--json]
3025
+ intentrax mcp proxy [--pins <file>] [--name <name>] [--on-drift block|warn]
3003
3026
 
3004
3027
  Adapters:
3005
3028
  ${Object.keys(ADAPTERS).join(", ")}
@@ -3063,6 +3086,23 @@ Proof export verification:
3063
3086
  Add more sets, for example revocations, with --trusted-keys <file>
3064
3087
  (repeatable).
3065
3088
 
3089
+ Read-back (intentrax readback --help):
3090
+ Reads the system of record with your read-only check before anyone reports
3091
+ success. 0 CONFIRMED, 12 CONTRADICTED (CAUGHT), 10 PENDING, 11 UNKNOWN,
3092
+ 64 usage. SELF_REPORTED: not an Intentrax attestation.
3093
+
3094
+ Scan (intentrax scan --help):
3095
+ Lists the destructive or consequential actions an AI agent can reach in a
3096
+ project and flags broad credentials (EXPOSED), missing gates (UNGATED) and
3097
+ success reported without a read-back (SELF-REPORTED). Heuristic and static:
3098
+ nothing is run or sent. 0 no findings, 20 findings, 2 error.
3099
+
3100
+ MCP tool pinning (intentrax mcp --help):
3101
+ pin records a server's tool definitions in .intentrax/mcp-pins.json; check
3102
+ compares them (0 MATCH, 10 CHANGED, 2 UNCHECKED, 1 usage); proxy blocks
3103
+ changed and new tools in a stdio proxy. Covers tool definitions only. It
3104
+ does not show that the server's code or behaviour is unchanged.
3105
+
3066
3106
  PDF receipt verification:
3067
3107
  verify-pdf-receipt reads downloaded PDF receipt bytes, checks the PDF header,
3068
3108
  recomputes SHA-256, and compares it with the X-Intentrax-PDF-Hash response
@@ -3086,6 +3126,10 @@ Examples:
3086
3126
  intentrax sandbox
3087
3127
  intentrax sandbox --scenario contradicted
3088
3128
  intentrax sandbox --check ./my-check.mjs
3129
+ intentrax readback --check ./read-refund.mjs --expected '{"status":"succeeded"}' --claimed '{"status":"processed"}'
3130
+ intentrax scan .
3131
+ intentrax mcp pin --name github --server https://api.example.com/mcp --header 'Authorization: Bearer \${GITHUB_TOKEN}'
3132
+ intentrax mcp check
3089
3133
  `);
3090
3134
  }
3091
3135
 
package/mcp/README.md ADDED
@@ -0,0 +1,138 @@
1
+ # `@intentrax/sdk/mcp`: "A tool you approved changed" (R1b)
2
+
3
+ Pins the tool definitions of a third-party MCP server and catches changes made after you approved them: rug pulls, rewritten descriptions, widened schemas, and annotations flipped to look safer. It also blocks those changes in a proxy.
4
+
5
+ Everything runs **offline and in private**. It needs no Intentrax account or token. Tool descriptions never leave your machine.
6
+
7
+ > Covers tool definitions only. It does not show that the server's code or behaviour is unchanged.
8
+
9
+ **Status:** shipped in `@intentrax/sdk` 1.8.0 as `intentrax mcp pin|check|proxy` and the
10
+ `@intentrax/sdk/mcp` subpath export (with types). Run `npx @intentrax/sdk mcp --help`.
11
+
12
+ ## Commands
13
+
14
+ ```
15
+ intentrax mcp pin --server <cmd|url> [--name <name>] [--out .intentrax/mcp-pins.json]
16
+ intentrax mcp pin --name <name> --accept <tool,...> # re-pin named tools on purpose
17
+ intentrax mcp pin --name <name> --replace # re-pin everything
18
+ intentrax mcp check [--pins .intentrax/mcp-pins.json] [--name <name>] [--json]
19
+ intentrax mcp proxy [--pins ...] [--name <name>] [--on-drift block|warn]
20
+ ```
21
+
22
+ Server options:
23
+ - `--server <cmd|url>` takes a command line or an MCP URL; `-- <command> [args...]` gives a stdio server as argv instead.
24
+ - `--header "Name: value"` (HTTP) and `--env KEY=value` (stdio) are repeatable. Put credentials in `${ENV_VAR}` placeholders, for example `--header 'Authorization: Bearer ${GITHUB_TOKEN}'` (single quotes, so a POSIX shell does not expand it; Intentrax expands it when connecting).
25
+ - `--registry-name` records the MCP Registry name with the pin; `--timeout-ms` sets the per-request timeout (default 15000).
26
+
27
+ In a host's MCP config, run the proxy in place of the server:
28
+
29
+ ```json
30
+ { "command": "npx", "args": ["-y", "@intentrax/sdk", "mcp", "proxy", "--name", "github"] }
31
+ ```
32
+
33
+ ### `check` exit codes
34
+
35
+ | Exit | Result | Meaning |
36
+ | --- | --- | --- |
37
+ | 0 | `MATCH` | Every pinned server's tools match its pin. |
38
+ | 10 | `CHANGED` | Drift. The first line starts with `CHANGED` and lists, for each tool, the change categories and any annotation weakening (e.g. `readOnlyHint became true`). |
39
+ | 2 | `UNCHECKED` | The check failed closed. The tools couldn't be listed (timeout, exit, HTTP error, a failing or looping page), or the pin file is missing, invalid or hand-edited. |
40
+ | 1 | `USAGE` | Bad arguments. |
41
+
42
+ **Several servers:**
43
+ - When drift and an unreachable server occur together, the exit code is 10.
44
+ - Both cases are non-zero.
45
+
46
+ **Every report:**
47
+ - includes the cloaking note;
48
+ - ends with the fixed limitation line.
49
+
50
+ ### `pin`
51
+
52
+ - **A first pin follows every `nextCursor`.** A partial list is an error and writes nothing.
53
+ - **Re-running `pin` on a changed server:**
54
+ - refuses to overwrite and exits 10;
55
+ - `--accept` re-pins only the tools you name: changed, new or removed;
56
+ - every other tool keeps its pinned definition.
57
+ - **Credentials are never stored.** Literal values in sensitive headers, env entries, URL query parameters or URL user-info are refused. Use `${ENV_VAR}` placeholders. They are expanded only when connecting and never logged.
58
+
59
+ ### `proxy`
60
+
61
+ A stdio proxy that sits between the host and the server. The server can be a stdio command or Streamable HTTP. The proxy:
62
+
63
+ - **Re-checks on connect and on `notifications/tools/list_changed`.** It runs on the host's own session.
64
+ - **Compares every `tools/list` response the host receives, tool by tool.** This is what defeats cloaking. `check` cannot do it, because it only sees what its own client is sent.
65
+ - **With `--on-drift block` (the default):**
66
+ - changed and new tools are removed from `tools/list`;
67
+ - `tools/call` to them is refused with JSON-RPC error `-32090`, which explains how to re-pin;
68
+ - calls wait while a re-check runs;
69
+ - if the tools cannot be listed, calls are refused.
70
+ - **With `--on-drift warn`:** it forwards everything and only logs.
71
+ - **Logs go to stderr only.** The protocol stream stays pure JSON-RPC.
72
+
73
+ ## Pin file: `.intentrax/mcp-pins.json` (`intentrax.mcp.pin/0.1`, unsigned)
74
+
75
+ ```json
76
+ {
77
+ "schema": "intentrax.mcp.pin/0.1",
78
+ "note": "Unsigned v0.1 pin file: ...",
79
+ "servers": {
80
+ "github": {
81
+ "profile": "intentrax.mcp.tool_manifest/0.1",
82
+ "server": { "registry_name": "com.example/github", "transport": "streamable-http",
83
+ "url": "https://…", "headers": { "Authorization": "Bearer ${GITHUB_TOKEN}" },
84
+ "server_info": { "name": "…", "version": "…" } },
85
+ "protocol_version": "2026-07-28",
86
+ "manifest_digest": "sha256:…",
87
+ "tools": [{ "name": "…", "digest": "sha256:…", "definition": { "name": "…", "…": "…" } }],
88
+ "pinned_at": "2026-11-19T12:00:00Z",
89
+ "pinned_by": "local"
90
+ }
91
+ }
92
+ }
93
+ ```
94
+
95
+ **How it relates to assessment §5.A:**
96
+ - The fields are the §5.A fields.
97
+ - Each tool also keeps its normalized definition, so `check` can say *which* fields changed.
98
+ - On load, every definition is re-hashed. A hand-edited entry is reported as inconsistent (exit 2), never trusted.
99
+ - The digests are the prototype's rules, unchanged:
100
+ - `INTENTRAX_MCP_TOOL_DEFINITION_V0_1`;
101
+ - `INTENTRAX_MCP_TOOL_MANIFEST_V0_1`;
102
+ - RFC 8785 canonical JSON;
103
+ - `_meta` is excluded.
104
+
105
+ ## Protocol support
106
+
107
+ **2026-07-28 (stateless):**
108
+ - `server/discover` first, with `_meta` on every request.
109
+ - Over HTTP, the `MCP-Protocol-Version`, `Mcp-Method` and `Mcp-Name` headers are set.
110
+
111
+ **Fallback to legacy `initialize`:** for 2025-11-25, 2025-06-18 and 2025-03-26.
112
+ - The fallback is used if discover is refused, times out, or the process dies on it. In that last case, the process is restarted once.
113
+ - 2024-11-05 is not accepted (fail closed).
114
+
115
+ **Streamable HTTP:**
116
+ - JSON and SSE responses;
117
+ - `Mcp-Session-Id`;
118
+ - a GET notification stream (the proxy uses it for `list_changed`).
119
+
120
+ **Not covered:**
121
+ - 2026-07-28 `subscriptions/listen` is forwarded by the proxy but not opened by it.
122
+ - Batches are refused by the proxy.
123
+
124
+ ## Modules
125
+
126
+ | File | Purpose |
127
+ | --- | --- |
128
+ | `canonical.mjs`, `tool-manifest.mjs`, `receipt-meta.mjs` | Ported from `examples/mcp-trust-receipts/src/`, with the same behaviour and profile strings. |
129
+ | `client.mjs` | Minimal MCP client: stdio and Streamable HTTP transports, discover/initialize, `tools/list` pagination, timeouts. |
130
+ | `commands.mjs` | `pin`, `check`: pure functions returning `{ exitCode, result, lines, report }`. |
131
+ | `proxy.mjs` | `startProxy` / `runProxy`. |
132
+ | `index.mjs` | Barrel for the future `@intentrax/sdk/mcp` export. |
133
+
134
+ ## Tests
135
+
136
+ ```bash
137
+ cd sdk/typescript/mcp && node --test test/*.test.mjs
138
+ ```
@@ -0,0 +1,12 @@
1
+ // Types for canonical.mjs: RFC 8785 canonical JSON and domain-separated SHA-256.
2
+
3
+ export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue };
4
+
5
+ /** RFC 8785 canonical JSON. Throws on NaN, Infinity, undefined members, non-plain objects, bigint. */
6
+ export function canonicalJson(value: JsonValue): string;
7
+
8
+ /** Lower-case hex SHA-256 of a string or bytes. */
9
+ export function sha256Hex(data: string | Uint8Array): string;
10
+
11
+ /** "sha256:" + hex(SHA-256(domain || canonicalJson(value))). */
12
+ export function domainDigest(domain: string, value: JsonValue): `sha256:${string}`;
@@ -0,0 +1,70 @@
1
+ // Canonical JSON for MCP tool manifests (RFC 8785 / JCS profile).
2
+ //
3
+ // The SDK's `canonicalJson` (sdk/typescript/index.ts) accepts integers only,
4
+ // because every Intentrax-signed structure is integer-only. MCP tool
5
+ // definitions are third-party JSON Schema and routinely carry non-integer
6
+ // numbers (`"minimum": 0.5`), so this module uses the full RFC 8785 rule
7
+ // instead (this file is ported unchanged in behaviour from
8
+ // examples/mcp-trust-receipts/src/canonical.mjs):
9
+ // - object keys sorted by UTF-16 code unit (JS default sort);
10
+ // - no insignificant whitespace;
11
+ // - strings via JSON.stringify (ES2019 well-formed escaping);
12
+ // - numbers via the ECMAScript Number-to-String rule (JSON.stringify),
13
+ // which is exactly the RFC 8785 number serialization; -0 becomes 0;
14
+ // - NaN, Infinity, undefined, functions, symbols, bigint and non-plain
15
+ // objects are rejected (fail closed: an unhashable manifest is an error,
16
+ // never a silent partial digest).
17
+ //
18
+ // For integer-only input this produces the same bytes as the SDK rule.
19
+
20
+ import { createHash } from "node:crypto";
21
+
22
+ export function canonicalJson(value) {
23
+ if (value === null) {
24
+ return "null";
25
+ }
26
+ if (Array.isArray(value)) {
27
+ return "[" + value.map((item) => canonicalJson(item)).join(",") + "]";
28
+ }
29
+ switch (typeof value) {
30
+ case "string":
31
+ return JSON.stringify(value);
32
+ case "boolean":
33
+ return value ? "true" : "false";
34
+ case "number":
35
+ if (!Number.isFinite(value)) {
36
+ throw new Error("canonical_json: non-finite number");
37
+ }
38
+ return JSON.stringify(value === 0 ? 0 : value);
39
+ case "object": {
40
+ const proto = Object.getPrototypeOf(value);
41
+ if (proto !== Object.prototype && proto !== null) {
42
+ throw new Error("canonical_json: only plain objects are allowed");
43
+ }
44
+ return "{" + Object.keys(value).sort().map((key) => {
45
+ const member = value[key];
46
+ if (member === undefined) {
47
+ throw new Error("canonical_json: undefined member " + JSON.stringify(key));
48
+ }
49
+ return JSON.stringify(key) + ":" + canonicalJson(member);
50
+ }).join(",") + "}";
51
+ }
52
+ default:
53
+ throw new Error("canonical_json: unsupported value of type " + typeof value);
54
+ }
55
+ }
56
+
57
+ export function sha256Hex(data) {
58
+ return createHash("sha256").update(data).digest("hex");
59
+ }
60
+
61
+ // Domain-separated digest: sha256(domain || canonical_json(value)), returned
62
+ // as "sha256:<hex>". The domain string stops a digest computed for one
63
+ // purpose being replayed as another (same pattern as the SDK's
64
+ // *_HASH_DOMAIN constants).
65
+ export function domainDigest(domain, value) {
66
+ if (typeof domain !== "string" || domain.length === 0) {
67
+ throw new Error("domain_digest: domain is required");
68
+ }
69
+ return "sha256:" + sha256Hex(Buffer.from(domain + canonicalJson(value), "utf8"));
70
+ }
package/mcp/cli.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ /** `intentrax mcp pin|check|proxy`. Resolves to the exit code (0 match, 10 drift, 2 unchecked, 1 usage). */
2
+ export function mcpMain(
3
+ argv?: string[],
4
+ io?: {
5
+ out?: (text: string) => unknown;
6
+ err?: (text: string) => unknown;
7
+ cwd?: string;
8
+ env?: Record<string, string | undefined>;
9
+ invokedAs?: string;
10
+ input?: NodeJS.ReadableStream;
11
+ output?: NodeJS.WritableStream;
12
+ errorOutput?: { write(chunk: string | Uint8Array): unknown };
13
+ },
14
+ ): Promise<number>;
15
+ export function parseMcpArgs(argv: string[]): { sub: "pin" | "check" | "proxy" | "help"; opts: Record<string, unknown> };
16
+ export function usage(invokedAs?: string): string;
package/mcp/cli.mjs ADDED
@@ -0,0 +1,214 @@
1
+ // `intentrax mcp pin|check|proxy`: the command-line front end for the R1b
2
+ // tool-pinning functions in commands.mjs and proxy.mjs.
3
+ //
4
+ // Exit codes (from commands.mjs): 0 match / pinned, 10 drift (CHANGED),
5
+ // 2 could not check (fail closed), 1 usage.
6
+ //
7
+ // `proxy` keeps stdout for JSON-RPC only; every log line goes to stderr.
8
+
9
+ import { EXIT_USAGE, check, pin } from "./commands.mjs";
10
+ import { ON_DRIFT_MODES, runProxy } from "./proxy.mjs";
11
+
12
+ const VALUE_FLAGS = new Map([
13
+ ["--server", "server"],
14
+ ["--name", "name"],
15
+ ["--out", "out"],
16
+ ["--pins", "pins"],
17
+ ["--accept", "accept"],
18
+ ["--registry-name", "registryName"],
19
+ ["--timeout-ms", "timeoutMs"],
20
+ ["--on-drift", "onDrift"],
21
+ ]);
22
+ const REPEAT_FLAGS = new Map([
23
+ ["--header", "headers"],
24
+ ["--env", "env"],
25
+ ]);
26
+ const BOOL_FLAGS = new Map([
27
+ ["--replace", "replace"],
28
+ ["--json", "json"],
29
+ ["--help", "help"],
30
+ ["-h", "help"],
31
+ ]);
32
+ const ALLOWED = {
33
+ pin: new Set(["server", "name", "out", "accept", "registryName", "timeoutMs", "headers", "env", "replace", "json", "command"]),
34
+ check: new Set(["server", "name", "pins", "timeoutMs", "headers", "env", "json", "command"]),
35
+ proxy: new Set(["server", "name", "pins", "timeoutMs", "headers", "env", "onDrift", "command"]),
36
+ };
37
+ const FLAG_NAME = {
38
+ server: "--server", name: "--name", out: "--out", pins: "--pins", accept: "--accept", registryName: "--registry-name",
39
+ timeoutMs: "--timeout-ms", onDrift: "--on-drift", headers: "--header", env: "--env", replace: "--replace", json: "--json",
40
+ command: "-- <command>",
41
+ };
42
+
43
+ class UsageError extends Error {}
44
+
45
+ export function usage(invokedAs = "intentrax mcp") {
46
+ return `Usage:
47
+ ${invokedAs} pin --server <cmd|url> [--name <name>] [--out .intentrax/mcp-pins.json] [--json]
48
+ ${invokedAs} pin --name <name> -- <command> [args...] (stdio server given as argv)
49
+ ${invokedAs} pin --name <name> --accept <tool,...> re-pin the named tools on purpose
50
+ ${invokedAs} pin --name <name> --replace re-pin everything
51
+ ${invokedAs} check [--pins .intentrax/mcp-pins.json] [--name <name>] [--json]
52
+ ${invokedAs} proxy [--pins .intentrax/mcp-pins.json] [--name <name>] [--on-drift block|warn]
53
+
54
+ Server options (pin; check/proxy use the pinned server unless given):
55
+ --server <cmd|url> a command line, or an https:// (or loopback http://) MCP URL
56
+ --header 'Name: value' HTTP header (repeatable); put credentials in '\${ENV_VAR}' placeholders
57
+ --env KEY=value stdio environment entry (repeatable); \${ENV_VAR} placeholders too
58
+ --registry-name <name> MCP Registry name to record with the pin (pin only)
59
+ --timeout-ms <ms> per-request timeout (default 15000)
60
+
61
+ Credentials are never stored: a literal secret in a header, env entry or URL
62
+ is refused. Placeholders are expanded only when connecting, never logged.
63
+
64
+ check exit codes:
65
+ 0 MATCH every pinned server's tools match the pin
66
+ 10 CHANGED a tool definition changed, was added or removed (line 1 lists them)
67
+ 2 UNCHECKED the tools could not be listed, or the pin file is missing or invalid
68
+ 1 USAGE bad arguments
69
+
70
+ proxy is a stdio MCP proxy for your host's config. --on-drift block (default)
71
+ hides changed and new tools and refuses calls to them (JSON-RPC error -32090);
72
+ warn forwards everything and only logs to stderr.
73
+
74
+ Covers tool definitions only. It does not show that the server's code or behaviour is unchanged.`;
75
+ }
76
+
77
+ export function parseMcpArgs(argv) {
78
+ const [sub, ...rest] = argv;
79
+ if (sub === undefined || sub === "--help" || sub === "-h" || sub === "help") return { sub: "help", opts: {} };
80
+ if (!Object.hasOwn(ALLOWED, sub)) throw new UsageError(`unknown subcommand ${JSON.stringify(sub)} (expected pin, check or proxy)`);
81
+ const opts = {};
82
+ for (let i = 0; i < rest.length; i++) {
83
+ const arg = rest[i];
84
+ if (arg === "--") {
85
+ const command = rest.slice(i + 1);
86
+ if (command.length === 0) throw new UsageError("-- must be followed by a command");
87
+ opts.command = command;
88
+ break;
89
+ }
90
+ const eq = arg.startsWith("--") ? arg.indexOf("=") : -1;
91
+ const flag = eq > 0 ? arg.slice(0, eq) : arg;
92
+ const inline = eq > 0 ? arg.slice(eq + 1) : undefined;
93
+ const takeValue = () => {
94
+ if (inline !== undefined) return inline;
95
+ const value = rest[i + 1];
96
+ if (value === undefined || (value.startsWith("-") && value !== "-")) throw new UsageError(`${flag} requires a value`);
97
+ i += 1;
98
+ return value;
99
+ };
100
+ if (BOOL_FLAGS.has(flag)) {
101
+ if (inline !== undefined) throw new UsageError(`${flag} takes no value`);
102
+ opts[BOOL_FLAGS.get(flag)] = true;
103
+ } else if (VALUE_FLAGS.has(flag)) {
104
+ const key = VALUE_FLAGS.get(flag);
105
+ if (Object.hasOwn(opts, key)) throw new UsageError(`${flag} given twice`);
106
+ opts[key] = takeValue();
107
+ } else if (REPEAT_FLAGS.has(flag)) {
108
+ const key = REPEAT_FLAGS.get(flag);
109
+ (opts[key] ??= []).push(takeValue());
110
+ } else {
111
+ throw new UsageError(arg.startsWith("-") ? `unknown option ${arg}` : `unexpected argument ${JSON.stringify(arg)}`);
112
+ }
113
+ }
114
+ if (opts.help) return { sub: "help", opts: {} };
115
+ for (const key of Object.keys(opts)) {
116
+ if (!ALLOWED[sub].has(key)) throw new UsageError(`${FLAG_NAME[key]} is not an option of ${sub}`);
117
+ }
118
+ return { sub, opts: normalize(sub, opts) };
119
+ }
120
+
121
+ function normalize(sub, opts) {
122
+ const out = {};
123
+ for (const key of ["name", "out", "pins", "registryName"]) if (opts[key] !== undefined) out[key] = opts[key];
124
+ if (opts.timeoutMs !== undefined) {
125
+ const n = Number(opts.timeoutMs);
126
+ if (!/^\d+$/.test(opts.timeoutMs) || !Number.isSafeInteger(n) || n < 1 || n > 600000) {
127
+ throw new UsageError("--timeout-ms must be an integer from 1 to 600000");
128
+ }
129
+ out.timeoutMs = n;
130
+ }
131
+ if (opts.onDrift !== undefined) {
132
+ if (!ON_DRIFT_MODES.includes(opts.onDrift)) throw new UsageError("--on-drift must be block or warn");
133
+ out.onDrift = opts.onDrift;
134
+ }
135
+ if (opts.accept !== undefined) {
136
+ const names = opts.accept.split(",").map((s) => s.trim()).filter((s) => s !== "");
137
+ if (names.length === 0) throw new UsageError("--accept needs at least one tool name");
138
+ out.accept = names;
139
+ }
140
+ if (opts.replace) out.replace = true;
141
+ if (opts.json) out.json = true;
142
+ if (opts.server !== undefined && opts.command !== undefined) throw new UsageError("give --server or -- <command>, not both");
143
+ const base = opts.command ?? opts.server;
144
+ if (opts.headers !== undefined || opts.env !== undefined) {
145
+ if (base === undefined) throw new UsageError("--header and --env need --server (or -- <command>)");
146
+ }
147
+ if (base !== undefined) out.server = buildServer(base, opts.headers, opts.env);
148
+ return out;
149
+ }
150
+
151
+ function buildServer(base, headers, env) {
152
+ const isUrl = typeof base === "string" && /^https?:\/\//i.test(base.trim());
153
+ if (headers === undefined && env === undefined) return base;
154
+ if (isUrl) {
155
+ if (env !== undefined) throw new UsageError("--env applies to stdio servers; use --header for an HTTP server");
156
+ return { transport: "streamable-http", url: base.trim(), headers: pairs(headers, ":", "--header", "Name: value") };
157
+ }
158
+ if (headers !== undefined) throw new UsageError("--header applies to HTTP servers; use --env for a stdio server");
159
+ return { transport: "stdio", command: base, env: pairs(env, "=", "--env", "KEY=value") };
160
+ }
161
+
162
+ function pairs(list, sep, flag, shape) {
163
+ const map = {};
164
+ for (const item of list) {
165
+ const at = item.indexOf(sep);
166
+ const key = at > 0 ? item.slice(0, at).trim() : "";
167
+ if (key === "") throw new UsageError(`${flag} must look like "${shape}"`);
168
+ if (Object.hasOwn(map, key)) throw new UsageError(`${flag} ${key} given twice`);
169
+ map[key] = item.slice(at + 1).trim();
170
+ }
171
+ return map;
172
+ }
173
+
174
+ /**
175
+ * Run `intentrax mcp ...`. Resolves to the exit code.
176
+ * io: { out, err, cwd, env, invokedAs, input, output } (defaults: process streams).
177
+ */
178
+ export async function mcpMain(argv = [], io = {}) {
179
+ const out = io.out ?? ((text) => process.stdout.write(text));
180
+ const err = io.err ?? ((text) => process.stderr.write(text));
181
+ const invokedAs = io.invokedAs ?? "intentrax mcp";
182
+ let parsed;
183
+ try {
184
+ parsed = parseMcpArgs(argv);
185
+ } catch (error) {
186
+ if (!(error instanceof UsageError)) throw error;
187
+ err(`intentrax mcp: ${error.message}\n\n${usage(invokedAs)}\n`);
188
+ return EXIT_USAGE;
189
+ }
190
+ const { sub, opts } = parsed;
191
+ if (sub === "help") {
192
+ out(usage(invokedAs) + "\n");
193
+ return 0;
194
+ }
195
+ const base = { cwd: io.cwd ?? process.cwd(), env: io.env ?? process.env };
196
+ if (sub === "proxy") {
197
+ // stdout belongs to JSON-RPC; startProxy logs to stderr only.
198
+ return runProxy({
199
+ ...base,
200
+ pins: opts.pins,
201
+ name: opts.name,
202
+ server: opts.server,
203
+ onDrift: opts.onDrift,
204
+ timeoutMs: opts.timeoutMs,
205
+ ...(io.input ? { input: io.input } : {}),
206
+ ...(io.output ? { output: io.output } : {}),
207
+ ...(io.errorOutput ? { errorOutput: io.errorOutput } : {}),
208
+ });
209
+ }
210
+ const { json, ...fnOpts } = opts;
211
+ const result = sub === "pin" ? await pin({ ...base, ...fnOpts }) : await check({ ...base, ...fnOpts });
212
+ out((json ? JSON.stringify(result.report, null, 2) : result.lines.join("\n")) + "\n");
213
+ return result.exitCode;
214
+ }