@intentrax/sdk 1.6.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 (62) hide show
  1. package/README.md +56 -3
  2. package/cli/intentrax.mjs +57 -1
  3. package/index.js +4 -2
  4. package/index.ts +4 -2
  5. package/mcp/README.md +138 -0
  6. package/mcp/canonical.d.ts +12 -0
  7. package/mcp/canonical.mjs +70 -0
  8. package/mcp/cli.d.ts +16 -0
  9. package/mcp/cli.mjs +214 -0
  10. package/mcp/client.d.ts +131 -0
  11. package/mcp/client.mjs +955 -0
  12. package/mcp/commands.d.ts +113 -0
  13. package/mcp/commands.mjs +575 -0
  14. package/mcp/index.d.ts +12 -0
  15. package/mcp/index.mjs +12 -0
  16. package/mcp/proxy.d.ts +47 -0
  17. package/mcp/proxy.mjs +434 -0
  18. package/mcp/receipt-meta.d.ts +59 -0
  19. package/mcp/receipt-meta.mjs +178 -0
  20. package/mcp/tool-manifest.d.ts +74 -0
  21. package/mcp/tool-manifest.mjs +154 -0
  22. package/package.json +19 -1
  23. package/readback/README.md +352 -0
  24. package/readback/bridge.mjs +71 -0
  25. package/readback/cli.mjs +150 -0
  26. package/readback/confirm.mjs +404 -0
  27. package/readback/index.mjs +12 -0
  28. package/readback/recipe-worker.mjs +33 -0
  29. package/readback/recipes/_shared.mjs +126 -0
  30. package/readback/recipes/email-delivery.mjs +136 -0
  31. package/readback/recipes/github-issue.mjs +88 -0
  32. package/readback/recipes/http-json.mjs +109 -0
  33. package/readback/recipes/sql-row.mjs +96 -0
  34. package/readback/recipes/stripe-refund.mjs +73 -0
  35. package/readback/redact.mjs +68 -0
  36. package/sandbox/README.md +255 -0
  37. package/sandbox/authority.mjs +66 -0
  38. package/sandbox/bundle.mjs +93 -0
  39. package/sandbox/canonical.mjs +64 -0
  40. package/sandbox/check-runner.mjs +50 -0
  41. package/sandbox/check-worker.mjs +30 -0
  42. package/sandbox/cli.mjs +376 -0
  43. package/sandbox/effect-verifier.mjs +242 -0
  44. package/sandbox/effects.mjs +80 -0
  45. package/sandbox/envelope.mjs +174 -0
  46. package/sandbox/examples/read-only-check.example.mjs +32 -0
  47. package/sandbox/external-decision.mjs +364 -0
  48. package/sandbox/keys.mjs +179 -0
  49. package/sandbox/model.mjs +170 -0
  50. package/sandbox/run.mjs +324 -0
  51. package/sandbox/time.mjs +18 -0
  52. package/sandbox/verifier.mjs +503 -0
  53. package/scan/README.md +211 -0
  54. package/scan/classify.mjs +276 -0
  55. package/scan/cli.mjs +102 -0
  56. package/scan/configs.mjs +261 -0
  57. package/scan/credentials.mjs +121 -0
  58. package/scan/extract.mjs +323 -0
  59. package/scan/gates.mjs +94 -0
  60. package/scan/report.mjs +58 -0
  61. package/scan/scan.mjs +571 -0
  62. package/scan/text.mjs +186 -0
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
+ }
@@ -0,0 +1,131 @@
1
+ // Types for client.mjs: the minimal, dependency-free MCP client used by
2
+ // `intentrax mcp pin|check|proxy`.
3
+
4
+ import type { McpToolDefinition } from "./tool-manifest.js";
5
+
6
+ export const MODERN_PROTOCOL_VERSION: "2026-07-28";
7
+ export const LEGACY_PROTOCOL_VERSIONS: readonly ["2025-11-25", "2025-06-18", "2025-03-26"];
8
+ export const SUPPORTED_PROTOCOL_VERSIONS: readonly ["2026-07-28", "2025-11-25", "2025-06-18", "2025-03-26"];
9
+ export type ProtocolVersion = (typeof SUPPORTED_PROTOCOL_VERSIONS)[number];
10
+ export const DEFAULT_TIMEOUT_MS: number;
11
+ export const DEFAULT_DISCOVER_TIMEOUT_MS: number;
12
+ export const DEFAULT_MAX_PAGES: number;
13
+ export const MAX_MESSAGE_BYTES: number;
14
+ export const CLIENT_INFO: Readonly<{ name: string; version: string }>;
15
+ export const META_PROTOCOL_VERSION: "io.modelcontextprotocol/protocolVersion";
16
+ export const META_CLIENT_CAPABILITIES: "io.modelcontextprotocol/clientCapabilities";
17
+ export const META_CLIENT_INFO: "io.modelcontextprotocol/clientInfo";
18
+ export const META_SERVER_INFO: "io.modelcontextprotocol/serverInfo";
19
+
20
+ export type McpClientErrorCode =
21
+ | "invalid_spec"
22
+ | "env_missing"
23
+ | "spawn_failed"
24
+ | "transport_closed"
25
+ | "unreachable"
26
+ | "timeout"
27
+ | "http_status"
28
+ | "protocol"
29
+ | "pagination"
30
+ | "rpc_error"
31
+ | "unsupported_version";
32
+
33
+ /** Messages never contain expanded ${ENV} values, URL queries, user-info or header values. */
34
+ export class McpClientError extends Error {
35
+ constructor(code: McpClientErrorCode, message: string, details?: unknown);
36
+ readonly code: McpClientErrorCode;
37
+ readonly details?: { status?: number; rpc?: { code?: number; message?: string } };
38
+ }
39
+
40
+ /** UNEXPANDED server spec. `${NAME}` placeholders are expanded from the environment only when connecting. */
41
+ export type StdioServerSpec = { transport: "stdio"; command: string[]; env?: Record<string, string>; cwd?: string };
42
+ export type HttpServerSpec = { transport: "streamable-http"; url: string; headers?: Record<string, string> };
43
+ export type ServerSpec = StdioServerSpec | HttpServerSpec;
44
+ /** A URL, a command line, an argv array, or a spec object. */
45
+ export type ServerInput = string | string[] | ServerSpec | { url: string; headers?: Record<string, string> } | { command: string | string[]; env?: Record<string, string>; cwd?: string };
46
+
47
+ export interface ClientOptions {
48
+ env?: Record<string, string | undefined>;
49
+ timeoutMs?: number;
50
+ discoverTimeoutMs?: number;
51
+ protocolVersions?: readonly ProtocolVersion[];
52
+ clientInfo?: { name: string; version: string };
53
+ /** Diagnostics (never contain credentials). The CLI points this at stderr. */
54
+ log?: (line: string) => void;
55
+ /** Allow plain http:// to a non-loopback host. Default false. */
56
+ allowInsecureHttp?: boolean;
57
+ /** stdio server stderr: "ignore" (default), "inherit", or a sink. */
58
+ stderr?: "ignore" | "inherit" | ((chunk: Buffer) => void);
59
+ fetchImpl?: typeof fetch;
60
+ maxPages?: number;
61
+ }
62
+
63
+ export function splitCommandLine(line: string): string[];
64
+ export function parseServerSpec(input: ServerInput): ServerSpec;
65
+ export function expandEnv(text: string, env?: Record<string, string | undefined>): string;
66
+ /** Log-safe description of an UNEXPANDED spec (query, user-info and secret-looking arguments redacted). */
67
+ export function describeServer(input: ServerInput): string;
68
+ /** Credentials that would be WRITTEN to a pin file (names only), plus warnings. */
69
+ export function findStoredSecrets(input: ServerInput): { problems: string[]; warnings: string[] };
70
+ export function createLineSplitter(onLine: (line: string) => void, options?: { maxBytes?: number; onOverflow?: () => void }): (chunk: string | Buffer) => void;
71
+
72
+ export interface Transport {
73
+ readonly kind: "stdio" | "streamable-http";
74
+ start(): Promise<void>;
75
+ send(message: unknown): Promise<void>;
76
+ close(): Promise<void>;
77
+ onmessage: ((message: unknown) => void) | null;
78
+ onclose: ((info: { code: number | null; signal: string | null; error?: string }) => void) | null;
79
+ onnoise: ((kind: string) => void) | null;
80
+ openNotificationStream?(): Promise<boolean>;
81
+ }
82
+ export class StdioTransport implements Transport {
83
+ constructor(spec: StdioServerSpec, options?: ClientOptions);
84
+ readonly kind: "stdio";
85
+ start(): Promise<void>;
86
+ send(message: unknown): Promise<void>;
87
+ close(): Promise<void>;
88
+ onmessage: ((message: unknown) => void) | null;
89
+ onclose: ((info: { code: number | null; signal: string | null; error?: string }) => void) | null;
90
+ onnoise: ((kind: string) => void) | null;
91
+ }
92
+ export class HttpTransport implements Transport {
93
+ constructor(spec: HttpServerSpec, options?: ClientOptions);
94
+ readonly kind: "streamable-http";
95
+ readonly sessionId: string | null;
96
+ readonly negotiatedVersion: string | null;
97
+ start(): Promise<void>;
98
+ send(message: unknown): Promise<void>;
99
+ close(): Promise<void>;
100
+ openNotificationStream(): Promise<boolean>;
101
+ onmessage: ((message: unknown) => void) | null;
102
+ onclose: ((info: { code: number | null; signal: string | null; error?: string }) => void) | null;
103
+ onnoise: ((kind: string) => void) | null;
104
+ }
105
+ export function openTransport(input: ServerInput, options?: ClientOptions): Promise<Transport>;
106
+
107
+ export class McpClient {
108
+ constructor(transport: Transport, options?: ClientOptions & { meta?: Record<string, unknown> });
109
+ era: "modern" | "legacy" | null;
110
+ protocolVersion: ProtocolVersion | null;
111
+ serverInfo: { name?: string; version?: string; [key: string]: unknown } | null;
112
+ serverCapabilities: Record<string, unknown> | null;
113
+ request(method: string, params?: Record<string, unknown>, options?: { timeoutMs?: number; modern?: boolean }): Promise<any>;
114
+ notify(method: string, params?: Record<string, unknown>): Promise<void>;
115
+ onNotification(handler: (message: { method: string; params?: unknown }) => void): () => void;
116
+ close(): Promise<void>;
117
+ }
118
+
119
+ /** 2026-07-28 `server/discover`, falling back to legacy `initialize`. */
120
+ export function connect(server: ServerInput, options?: ClientOptions): Promise<McpClient>;
121
+ /** Follows every nextCursor; a partial, looping or malformed list throws. */
122
+ export function listAllTools(client: Pick<McpClient, "request">, options?: { maxPages?: number; timeoutMs?: number }): Promise<{ tools: McpToolDefinition[]; pages: number }>;
123
+
124
+ export interface ListedTools {
125
+ tools: McpToolDefinition[];
126
+ pages: number;
127
+ era: "modern" | "legacy";
128
+ protocolVersion: ProtocolVersion;
129
+ serverInfo: { name?: string; version?: string; [key: string]: unknown } | null;
130
+ }
131
+ export function listServerTools(server: ServerInput, options?: ClientOptions): Promise<ListedTools>;