@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/scan/README.md ADDED
@@ -0,0 +1,211 @@
1
+ # `intentrax scan`: what could your agent break? (preview, R1c)
2
+
3
+ > **Heuristic, static scan. It can miss actions and misclassify names.**
4
+
5
+ `intentrax scan` lists the destructive or consequential actions an AI agent can
6
+ reach in a project. It flags three things:
7
+
8
+ - broad credentials behind those actions;
9
+ - actions with no gate in front of them;
10
+ - actions whose success is self-reported, with no read-back.
11
+
12
+ It is local, static and needs no account:
13
+
14
+ - it reads files only: it never imports or runs the project's code;
15
+ - it makes no network call;
16
+ - it never prints a credential value. A credential is reported by its variable
17
+ or config name and its file location only. Literal values in config files are
18
+ noted as "written inline (not shown)".
19
+
20
+ The first line of the output is the catch:
21
+
22
+ ```text
23
+ EXPOSED delete_volume reachable with an account-wide token (RAILWAY_ACCOUNT_TOKEN), no gate
24
+ UNGATED MCP server "billing-remote" (moves money) runs with no gate or approval step
25
+ SELF-REPORTED delete_volume reports success without reading the result back
26
+ ```
27
+
28
+ Plan: `docs/architecture/INTENTRAX_INCIDENT_LED_MILESTONES.md` (R1c). Why
29
+ prevention comes first: `docs/gtm/pain-point-research-2026-11.md`. In the
30
+ incident behind R1c, an agent deleted a production volume and its backups with
31
+ an account-wide token. Commenters' first fix was least privilege, so every
32
+ finding recommends narrowing the credential **before** any Intentrax step.
33
+
34
+ ## Run it
35
+
36
+ With `@intentrax/sdk` 1.8.0 or later:
37
+
38
+ ```bash
39
+ npx @intentrax/sdk scan [dir] [--json] [--include-tests] [--max-files N]
40
+ ```
41
+
42
+ From a checkout of this repository, `node sdk/typescript/scan/cli.mjs` takes the
43
+ same arguments.
44
+
45
+ | Exit | Meaning |
46
+ | --- | --- |
47
+ | 0 | no findings |
48
+ | 20 | findings |
49
+ | 2 | scan error: the directory is missing or unreadable, or the usage is bad |
50
+
51
+ `--json` prints `{ schema: "intentrax.scan.v1", firstLine, findings, actions, summary, warnings, note }`.
52
+
53
+ From code:
54
+
55
+ ```js
56
+ import { scanProject } from "./scan/scan.mjs";
57
+ const { findings, summary, firstLine } = scanProject("path/to/project");
58
+ ```
59
+
60
+ ## Finding types
61
+
62
+ Each finding is one line. Its details carry the classification and its reasons,
63
+ the credentials (names and locations), the gate and read-back evidence, and
64
+ two ordered recommendations: least privilege first, then Intentrax.
65
+
66
+ | Line | When | Recommendations |
67
+ | --- | --- | --- |
68
+ | `EXPOSED` | A consequential action is reachable with a credential whose name suggests broad reach: account-wide, organization-wide, admin, root, owner, master, service-role, full-access, a global API key, a personal access token, a standard Stripe secret key, long-lived cloud keys, kubeconfig. Also flagged: the **same** credential reaching both read-only tools and a severe tool (destructive, money, shell, SQL, infrastructure). | 1. Replace the credential with the platform's scoped mechanism: "a token limited to …", a fine-grained PAT, a Stripe restricted key, a narrow IAM role. Or split it into a read-only credential and a narrow one for the severe tool. 2. If no gate is present, add an Intentrax gate. |
69
+ | `UNGATED` | A consequential action with no gate or approval step in front of it, and no broad credential. (EXPOSED already says "no gate".) | 1. Give the tool a credential limited to what it does, or remove the tool. For a shell: no production credentials in its environment, and an allowlist instead of auto-approve. 2. `npx @intentrax/sdk init <adapter>`, then call the hook before the tool runs (fail closed). |
70
+ | `SELF-REPORTED` | A consequential action whose handler is in the repository, with no read of the affected state after it. Flagged when the action has severity ≥ 2 (deploys, messages, access changes and the severe kinds), or when it returns a success message. | 1. Read back with a separate read-only credential. 2. Try `npx @intentrax/sdk sandbox --check` (a local, non-trust-bearing trial, not evidence). |
71
+
72
+ Findings are ordered by severity, then type. Severity 3 covers destructive
73
+ actions, money movement, shell, arbitrary SQL and infrastructure.
74
+
75
+ ## What it discovers
76
+
77
+ The discovery anchors come from
78
+ `skills/intentrax-integrate-agent-actions/references/discovery-patterns.md`.
79
+ The adapter names come from `npx @intentrax/sdk init`.
80
+
81
+ - **MCP server configs.** It reads these files:
82
+ - `.mcp.json`;
83
+ - `.claude/settings.json` and `.claude/settings.local.json`;
84
+ - `.cursor/mcp.json`;
85
+ - `.vscode/mcp.json` and `.vscode/settings.json`;
86
+ - `.gemini/settings.json`;
87
+ - `claude_desktop_config.json`;
88
+ - `mcp.json`.
89
+
90
+ JSON with comments is accepted. Credentials come from:
91
+ - `env` entries;
92
+ - auth headers;
93
+ - URL query parameters;
94
+ - secret-looking CLI flags;
95
+ - docker `-e NAME`.
96
+
97
+ An stdio server whose entry file is in the repository is linked to its
98
+ source. The scan follows `node path`, `tsx path`, `python -m pkg.mod` and
99
+ `uv --directory d run file.py`, maps `dist/` to `src/`, and follows relative
100
+ imports 3 levels deep. That server's tools then carry its config's
101
+ credentials.
102
+
103
+ A server whose code is not in the repository (an npm package, a docker image,
104
+ or a remote URL) becomes a single action. It is classified by the words in
105
+ its name and launch command (postgres, stripe, github, aws, shell, …).
106
+ - **Tool definitions in source:**
107
+ - MCP TypeScript `server.tool()` and `registerTool()`;
108
+ - low-level `ListTools` arrays with `case "name":` handlers;
109
+ - Python FastMCP `@mcp.tool()`, `Tool(...)` and `if name == "x":` dispatchers;
110
+ - Anthropic `input_schema` and OpenAI `parameters` tool definitions, both chat
111
+ and Responses shapes;
112
+ - OpenAI Agents SDK `@function_tool`;
113
+ - LangChain and LangGraph: `tool()`, `DynamicStructuredTool`, `StructuredTool`
114
+ and `BaseTool` subclasses, `@tool`;
115
+ - Vercel AI SDK `tool({ ... })`;
116
+ - Mastra `createTool`;
117
+ - `*tool*.json` and `*function*.json` definition files.
118
+ - **Shell tools:**
119
+ - tools named for shells or commands;
120
+ - handlers that spawn processes;
121
+ - Claude Code's built-in `Bash` when the project auto-approves it
122
+ (`permissions.allow: ["Bash(*)"]` or `defaultMode: "bypassPermissions"`).
123
+
124
+ ## Classification (heuristic)
125
+
126
+ Every classification has `heuristic: true` and the reasons behind it.
127
+
128
+ - **Name verbs.** For example `delete_volume`, `volumeDelete`, `issue_refund`,
129
+ `run_sql` and `execute_command`.
130
+ - A read verb in the name (`get_refund`, `list_transfers`,
131
+ `list_deleted_items`) keeps the tool read-only, unless the name also has a
132
+ plain destructive verb.
133
+ - Words that are nouns in one name and verbs in another (`blog_post` vs
134
+ `post_tweet`) count only as the first word of the name.
135
+ - **Descriptions** are used when the name has no verb. Negated verbs ("does not
136
+ delete") are skipped.
137
+ - **Handler side effects** can raise a classification but never lower it. They
138
+ include SQL `DELETE`/`DROP`, HTTP `DELETE`, payment API calls, process
139
+ execution, message sending and file deletion. A generic `.delete(` (often a
140
+ `Map` or a cache) does not overrule a read name.
141
+ - **MCP annotations are untrusted.** `destructiveHint: true` raises concern.
142
+ `destructiveHint: false` and `readOnlyHint: true` never lower it, and the
143
+ reasons say they were ignored.
144
+
145
+ ## Gate and read-back (heuristic)
146
+
147
+ A tool counts as gated when one of these sits in front of it:
148
+
149
+ - an Intentrax admission or execute call in its handler, or in the same file
150
+ (assumed to be a shared dispatcher). This means `admitAgentGatewayHttp`,
151
+ `executeIntentHttp` or a generated hook entrypoint such as
152
+ `beforeMCPToolCall` or `withIntentraxLangChainCallback`. A call placed
153
+ **after** the side effect does not count;
154
+ - an approval step: `needsApproval`, LangGraph `interrupt`/`interrupt_before`,
155
+ LangChain human-approval handlers, MCP elicitation, or OpenAI Agents
156
+ `needs_approval`;
157
+ - a Claude Code `PreToolUse` hook whose matcher covers the tool and whose
158
+ command runs Intentrax or an approval step;
159
+ - a Claude Code `permissions.ask` rule;
160
+ - a Cursor `beforeMCPExecution` or `beforeShellExecution` hook.
161
+
162
+ A tool matched by `permissions.deny` is listed but not reported.
163
+
164
+ A read-back is a read of the affected state after the side effect, or a call
165
+ to a confirmation step (`confirmThenReport`, `readBack`, AWS waiters,
166
+ `verifyDeleted…`).
167
+
168
+ ## Known limits
169
+
170
+ - **Names are not behaviour.** A tool named `sync` may delete. A tool named
171
+ `delete_draft` may be harmless.
172
+ - **Credential breadth is inferred from names only.** The scan cannot see a
173
+ token's real scopes.
174
+ - **What it cannot see:** a server whose code is outside the repository, tools
175
+ registered dynamically, and dispatchers in another file.
176
+ - **No cross-file guarantee.** A gate in a different file from the tool is not
177
+ linked, so the tool may be reported as UNGATED.
178
+ - **Config the scan never reads:**
179
+ - client settings outside the project, such as user-level Claude or Cursor
180
+ config;
181
+ - `--dangerously-skip-permissions`;
182
+ - `.env` files.
183
+ - **Skipped by default:** test and fixture directories, generated code
184
+ (`dist`, `build`) and vendored code. Use `--include-tests` to scan test and
185
+ fixture directories.
186
+
187
+ ## Tests
188
+
189
+ ```bash
190
+ node --test sdk/typescript/scan/test/*.test.mjs
191
+ ```
192
+
193
+ The fixture projects live in `test/fixtures/`:
194
+
195
+ | Fixture | Shows |
196
+ | --- | --- |
197
+ | `exposed-mcp` | An MCP config with a destructive tool and an account-wide token, inline fake secrets, and a remote server. |
198
+ | `gated` | An Intentrax dispatcher gate and a Claude Code PreToolUse hook. |
199
+ | `readback` | A Vercel AI SDK tool and a LangChain Python tool, each with a read-back. |
200
+ | `clean` | Read-only tools. |
201
+ | `shared-credential` | One token serving read and destructive tools. |
202
+ | `shell` | An auto-approved Bash tool and a denied server. |
203
+
204
+ The tests also check that no fixture secret value or server URL ever appears
205
+ in text or JSON output.
206
+
207
+ ## Status
208
+
209
+ Shipped in `@intentrax/sdk` 1.8.0: `cli/intentrax.mjs` dispatches `scan` to
210
+ `scanMain`, and `package.json` `files` packs `scan/*.mjs` and
211
+ `scan/README.md` (never `scan/test`). Exit codes stay 0, 20 and 2.
@@ -0,0 +1,276 @@
1
+ // Heuristic classification of agent-reachable actions by the verbs in their
2
+ // names and descriptions, the side effects visible in their handlers, and
3
+ // (untrusted) MCP annotations. Every result carries `heuristic: true` and the
4
+ // reasons it was reached, because a name is not a behaviour.
5
+
6
+ import { tokenize } from "./text.mjs";
7
+
8
+ // severity 3: hard or impossible to undo; 2: consequential and visible to
9
+ // others; 1: changes state. 0: read-only or unclassified.
10
+ export const CATEGORIES = Object.freeze({
11
+ destructive: { severity: 3, label: "destructive" },
12
+ financial: { severity: 3, label: "moves money" },
13
+ shell: { severity: 3, label: "runs shell commands" },
14
+ database: { severity: 3, label: "can run arbitrary SQL" },
15
+ infrastructure: { severity: 3, label: "changes infrastructure" },
16
+ deploy: { severity: 2, label: "deploys, merges or publishes" },
17
+ communication: { severity: 2, label: "sends messages" },
18
+ access: { severity: 2, label: "changes access" },
19
+ browser: { severity: 2, label: "acts in a browser" },
20
+ write: { severity: 1, label: "writes data" },
21
+ unknown: { severity: 1, label: "tools not listed statically" },
22
+ read: { severity: 0, label: "read-only" },
23
+ unclassified: { severity: 0, label: "unclassified" },
24
+ });
25
+
26
+ const VERBS = [
27
+ ["destructive", ["delete", "del", "remove", "rm", "drop", "destroy", "purge", "truncate", "wipe", "erase", "terminate", "kill", "deprovision", "teardown", "nuke", "reset", "overwrite", "revoke", "uninstall", "cancel", "archive", "unlink", "rmdir", "shred", "flush", "evict"]],
28
+ ["financial", ["refund", "payment", "transfer", "pay", "payout", "charge", "withdraw", "wire", "purchase", "buy", "sell", "trade", "swap", "capture", "settle", "disburse", "invoice", "bill", "checkout", "debit", "credit", "remit"]],
29
+ ["shell", ["bash", "shell", "exec", "terminal", "cmd", "powershell", "sh", "zsh", "subprocess", "eval"]],
30
+ ["deploy", ["deploy", "release", "publish", "rollback", "promote", "merge", "push", "apply", "scale", "restart", "provision", "migrate", "rebase", "tag", "redeploy", "shutdown", "reboot", "stop", "start"]],
31
+ ["communication", ["send", "email", "mail", "post", "message", "notify", "sms", "tweet", "reply", "dm", "broadcast", "text", "call", "comment", "forward"]],
32
+ ["access", ["grant", "invite", "permit", "authorize", "promote", "assign", "share", "impersonate", "rotate"]],
33
+ ["write", ["write", "update", "create", "insert", "upsert", "edit", "modify", "set", "patch", "put", "save", "commit", "rename", "move", "upload", "approve", "execute", "run", "add", "append", "import", "sync", "submit", "change", "replace", "store", "enable", "disable", "close", "open", "book", "order", "schedule"]],
34
+ ];
35
+
36
+ const READ_VERBS = new Set([
37
+ "get", "list", "read", "search", "fetch", "query", "describe", "show", "find", "view", "lookup", "inspect",
38
+ "status", "count", "check", "browse", "retrieve", "download", "explain", "preview", "validate", "verify",
39
+ "diff", "ls", "cat", "head", "tail", "grep", "summarize", "summarise", "analyze", "analyse", "compare",
40
+ "estimate", "quote", "ping", "health", "whoami", "info", "watch", "poll", "load", "lint", "parse",
41
+ ]);
42
+
43
+ // Objects that turn "run"/"execute" into a shell or SQL action.
44
+ const SHELL_OBJECTS = new Set(["command", "commands", "shell", "bash", "script", "code", "terminal", "cmd", "process", "python", "powershell", "subprocess", "program"]);
45
+ const SQL_OBJECTS = new Set(["sql", "statement", "ddl", "dml"]);
46
+
47
+ const NEGATIONS = new Set(["not", "never", "no", "without", "cannot", "can't", "won't", "doesn't", "don't", "nothing", "non", "neither", "nor"]);
48
+
49
+ const VERB_INDEX = new Map();
50
+ for (const [category, verbs] of VERBS) {
51
+ for (const v of verbs) if (!VERB_INDEX.has(v)) VERB_INDEX.set(v, category);
52
+ }
53
+
54
+ function stems(token) {
55
+ const out = [token];
56
+ if (token.endsWith("ing")) out.push(token.slice(0, -3), token.slice(0, -3) + "e");
57
+ if (token.endsWith("ed")) out.push(token.slice(0, -2), token.slice(0, -1));
58
+ if (token.endsWith("es")) out.push(token.slice(0, -2));
59
+ if (token.endsWith("s")) out.push(token.slice(0, -1));
60
+ return out;
61
+ }
62
+
63
+ function verbCategory(token) {
64
+ for (const s of stems(token)) {
65
+ if (VERB_INDEX.has(s)) return { category: VERB_INDEX.get(s), verb: s };
66
+ }
67
+ return null;
68
+ }
69
+
70
+ function isReadVerb(token) {
71
+ return stems(token).some((s) => READ_VERBS.has(s));
72
+ }
73
+
74
+ function sev(category) {
75
+ return CATEGORIES[category]?.severity ?? 0;
76
+ }
77
+
78
+ // Words that are verbs in "post_tweet" but nouns in "blog_post": they count
79
+ // only as the first word of a name.
80
+ const NOUN_LIKE = new Set([
81
+ "post", "message", "email", "mail", "text", "call", "comment", "tag", "order", "book", "schedule", "credit",
82
+ "bill", "invoice", "sms", "dm", "start", "stop", "open", "close", "set", "share", "change", "store", "archive",
83
+ "transfer", "charge", "wire", "trade", "swap", "capture", "settle", "push", "apply", "scale", "release",
84
+ "forward", "reply", "run", "import", "sync", "cancel", "flush", "promote", "rotate", "debit", "checkout",
85
+ "payout", "refund", "payment", "purchase", "commit", "merge", "deploy", "publish",
86
+ ]);
87
+
88
+ // "issue_refund", "make_payment", "trigger_deploy": the second word is the verb.
89
+ const LIGHT_VERBS = new Set(["issue", "make", "initiate", "trigger", "perform", "process", "do", "request", "force", "batch", "bulk", "auto", "mass"]);
90
+
91
+ function runLike(t, next) {
92
+ if (!["run", "execute", "exec", "eval", "raw"].includes(t)) return null;
93
+ const sql = next.find((n) => SQL_OBJECTS.has(n));
94
+ if (sql) return { category: "database", verb: `${t} ${sql}` };
95
+ const sh = next.find((n) => SHELL_OBJECTS.has(n));
96
+ if (sh) return { category: "shell", verb: `${t} ${sh}` };
97
+ return null;
98
+ }
99
+
100
+ // Tool names: "delete_volume", "volumeDelete", "get_refund", "list_deleted".
101
+ // A read verb anywhere in the name makes it read-only unless the name also
102
+ // carries a plain destructive verb or a run-SQL/run-shell pair.
103
+ function fromNameTokens(tokens) {
104
+ const readVerb = tokens.find(isReadVerb);
105
+ const hits = [];
106
+ for (let i = 0; i < tokens.length; i += 1) {
107
+ const t = tokens[i];
108
+ const special = runLike(t, tokens.slice(i + 1, i + 3));
109
+ if (special) {
110
+ hits.push(special);
111
+ continue;
112
+ }
113
+ if (SQL_OBJECTS.has(t) && tokens.length <= 2 && !readVerb) {
114
+ hits.push({ category: "database", verb: t });
115
+ continue;
116
+ }
117
+ const hit = verbCategory(t);
118
+ if (!hit) continue;
119
+ if (readVerb) {
120
+ // "get_refund", "list_transfers", "list_deleted_items" stay read-only.
121
+ if (hit.category === "destructive" && t === hit.verb) hits.push(hit);
122
+ continue;
123
+ }
124
+ if (NOUN_LIKE.has(hit.verb) && i !== 0 && !(i === 1 && LIGHT_VERBS.has(tokens[0]))) continue;
125
+ hits.push(hit);
126
+ }
127
+ if (hits.length === 0) return readVerb ? { category: "read", verb: readVerb } : null;
128
+ return hits.reduce((best, h) => (sev(h.category) > sev(best.category) ? h : best), hits[0]);
129
+ }
130
+
131
+ // Descriptions: highest-severity verb in the first 300 characters, skipping
132
+ // negated ones ("does not delete").
133
+ function fromDescriptionTokens(tokens) {
134
+ let best = null;
135
+ for (let i = 0; i < tokens.length; i += 1) {
136
+ if (tokens.slice(Math.max(0, i - 3), i).some((p) => NEGATIONS.has(p))) continue;
137
+ const hit = runLike(tokens[i], tokens.slice(i + 1, i + 3)) ?? verbCategory(tokens[i]);
138
+ if (hit && !NOUN_LIKE.has(hit.verb) && (!best || sev(hit.category) > sev(best.category))) best = hit;
139
+ }
140
+ return best;
141
+ }
142
+
143
+ // Side effects visible in a handler body. Order matters: first match per
144
+ // category wins; we report the strongest.
145
+ const SIDE_EFFECTS = [
146
+ { category: "destructive", re: /\b(?:DELETE\s+FROM|DROP\s+(?:TABLE|DATABASE|SCHEMA|INDEX|VIEW)|TRUNCATE\s+(?:TABLE\s+)?\w)/i, what: "SQL DELETE/DROP/TRUNCATE" },
147
+ { category: "destructive", re: /\.(?:delete|destroy|remove|deleteMany|deleteOne|drop|terminate|purge)\w*\s*\(/, what: "a delete/destroy call", weak: true },
148
+ { category: "destructive", re: /\brm\s+-[a-z]*r|\brmSync\s*\(|\bunlinkSync\s*\(|\bunlink\s*\(|shutil\.rmtree|os\.remove\s*\(|os\.unlink\s*\(/, what: "a file deletion" },
149
+ { category: "destructive", re: /method\s*[:=]\s*["']DELETE["']/i, what: "an HTTP DELETE" },
150
+ { category: "financial", re: /\b(?:refunds|transfers|payouts|charges|paymentIntents|payment_intents)\.(?:create|confirm|capture)\b|\bRefund\.create\b|\bTransfer\.create\b/, what: "a payment API call" },
151
+ { category: "shell", re: /\bchild_process\b|\b(?:execSync|execFileSync|execFile|spawnSync)\s*\(|(?<![.\w$])exec\s*\(|\b(?:cp|childProcess)\.exec\s*\(|(?<![.\w$])spawn\s*\(|\bsubprocess\.(?:run|call|Popen|check_output|check_call)\b|\bos\.system\s*\(|shell\s*=\s*True/, what: "a shell/process execution" },
152
+ { category: "communication", re: /\b(?:sendMail|sendEmail|send_email|send_mail)\s*\(|\.messages\.send\b|chat\.postMessage|chat_postMessage|\btwilio\b|\bses\.send|\bresend\.emails\b|\bsendgrid\b/i, what: "a message-sending call" },
153
+ { category: "deploy", re: /\bgit\s+push\b|\bkubectl\s+(?:apply|delete|scale|rollout)|\bterraform\s+(?:apply|destroy)|\bhelm\s+(?:install|upgrade|uninstall)/, what: "a deploy/infra command" },
154
+ { category: "write", re: /\b(?:INSERT\s+INTO|UPDATE\s+\w+\s+SET)\b/i, what: "SQL INSERT/UPDATE" },
155
+ { category: "write", re: /method\s*[:=]\s*["'](?:POST|PUT|PATCH)["']/i, what: "an HTTP POST/PUT/PATCH" },
156
+ ];
157
+
158
+ export function sideEffectsIn(body) {
159
+ const hits = [];
160
+ for (const se of SIDE_EFFECTS) {
161
+ const m = se.re.exec(body ?? "");
162
+ if (m) hits.push({ category: se.category, what: se.what, index: m.index, weak: Boolean(se.weak) });
163
+ }
164
+ return hits;
165
+ }
166
+
167
+ // Every side-effect occurrence, in source order. Used where ordering matters
168
+ // (a read-back must follow the LAST mutation, not the first of each kind).
169
+ export function allSideEffectsIn(body) {
170
+ const hits = [];
171
+ const text = body ?? "";
172
+ for (const se of SIDE_EFFECTS) {
173
+ const re = new RegExp(se.re.source, se.re.flags.includes("g") ? se.re.flags : `${se.re.flags}g`);
174
+ let m;
175
+ while ((m = re.exec(text))) {
176
+ hits.push({ category: se.category, what: se.what, index: m.index, weak: Boolean(se.weak) });
177
+ if (m[0].length === 0) re.lastIndex += 1;
178
+ }
179
+ }
180
+ return hits.sort((a, b) => a.index - b.index);
181
+ }
182
+
183
+ // Classifies one action. Inputs are names, a description and a handler body;
184
+ // none of them is printed back (only the matched verb).
185
+ export function classifyAction({ name, description = "", body = "", annotations = {}, domainTokens = null }) {
186
+ const reasons = [];
187
+ const nameTokens = tokenize(name);
188
+ let result = null;
189
+
190
+ const fromName = fromNameTokens(nameTokens);
191
+ if (fromName && fromName.category === "read") {
192
+ result = "read";
193
+ reasons.push(`name contains the read verb "${fromName.verb}"`);
194
+ } else if (fromName) {
195
+ result = fromName.category;
196
+ reasons.push(`name contains "${fromName.verb}"`);
197
+ } else if (description) {
198
+ const fromDesc = fromDescriptionTokens(tokenize(String(description).slice(0, 300)));
199
+ if (fromDesc) {
200
+ result = fromDesc.category;
201
+ reasons.push(`description contains "${fromDesc.verb}"`);
202
+ }
203
+ }
204
+
205
+ // Handler side effects can upgrade, never downgrade.
206
+ for (const se of sideEffectsIn(body)) {
207
+ // A generic ".delete(" (often a Map or cache) does not overrule a read name.
208
+ if (se.weak && result === "read") continue;
209
+ if (!result || sev(se.category) > sev(result)) {
210
+ reasons.push(`handler contains ${se.what}`);
211
+ result = se.category;
212
+ }
213
+ }
214
+
215
+ // Domain words (external MCP servers whose tools cannot be listed).
216
+ if (domainTokens) {
217
+ const d = domainCategory(domainTokens);
218
+ if (d && (!result || sev(d.category) > sev(result))) {
219
+ result = d.category;
220
+ reasons.push(`server name or launch command mentions "${d.word}"; its tools could not be listed statically`);
221
+ }
222
+ }
223
+
224
+ // MCP annotations are self-declared by the server, so they are untrusted:
225
+ // they may raise our concern but never lower it.
226
+ if (annotations.destructiveHint === true) {
227
+ if (sev(result) < 3) {
228
+ result = "destructive";
229
+ reasons.push("annotation destructiveHint=true (self-declared by the server; read as a warning, never as reassurance)");
230
+ } else {
231
+ reasons.push("annotation destructiveHint=true agrees (self-declared, untrusted)");
232
+ }
233
+ } else if (annotations.destructiveHint === false && sev(result) >= 3) {
234
+ reasons.push("annotation destructiveHint=false ignored: annotations are untrusted");
235
+ }
236
+ if (annotations.readOnlyHint === true && sev(result) > 0) {
237
+ reasons.push("annotation readOnlyHint=true ignored: annotations are untrusted");
238
+ }
239
+
240
+ if (!result) {
241
+ result = "unclassified";
242
+ reasons.push("no consequential verb in the name or description");
243
+ }
244
+ return {
245
+ category: result,
246
+ label: CATEGORIES[result].label,
247
+ severity: sev(result),
248
+ consequential: sev(result) > 0,
249
+ heuristic: true,
250
+ reasons,
251
+ };
252
+ }
253
+
254
+ const DOMAINS = [
255
+ ["shell", ["shell", "terminal", "commander", "bash", "cmd", "ssh", "exec", "powershell", "zsh"]],
256
+ ["database", ["postgres", "postgresql", "pg", "mysql", "mariadb", "sqlite", "sql", "mssql", "mongo", "mongodb", "redis", "supabase", "neon", "database", "db", "prisma", "planetscale", "dynamodb", "firestore", "bigquery", "snowflake", "clickhouse"]],
257
+ ["infrastructure", ["aws", "gcp", "gcloud", "azure", "kubernetes", "k8s", "kubectl", "terraform", "railway", "vercel", "netlify", "fly", "heroku", "cloudflare", "digitalocean", "docker", "render", "pulumi", "ec2", "s3", "lambda", "infra"]],
258
+ ["financial", ["stripe", "paypal", "square", "plaid", "braintree", "adyen", "payment", "payments", "billing", "bank", "banking", "ledger", "wise", "coinbase"]],
259
+ ["deploy", ["github", "gitlab", "bitbucket", "git", "jenkins", "circleci", "argocd", "deploy"]],
260
+ ["communication", ["slack", "gmail", "email", "mail", "twilio", "sendgrid", "discord", "telegram", "teams", "outlook", "resend", "whatsapp", "mailgun", "postmark", "intercom", "zendesk"]],
261
+ ["browser", ["puppeteer", "playwright", "browser", "chrome", "selenium", "browserbase"]],
262
+ ["write", ["filesystem", "fs", "files", "drive", "gdrive", "dropbox", "onedrive", "box", "notion", "jira", "linear", "airtable", "sheets", "hubspot", "salesforce", "shopify"]],
263
+ ];
264
+
265
+ export function domainCategory(tokens) {
266
+ let best = null;
267
+ for (const [category, words] of DOMAINS) {
268
+ const word = tokens.find((t) => words.includes(t));
269
+ if (word && (!best || sev(category) > sev(best.category))) best = { category, word };
270
+ }
271
+ return best;
272
+ }
273
+
274
+ export function isReadOnlyClassification(c) {
275
+ return c.category === "read";
276
+ }
package/scan/cli.mjs ADDED
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env node
2
+ // `intentrax scan`: what could your agent break?
3
+ //
4
+ // intentrax scan [dir] [--json] [--include-tests] [--max-files N]
5
+ //
6
+ // Local and static: reads files under [dir] (default: the current directory),
7
+ // never runs or imports them, makes no network call and needs no account.
8
+ // Credentials are reported by name and location only, never by value.
9
+ //
10
+ // Exit codes: 0 no findings, 20 findings, 2 scan error (including bad usage).
11
+ //
12
+ // From a repository checkout, `node sdk/typescript/scan/cli.mjs [args]` runs
13
+ // the same thing. The SDK 1.8.0 integration step wires
14
+ // `intentrax scan ...` (cli/intentrax.mjs) to `scanMain`.
15
+
16
+ import { realpathSync } from "node:fs";
17
+ import { resolve } from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+ import { scanProject, ScanError, SCAN_NOTE } from "./scan.mjs";
20
+ import { EXIT_CODES, exitCodeFor, formatJson, formatText } from "./report.mjs";
21
+
22
+ class UsageError extends Error {}
23
+
24
+ export function usage(invokedAs = "intentrax scan") {
25
+ return [
26
+ `Usage: ${invokedAs} [dir] [--json] [--include-tests] [--max-files N]`,
27
+ "",
28
+ "Lists the destructive or consequential actions an AI agent can reach in a",
29
+ "project (MCP servers and tools, OpenAI/Anthropic tool definitions,",
30
+ "LangChain/LangGraph and Vercel AI SDK tools, shell tools), and flags broad",
31
+ "credentials (EXPOSED), missing gates (UNGATED) and success reported without",
32
+ "a read-back (SELF-REPORTED). Local and static: nothing is run or sent.",
33
+ "",
34
+ " --json machine-readable output",
35
+ " --include-tests also scan test and fixture directories",
36
+ " --max-files N stop after N files (default 20000)",
37
+ "",
38
+ "Exit codes: 0 no findings, 20 findings, 2 scan error.",
39
+ SCAN_NOTE,
40
+ ].join("\n");
41
+ }
42
+
43
+ function parseArgs(argv) {
44
+ const opts = { dir: null, json: false, includeTests: false, maxFiles: undefined, help: false };
45
+ for (let i = 0; i < argv.length; i += 1) {
46
+ const a = argv[i];
47
+ if (a === "--help" || a === "-h") opts.help = true;
48
+ else if (a === "--json") opts.json = true;
49
+ else if (a === "--include-tests") opts.includeTests = true;
50
+ else if (a === "--max-files") {
51
+ const n = Number(argv[i + 1]);
52
+ if (!Number.isSafeInteger(n) || n < 1) throw new UsageError("--max-files requires a positive integer");
53
+ opts.maxFiles = n;
54
+ i += 1;
55
+ } else if (a.startsWith("-")) throw new UsageError(`unknown option ${a}`);
56
+ else if (opts.dir === null) opts.dir = a;
57
+ else throw new UsageError(`unexpected argument ${a}`);
58
+ }
59
+ return opts;
60
+ }
61
+
62
+ export function scanMain(argv = [], io = {}) {
63
+ const out = io.out ?? ((s) => process.stdout.write(s));
64
+ const err = io.err ?? ((s) => process.stderr.write(s));
65
+ const cwd = io.cwd ?? process.cwd();
66
+ const invokedAs = io.invokedAs ?? "intentrax scan";
67
+ let opts;
68
+ try {
69
+ opts = parseArgs(argv);
70
+ } catch (e) {
71
+ err(`intentrax scan: ${e.message}\n${usage(invokedAs)}\n`);
72
+ return EXIT_CODES.SCAN_ERROR;
73
+ }
74
+ if (opts.help) {
75
+ out(usage(invokedAs) + "\n");
76
+ return EXIT_CODES.NO_FINDINGS;
77
+ }
78
+ let result;
79
+ try {
80
+ result = scanProject(opts.dir ? resolve(cwd, opts.dir) : cwd, { includeTests: opts.includeTests, maxFiles: opts.maxFiles });
81
+ } catch (e) {
82
+ const message = e instanceof ScanError ? e.message : `unexpected error: ${e?.message ?? e}`;
83
+ if (opts.json) out(JSON.stringify({ schema: "intentrax.scan.v1", error: message, note: SCAN_NOTE }, null, 2) + "\n");
84
+ err(`intentrax scan: ${message}\n`);
85
+ return EXIT_CODES.SCAN_ERROR;
86
+ }
87
+ out(opts.json ? formatJson(result) : formatText(result));
88
+ return exitCodeFor(result);
89
+ }
90
+
91
+ function invokedDirectly() {
92
+ if (!process.argv[1]) return false;
93
+ try {
94
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
95
+ } catch {
96
+ return false;
97
+ }
98
+ }
99
+
100
+ if (invokedDirectly()) {
101
+ process.exitCode = scanMain(process.argv.slice(2), { invokedAs: "node sdk/typescript/scan/cli.mjs" });
102
+ }