@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.
- package/README.md +17 -2
- package/cli/intentrax.mjs +45 -1
- package/mcp/README.md +138 -0
- package/mcp/canonical.d.ts +12 -0
- package/mcp/canonical.mjs +70 -0
- package/mcp/cli.d.ts +16 -0
- package/mcp/cli.mjs +214 -0
- package/mcp/client.d.ts +131 -0
- package/mcp/client.mjs +955 -0
- package/mcp/commands.d.ts +113 -0
- package/mcp/commands.mjs +575 -0
- package/mcp/index.d.ts +12 -0
- package/mcp/index.mjs +12 -0
- package/mcp/proxy.d.ts +47 -0
- package/mcp/proxy.mjs +434 -0
- package/mcp/receipt-meta.d.ts +59 -0
- package/mcp/receipt-meta.mjs +178 -0
- package/mcp/tool-manifest.d.ts +74 -0
- package/mcp/tool-manifest.mjs +154 -0
- package/package.json +16 -1
- package/readback/README.md +352 -0
- package/readback/bridge.mjs +71 -0
- package/readback/cli.mjs +150 -0
- package/readback/confirm.mjs +404 -0
- package/readback/index.mjs +12 -0
- package/readback/recipe-worker.mjs +33 -0
- package/readback/recipes/_shared.mjs +126 -0
- package/readback/recipes/email-delivery.mjs +136 -0
- package/readback/recipes/github-issue.mjs +88 -0
- package/readback/recipes/http-json.mjs +109 -0
- package/readback/recipes/sql-row.mjs +96 -0
- package/readback/recipes/stripe-refund.mjs +73 -0
- package/readback/redact.mjs +68 -0
- package/scan/README.md +211 -0
- package/scan/classify.mjs +276 -0
- package/scan/cli.mjs +102 -0
- package/scan/configs.mjs +261 -0
- package/scan/credentials.mjs +121 -0
- package/scan/extract.mjs +323 -0
- package/scan/gates.mjs +94 -0
- package/scan/report.mjs +58 -0
- package/scan/scan.mjs +571 -0
- package/scan/text.mjs +186 -0
package/scan/extract.mjs
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
// Static extraction of tool definitions from source files: MCP servers
|
|
2
|
+
// (TypeScript/JavaScript and Python), OpenAI and Anthropic tool/function
|
|
3
|
+
// definitions, LangChain/LangGraph tools, Vercel AI SDK tools and Mastra
|
|
4
|
+
// tools. Pattern-based (the anchors follow
|
|
5
|
+
// skills/intentrax-integrate-agent-actions/references/discovery-patterns.md):
|
|
6
|
+
// it reads text, never imports or runs it.
|
|
7
|
+
|
|
8
|
+
import { makeLineIndex, readString, matchBracket, depthAt, findKeyString } from "./text.mjs";
|
|
9
|
+
|
|
10
|
+
const MAX_SPAN_LINES = 120;
|
|
11
|
+
|
|
12
|
+
function frameworkOf(text, isPython, hint) {
|
|
13
|
+
if (/@modelcontextprotocol\/sdk|from\s+mcp\b|import\s+mcp\b|from\s+fastmcp\b|import\s+fastmcp\b|FastMCP\s*\(|McpServer\s*\(/.test(text)) {
|
|
14
|
+
if (hint === "mcp" || hint === "object") return "mcp";
|
|
15
|
+
}
|
|
16
|
+
if (/@langchain\/langgraph|from\s+langgraph\b|import\s+langgraph\b/.test(text)) return "langgraph";
|
|
17
|
+
if (/@langchain\/|from\s+langchain|import\s+langchain/.test(text)) return "langchain";
|
|
18
|
+
if (/from\s+["']ai["']|require\(\s*["']ai["']\s*\)|@ai-sdk\//.test(text)) return "vercel-ai-sdk";
|
|
19
|
+
if (/@mastra\//.test(text)) return "mastra";
|
|
20
|
+
if (/from\s+agents\b|@openai\/agents/.test(text)) return "openai-agents";
|
|
21
|
+
if (/\bopenai\b/i.test(text)) return "openai";
|
|
22
|
+
if (/\banthropic\b/i.test(text)) return "anthropic";
|
|
23
|
+
return isPython ? "python" : "javascript";
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function annotationsIn(text) {
|
|
27
|
+
const out = {};
|
|
28
|
+
const d = /["']?destructiveHint["']?\s*[:=]\s*(true|false|True|False)\b/.exec(text);
|
|
29
|
+
if (d) out.destructiveHint = d[1].toLowerCase() === "true";
|
|
30
|
+
const r = /["']?readOnlyHint["']?\s*[:=]\s*(true|false|True|False)\b/.exec(text);
|
|
31
|
+
if (r) out.readOnlyHint = r[1].toLowerCase() === "true";
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function prevIdentifier(text, index) {
|
|
36
|
+
const before = text.slice(Math.max(0, index - 200), index);
|
|
37
|
+
const key = /(?:^|[\s,{])(?:["']([^"'\n]+)["']|([A-Za-z_$][\w$]*))\s*:\s*$/.exec(before);
|
|
38
|
+
if (key) return key[1] ?? key[2];
|
|
39
|
+
const decl = /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*$/.exec(before);
|
|
40
|
+
if (decl) return decl[1];
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Each extractor pushes { name, kind, framework, index, description, annotations, callText }.
|
|
45
|
+
function extractJs(text, push) {
|
|
46
|
+
let m;
|
|
47
|
+
|
|
48
|
+
// MCP TypeScript SDK: server.tool("name", "description"?, ...)
|
|
49
|
+
const dotTool = /\.tool\s*\(/g;
|
|
50
|
+
while ((m = dotTool.exec(text))) {
|
|
51
|
+
const open = m.index + m[0].length - 1;
|
|
52
|
+
const name = readString(text, open + 1);
|
|
53
|
+
if (!name || name.start !== skipWs(text, open + 1)) continue;
|
|
54
|
+
const after = skipWs(text, name.end);
|
|
55
|
+
let description = "";
|
|
56
|
+
if (text[after] === ",") {
|
|
57
|
+
const d = readString(text, after + 1);
|
|
58
|
+
if (d && d.start === skipWs(text, after + 1)) description = d.value;
|
|
59
|
+
}
|
|
60
|
+
const close = matchBracket(text, open);
|
|
61
|
+
const callText = text.slice(m.index, close > 0 ? close : m.index + 1500);
|
|
62
|
+
push({ name: name.value, framework: "mcp", index: m.index, description, annotations: annotationsIn(callText) });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// MCP TypeScript SDK: server.registerTool("name", { description, annotations }, handler)
|
|
66
|
+
const register = /\.registerTool\s*\(/g;
|
|
67
|
+
while ((m = register.exec(text))) {
|
|
68
|
+
const open = m.index + m[0].length - 1;
|
|
69
|
+
const name = readString(text, open + 1);
|
|
70
|
+
if (!name) continue;
|
|
71
|
+
const close = matchBracket(text, open);
|
|
72
|
+
const end = close > 0 ? close : m.index + 2000;
|
|
73
|
+
const desc = findKeyString(text, "description", name.end, end);
|
|
74
|
+
push({ name: name.value, framework: "mcp", index: m.index, description: desc?.value ?? "", annotations: annotationsIn(text.slice(m.index, end)) });
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Bare tool(...): Vercel AI SDK tool({ ... }) or LangChain tool(fn, { name, ... })
|
|
78
|
+
const bareTool = /(?<![.\w$])(tool|dynamicTool|createTool)\s*\(/g;
|
|
79
|
+
while ((m = bareTool.exec(text))) {
|
|
80
|
+
const open = m.index + m[0].length - 1;
|
|
81
|
+
const first = skipWs(text, open + 1);
|
|
82
|
+
const close = matchBracket(text, open);
|
|
83
|
+
const end = close > 0 ? close : m.index + 2000;
|
|
84
|
+
if (text[first] === "{") {
|
|
85
|
+
const objClose = matchBracket(text, first);
|
|
86
|
+
const objEnd = objClose > 0 ? objClose : end;
|
|
87
|
+
const id = findKeyString(text, "id", first, objEnd, { open: first, depth: 1 }) ?? findKeyString(text, "name", first, objEnd, { open: first, depth: 1 });
|
|
88
|
+
const name = id?.value ?? prevIdentifier(text, m.index);
|
|
89
|
+
if (!name) continue;
|
|
90
|
+
const desc = findKeyString(text, "description", first, objEnd, { open: first, depth: 1 });
|
|
91
|
+
const fw = m[1] === "createTool" ? "mastra" : frameworkOf(text, false, "vercel");
|
|
92
|
+
push({ name, framework: fw, index: m.index, description: desc?.value ?? "", annotations: annotationsIn(text.slice(first, objEnd)) });
|
|
93
|
+
} else {
|
|
94
|
+
const nameKey = findKeyString(text, "name", first, end);
|
|
95
|
+
if (!nameKey) continue;
|
|
96
|
+
const desc = findKeyString(text, "description", first, end);
|
|
97
|
+
push({ name: nameKey.value, framework: frameworkOf(text, false, "langchain"), index: m.index, description: desc?.value ?? "", annotations: {} });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// LangChain JS: new DynamicStructuredTool({ name, description, func })
|
|
102
|
+
const dyn = /new\s+(?:DynamicStructuredTool|DynamicTool)\s*\(\s*\{/g;
|
|
103
|
+
while ((m = dyn.exec(text))) {
|
|
104
|
+
const objOpen = m.index + m[0].length - 1;
|
|
105
|
+
const objClose = matchBracket(text, objOpen);
|
|
106
|
+
const end = objClose > 0 ? objClose : m.index + 2000;
|
|
107
|
+
const name = findKeyString(text, "name", objOpen, end, { open: objOpen, depth: 1 });
|
|
108
|
+
if (!name) continue;
|
|
109
|
+
const desc = findKeyString(text, "description", objOpen, end, { open: objOpen, depth: 1 });
|
|
110
|
+
push({ name: name.value, framework: frameworkOf(text, false, "langchain"), index: m.index, description: desc?.value ?? "", annotations: {} });
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// LangChain JS: class X extends StructuredTool { name = "x"; description = "..." }
|
|
114
|
+
const cls = /class\s+([A-Za-z_$][\w$]*)\s+extends\s+(?:StructuredTool|Tool|DynamicTool)\b[^{]*\{/g;
|
|
115
|
+
while ((m = cls.exec(text))) {
|
|
116
|
+
const open = m.index + m[0].length - 1;
|
|
117
|
+
const close = matchBracket(text, open);
|
|
118
|
+
const end = close > 0 ? close : m.index + 3000;
|
|
119
|
+
const name = findKeyString(text, "name", open, end, { open, depth: 1 });
|
|
120
|
+
const desc = findKeyString(text, "description", open, end, { open, depth: 1 });
|
|
121
|
+
push({ name: name?.value ?? m[1], framework: frameworkOf(text, false, "langchain"), index: m.index, description: desc?.value ?? "", annotations: {} });
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function extractPython(text, push) {
|
|
126
|
+
let m;
|
|
127
|
+
|
|
128
|
+
// @mcp.tool(), @server.tool(name=...), @tool, @tool("name"), @function_tool
|
|
129
|
+
const deco = /^[ \t]*@((?:[A-Za-z_]\w*\.)*)(tool|function_tool)\b/gm;
|
|
130
|
+
while ((m = deco.exec(text))) {
|
|
131
|
+
let i = m.index + m[0].length;
|
|
132
|
+
let decoArgs = "";
|
|
133
|
+
const p = skipWs(text, i, true);
|
|
134
|
+
if (text[p] === "(") {
|
|
135
|
+
const close = matchBracket(text, p, { python: true });
|
|
136
|
+
if (close < 0) continue;
|
|
137
|
+
decoArgs = text.slice(p, close + 1);
|
|
138
|
+
i = close + 1;
|
|
139
|
+
}
|
|
140
|
+
const nl = text.indexOf("\n", i);
|
|
141
|
+
if (nl < 0) continue;
|
|
142
|
+
const def = /^(?:\s*\n)*(?:[ \t]*@[^\n]*\n)*[ \t]*(?:async\s+)?def\s+([A-Za-z_]\w*)\s*\(/.exec(text.slice(nl));
|
|
143
|
+
if (!def) continue;
|
|
144
|
+
const defParen = nl + def.index + def[0].length - 1;
|
|
145
|
+
let name = def[1];
|
|
146
|
+
const named = /\bname\s*=\s*/.exec(decoArgs);
|
|
147
|
+
if (named) {
|
|
148
|
+
const s = readString(decoArgs, named.index + named[0].length);
|
|
149
|
+
if (s) name = s.value;
|
|
150
|
+
} else {
|
|
151
|
+
const s = readString(decoArgs, 1);
|
|
152
|
+
if (s && s.start === skipWs(decoArgs, 1)) name = s.value;
|
|
153
|
+
}
|
|
154
|
+
let description = "";
|
|
155
|
+
const descArg = /\bdescription\s*=\s*/.exec(decoArgs);
|
|
156
|
+
if (descArg) description = readString(decoArgs, descArg.index + descArg[0].length)?.value ?? "";
|
|
157
|
+
if (!description) {
|
|
158
|
+
const parenClose = matchBracket(text, defParen, { python: true });
|
|
159
|
+
if (parenClose > 0) {
|
|
160
|
+
const doc = /^\s*(?:->[^:\n]*)?:\s*\n\s*([rRuU]?(?:"""|'''))/.exec(text.slice(parenClose + 1));
|
|
161
|
+
if (doc) description = readString(text, parenClose + 1 + doc.index + doc[0].length - doc[1].length)?.value ?? "";
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
const prefix = m[1].replace(/\.$/, "");
|
|
165
|
+
const hint = prefix ? "mcp" : "decorator";
|
|
166
|
+
let framework = frameworkOf(text, true, hint);
|
|
167
|
+
if (m[2] === "function_tool") framework = "openai-agents";
|
|
168
|
+
push({ name, framework, index: m.index, description, annotations: annotationsIn(decoArgs) });
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Tool(name=..., ...), types.Tool(...), StructuredTool.from_function(...), FunctionTool(...)
|
|
172
|
+
const ctor = /\b(?:types\.)?(?:Tool|StructuredTool\.from_function|Tool\.from_function|FunctionTool(?:\.from_defaults)?)\s*\(/g;
|
|
173
|
+
while ((m = ctor.exec(text))) {
|
|
174
|
+
const open = m.index + m[0].length - 1;
|
|
175
|
+
const close = matchBracket(text, open, { python: true });
|
|
176
|
+
if (close < 0) continue;
|
|
177
|
+
const name = findKeyString(text, "name", open, close, { open, depth: 1 });
|
|
178
|
+
if (!name) continue;
|
|
179
|
+
const desc = findKeyString(text, "description", open, close, { open, depth: 1 });
|
|
180
|
+
const call = text.slice(open, close);
|
|
181
|
+
const framework = /\binputSchema\s*=/.test(call) ? "mcp" : frameworkOf(text, true, "ctor");
|
|
182
|
+
push({ name: name.value, framework, index: m.index, description: desc?.value ?? "", annotations: annotationsIn(call) });
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// class X(BaseTool): name: str = "x"
|
|
186
|
+
const cls = /^class\s+([A-Za-z_]\w*)\s*\([^)]*\b(?:BaseTool|StructuredTool)\b[^)]*\)\s*:/gm;
|
|
187
|
+
while ((m = cls.exec(text))) {
|
|
188
|
+
const end = Math.min(text.length, m.index + 3000);
|
|
189
|
+
const name = /\bname\s*(?::\s*[\w\[\]]+\s*)?=\s*/.exec(text.slice(m.index, end));
|
|
190
|
+
const nameValue = name ? readString(text, m.index + name.index + name[0].length)?.value : null;
|
|
191
|
+
const desc = /\bdescription\s*(?::\s*[\w\[\]]+\s*)?=\s*/.exec(text.slice(m.index, end));
|
|
192
|
+
const descValue = desc ? readString(text, m.index + desc.index + desc[0].length)?.value : "";
|
|
193
|
+
push({ name: nameValue ?? m[1], framework: frameworkOf(text, true, "class"), index: m.index, description: descValue ?? "", annotations: {} });
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Object-literal and dict definitions shared by JS, Python and JSON:
|
|
198
|
+
// { name, description, inputSchema } (MCP list_tools)
|
|
199
|
+
// { name, description, input_schema } (Anthropic tool use)
|
|
200
|
+
// { type: "function", function: { name, description, parameters } } (OpenAI)
|
|
201
|
+
function extractObjectDefinitions(text, push, isPython) {
|
|
202
|
+
const re = /["']?\bname["']?\s*:\s*(?=[rRuU]?["'`])/g;
|
|
203
|
+
let m;
|
|
204
|
+
while ((m = re.exec(text))) {
|
|
205
|
+
const name = readString(text, m.index + m[0].length);
|
|
206
|
+
if (!name) continue;
|
|
207
|
+
const open = enclosingOpenBrace(text, m.index);
|
|
208
|
+
if (open < 0) continue;
|
|
209
|
+
const close = matchBracket(text, open, { python: isPython });
|
|
210
|
+
if (close < 0) continue;
|
|
211
|
+
if (depthAt(text, open, m.index) !== 1) continue;
|
|
212
|
+
const obj = text.slice(open, close + 1);
|
|
213
|
+
const schemaKey = /["']?\b(inputSchema|input_schema|parameters|args_schema)["']?\s*:/.exec(obj);
|
|
214
|
+
if (!schemaKey) continue;
|
|
215
|
+
const desc = findKeyString(text, "description", open, close, { open, depth: 1 });
|
|
216
|
+
let framework;
|
|
217
|
+
if (schemaKey[1] === "inputSchema") framework = "mcp";
|
|
218
|
+
else if (schemaKey[1] === "input_schema") framework = "anthropic";
|
|
219
|
+
else if (schemaKey[1] === "args_schema") framework = frameworkOf(text, isPython, "object");
|
|
220
|
+
else framework = "openai";
|
|
221
|
+
push({ name: name.value, framework, index: m.index, description: desc?.value ?? "", annotations: annotationsIn(obj) });
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function enclosingOpenBrace(text, index) {
|
|
226
|
+
let depth = 0;
|
|
227
|
+
for (let i = index - 1; i >= Math.max(0, index - 600); i -= 1) {
|
|
228
|
+
const c = text[i];
|
|
229
|
+
if (c === "}") depth += 1;
|
|
230
|
+
else if (c === "{") {
|
|
231
|
+
if (depth === 0) return i;
|
|
232
|
+
depth -= 1;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return -1;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function skipWs(text, i, sameLine = false) {
|
|
239
|
+
let j = i;
|
|
240
|
+
while (j < text.length && (sameLine ? /[ \t]/ : /\s/).test(text[j])) j += 1;
|
|
241
|
+
return j;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// Handler spans for low-level dispatchers: `case "name":` (JS) and
|
|
245
|
+
// `if name == "name":` / `elif name == "name":` (Python).
|
|
246
|
+
function dispatcherSpan(text, toolName) {
|
|
247
|
+
const esc = toolName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
248
|
+
const re = new RegExp(`case\\s+["'\`]${esc}["'\`]\\s*:|(?:if|elif)\\s+[\\w.\\[\\]"']+\\s*==\\s*["']${esc}["']\\s*:`);
|
|
249
|
+
const m = re.exec(text);
|
|
250
|
+
if (!m) return null;
|
|
251
|
+
const rest = text.slice(m.index + m[0].length);
|
|
252
|
+
const next = /\n\s*(?:case\s+["'`]|default\s*:|elif\s|else\s*:)/.exec(rest);
|
|
253
|
+
const lines = rest.split("\n").slice(0, 80).join("\n");
|
|
254
|
+
const end = m.index + m[0].length + Math.min(next ? next.index : rest.length, lines.length);
|
|
255
|
+
return { start: m.index, end };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// Returns tool definitions found in one file, each with a body span (the text
|
|
259
|
+
// from the definition to the next definition, capped) used for side-effect,
|
|
260
|
+
// gate and read-back heuristics.
|
|
261
|
+
export function extractTools(text, relPath) {
|
|
262
|
+
const isPython = /\.py$/i.test(relPath);
|
|
263
|
+
const isJson = /\.json$/i.test(relPath);
|
|
264
|
+
const found = [];
|
|
265
|
+
const seen = new Set();
|
|
266
|
+
const push = (t) => {
|
|
267
|
+
if (!t.name || typeof t.name !== "string" || t.name.length > 120 || /\s{2,}|\n/.test(t.name)) return;
|
|
268
|
+
const key = t.name;
|
|
269
|
+
if (seen.has(key)) return;
|
|
270
|
+
seen.add(key);
|
|
271
|
+
found.push(t);
|
|
272
|
+
};
|
|
273
|
+
if (isJson) extractObjectDefinitions(text, push, false);
|
|
274
|
+
else if (isPython) {
|
|
275
|
+
extractPython(text, push);
|
|
276
|
+
extractObjectDefinitions(text, push, true);
|
|
277
|
+
} else {
|
|
278
|
+
extractJs(text, push);
|
|
279
|
+
extractObjectDefinitions(text, push, false);
|
|
280
|
+
}
|
|
281
|
+
found.sort((a, b) => a.index - b.index);
|
|
282
|
+
const lineOf = makeLineIndex(text);
|
|
283
|
+
// Dispatcher handlers (`case "x":`) belong to their own tool, so a
|
|
284
|
+
// definition span stops where any of them starts.
|
|
285
|
+
const dispatchers = found.map((t) => dispatcherSpan(text, t.name)).filter(Boolean);
|
|
286
|
+
return found.map((t, i) => {
|
|
287
|
+
const nextIndex = i + 1 < found.length ? found[i + 1].index : text.length;
|
|
288
|
+
let end = nextIndex;
|
|
289
|
+
for (const d of dispatchers) if (d.start > t.index && d.start < end) end = d.start;
|
|
290
|
+
const startLine = lineOf(t.index);
|
|
291
|
+
if (lineOf(end) - startLine > MAX_SPAN_LINES) {
|
|
292
|
+
let n = 0;
|
|
293
|
+
let j = t.index;
|
|
294
|
+
while (j < end && n < MAX_SPAN_LINES) {
|
|
295
|
+
j = text.indexOf("\n", j + 1);
|
|
296
|
+
if (j < 0) {
|
|
297
|
+
j = end;
|
|
298
|
+
break;
|
|
299
|
+
}
|
|
300
|
+
n += 1;
|
|
301
|
+
}
|
|
302
|
+
end = j;
|
|
303
|
+
}
|
|
304
|
+
const spans = [{ start: t.index, end }];
|
|
305
|
+
const dispatch = dispatcherSpan(text, t.name);
|
|
306
|
+
if (dispatch && (dispatch.start < t.index || dispatch.start >= end)) spans.push(dispatch);
|
|
307
|
+
return { ...t, line: startLine, spans };
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// Relative imports followed from an MCP server entry file.
|
|
312
|
+
export function relativeImports(text, isPython) {
|
|
313
|
+
const out = [];
|
|
314
|
+
let m;
|
|
315
|
+
if (isPython) {
|
|
316
|
+
const re = /^\s*from\s+(\.+[\w.]*|[A-Za-z_][\w.]*)\s+import\s+([^\n]+)/gm;
|
|
317
|
+
while ((m = re.exec(text))) out.push({ module: m[1], names: m[2] });
|
|
318
|
+
} else {
|
|
319
|
+
const re = /(?:import|export)\s[^'"`;]*?from\s*["'](\.{1,2}\/[^"']+)["']|import\s*\(\s*["'](\.{1,2}\/[^"']+)["']\s*\)|require\(\s*["'](\.{1,2}\/[^"']+)["']\s*\)|import\s+["'](\.{1,2}\/[^"']+)["']/g;
|
|
320
|
+
while ((m = re.exec(text))) out.push({ module: m[1] ?? m[2] ?? m[3] ?? m[4] });
|
|
321
|
+
}
|
|
322
|
+
return out;
|
|
323
|
+
}
|
package/scan/gates.mjs
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// Gate and read-back heuristics over handler text.
|
|
2
|
+
//
|
|
3
|
+
// A gate is something that can stop the call before it runs: an Intentrax
|
|
4
|
+
// admission or execute call (SDK or a generated .intentrax/hooks/ entrypoint),
|
|
5
|
+
// or another approval step (Vercel AI SDK needsApproval, LangGraph interrupt,
|
|
6
|
+
// LangChain human-approval handlers, MCP elicitation, OpenAI Agents
|
|
7
|
+
// needs_approval). A read-back is a read of the affected state after the
|
|
8
|
+
// action. Both are recognized by name only, so both are heuristic.
|
|
9
|
+
|
|
10
|
+
import { allSideEffectsIn, sideEffectsIn } from "./classify.mjs";
|
|
11
|
+
|
|
12
|
+
// Generated by `npx @intentrax/sdk init <adapter>` (cli/intentrax.mjs ADAPTERS).
|
|
13
|
+
const INTENTRAX_HOOK_ENTRYPOINTS = [
|
|
14
|
+
"beforeClaudeCodeToolUse", "beforeCursorShellExecution", "beforeMCPToolCall",
|
|
15
|
+
"withIntentraxLangChainCallback", "withIntentraxLangGraphNode", "withIntentraxVercelAIRoute",
|
|
16
|
+
"withIntentraxCustomAgentAdmission", "withIntentraxCrewAIStep", "withIntentraxAutoGenA2AWrapper",
|
|
17
|
+
"withIntentraxOpenClawAgent", "withIntentraxN8NRequestNode", "withIntentraxDeepFlowStep",
|
|
18
|
+
];
|
|
19
|
+
|
|
20
|
+
const INTENTRAX_GATE = new RegExp(
|
|
21
|
+
"\\b(?:admitAgentGatewayHttp|admitAgentGateway|admit_agent_gateway|executeIntentHttp|execute_intent|submit\\w*Admission|" +
|
|
22
|
+
INTENTRAX_HOOK_ENTRYPOINTS.join("|") +
|
|
23
|
+
"|withIntentrax\\w+)\\s*\\(",
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
// An approval flag counts only when it is not explicitly disabled:
|
|
27
|
+
// `needsApproval: false` / `needs_approval=False` / `requireApproval: null` are
|
|
28
|
+
// not gates.
|
|
29
|
+
const APPROVAL_GATE = /\bneedsApproval\s*:\s*(?:true\b|async\b|\(|(?!(?:false|null|undefined)\b)[A-Za-z_$])|\bneeds_approval\s*=\s*(?:True\b|(?!(?:False|None)\b)[A-Za-z_])|\brequires?_?[aA]pproval\b(?!\s*[:=]\s*(?:false|False|null|None|undefined|0)\b)|\bhuman_?[iI]n_?[tT]he_?[lL]oop|HumanInTheLoopMiddleware|HumanApprovalCallbackHandler|(?<![.\w$])interrupt\s*\(|\binterrupt_before\b|\binterruptBefore\b|\belicitInput\s*\(|\.elicit\s*\(|\bawait_?[aA]pproval\b|\brequest_?[aA]pproval\b|\bapproval_?[gG]ate\b/;
|
|
30
|
+
|
|
31
|
+
const READ_BACK_STRONG = /\bconfirmThenReport\b|\bconfirm_then_report\b|\bread_?[bB]ack\b|\breadback\b|\bwaitUntil\w+\s*\(|\bget_waiter\s*\(|\bverify(?:Effect|Deleted|Removed|After|State|Outcome|Result)\w*\s*\(|\bverify_(?:effect|deleted|removed|after|state|outcome|result)\w*\s*\(|\bconfirm(?:Deleted|Removed|State|Effect)\w*\s*\(|@intentrax\/sdk\/readback/;
|
|
32
|
+
const READ_AFTER = /\.(?:get|retrieve|describe\w*|head\w*|findUnique|findFirst|findOne|exists|fetch\w*|read\w*|list\w*)\s*\(|\bSELECT\s+[\w*]/i;
|
|
33
|
+
|
|
34
|
+
const SUCCESS_TEXT = /["'`][^"'`\n]{0,80}\b(?:deleted|removed|dropped|destroyed|refunded|sent|deployed|merged|transferred|charged|paid|succeeded|successfully|success|done|completed|created|updated)\b[^"'`\n]{0,80}["'`]|\b(?:success|ok|deleted|done)\s*[:=]\s*(?:true|True)\b|\bstatus\s*[:=]\s*["'](?:ok|success|succeeded|done|completed)["']/i;
|
|
35
|
+
|
|
36
|
+
function firstIndex(re, text) {
|
|
37
|
+
const m = re.exec(text);
|
|
38
|
+
return m ? m.index : -1;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// `spanText` is the tool's own handler text; `fileText` the whole file.
|
|
42
|
+
export function assessGate(spanText, fileText) {
|
|
43
|
+
const effects = sideEffectsIn(spanText);
|
|
44
|
+
const effectAt = effects.length ? Math.min(...effects.map((e) => e.index)) : -1;
|
|
45
|
+
const reasons = [];
|
|
46
|
+
|
|
47
|
+
const ix = firstIndex(INTENTRAX_GATE, spanText);
|
|
48
|
+
if (ix >= 0) {
|
|
49
|
+
if (effectAt >= 0 && ix > effectAt) {
|
|
50
|
+
reasons.push("an Intentrax call appears after the side effect in the handler, so it does not gate it");
|
|
51
|
+
} else {
|
|
52
|
+
return { gated: true, kind: "intentrax", heuristic: true, reasons: ["handler calls an Intentrax admission/execute entrypoint before acting"] };
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const ax = firstIndex(APPROVAL_GATE, spanText);
|
|
56
|
+
if (ax >= 0 && !(effectAt >= 0 && ax > effectAt)) {
|
|
57
|
+
return { gated: true, kind: "approval", heuristic: true, reasons: ["handler has an approval step (needsApproval / interrupt / elicitation / human-in-the-loop)"] };
|
|
58
|
+
}
|
|
59
|
+
if (fileText && INTENTRAX_GATE.test(fileText) && ix < 0) {
|
|
60
|
+
return { gated: true, kind: "intentrax", heuristic: true, reasons: ["an Intentrax admission/execute call is in the same file (assumed to be a shared dispatcher)"] };
|
|
61
|
+
}
|
|
62
|
+
if (fileText && APPROVAL_GATE.test(fileText) && ax < 0) {
|
|
63
|
+
return { gated: true, kind: "approval", heuristic: true, reasons: ["an approval step is in the same file (assumed to cover this tool)"] };
|
|
64
|
+
}
|
|
65
|
+
return { gated: false, kind: null, heuristic: true, reasons };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function assessReadBack(spanText) {
|
|
69
|
+
if (READ_BACK_STRONG.test(spanText)) {
|
|
70
|
+
return { present: true, heuristic: true, reasons: ["handler calls a read-back/confirmation step"], successMessage: SUCCESS_TEXT.test(spanText) };
|
|
71
|
+
}
|
|
72
|
+
// Every occurrence, so a repeated mutation after an earlier read is caught.
|
|
73
|
+
const effects = allSideEffectsIn(spanText);
|
|
74
|
+
if (effects.length) {
|
|
75
|
+
const effectAt = effects[effects.length - 1].index;
|
|
76
|
+
const after = spanText.slice(effectAt + 1);
|
|
77
|
+
// Skip the effect's own call expression before looking for a read.
|
|
78
|
+
const rest = after.slice(after.indexOf(")") + 1);
|
|
79
|
+
if (READ_AFTER.test(rest)) {
|
|
80
|
+
return { present: true, heuristic: true, reasons: ["handler reads state back after the side effect"], successMessage: SUCCESS_TEXT.test(spanText) };
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return { present: false, heuristic: true, reasons: ["no read of the affected state after the action"], successMessage: SUCCESS_TEXT.test(spanText) };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function mentionsIntentraxGate(text) {
|
|
87
|
+
return INTENTRAX_GATE.test(text);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function hookCommandKind(command) {
|
|
91
|
+
if (/intentrax/i.test(command)) return "intentrax";
|
|
92
|
+
if (/approv|gate|guard|policy|confirm|deny|block|allowlist|permission/i.test(command)) return "approval";
|
|
93
|
+
return null;
|
|
94
|
+
}
|
package/scan/report.mjs
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Text and JSON rendering for `intentrax scan`. The first line of the text
|
|
2
|
+
// report is the catch. Only names, locations and matched verbs are printed:
|
|
3
|
+
// never credential values, URLs, descriptions or source snippets.
|
|
4
|
+
|
|
5
|
+
export const EXIT_CODES = Object.freeze({ NO_FINDINGS: 0, FINDINGS: 20, SCAN_ERROR: 2 });
|
|
6
|
+
|
|
7
|
+
export function exitCodeFor(result) {
|
|
8
|
+
return result.findings.length ? EXIT_CODES.FINDINGS : EXIT_CODES.NO_FINDINGS;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function credLine(c) {
|
|
12
|
+
const parts = [`${c.name}${c.refersTo ? ` (from ${c.refersTo})` : ""} at ${c.location}`];
|
|
13
|
+
if (c.inline) parts.push("value written inline in the file (not shown)");
|
|
14
|
+
if (c.breadth) parts.push(`${c.breadth.label}: ${c.breadth.reason}`);
|
|
15
|
+
return parts.join("; ");
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function formatText(result) {
|
|
19
|
+
const out = [];
|
|
20
|
+
if (result.findings.length) {
|
|
21
|
+
for (const f of result.findings) out.push(f.line);
|
|
22
|
+
} else {
|
|
23
|
+
out.push(result.firstLine);
|
|
24
|
+
}
|
|
25
|
+
out.push("");
|
|
26
|
+
|
|
27
|
+
if (result.findings.length) {
|
|
28
|
+
out.push("Details (every classification below is heuristic):");
|
|
29
|
+
for (const f of result.findings) {
|
|
30
|
+
out.push("");
|
|
31
|
+
out.push(`[${f.id}] ${f.line}`);
|
|
32
|
+
out.push(` where: ${f.location}${f.server ? ` (MCP server "${f.server.name}", configured at ${f.server.config})` : ""}`);
|
|
33
|
+
out.push(` classified (heuristic): ${f.classification.label}. ${f.classification.reasons.join("; ")}`);
|
|
34
|
+
for (const c of f.credentials) out.push(` credential (heuristic): ${credLine(c)}`);
|
|
35
|
+
out.push(` gate (heuristic): ${f.gate.gated ? f.gate.reasons.join("; ") : ["none found", ...f.gate.reasons].join("; ")}`);
|
|
36
|
+
if (f.readBack.present !== null) out.push(` read-back (heuristic): ${f.readBack.present ? f.readBack.reasons.join("; ") : "none found"}`);
|
|
37
|
+
for (const n of f.notes) out.push(` note: ${n}`);
|
|
38
|
+
f.recommendations.forEach((r, i) => {
|
|
39
|
+
out.push(` ${i + 1}. ${r.kind === "least-privilege" ? "Least privilege" : "Intentrax"}: ${r.text}`);
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
out.push("");
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
for (const w of result.warnings) out.push(`warning: ${w}`);
|
|
46
|
+
const s = result.summary;
|
|
47
|
+
out.push(
|
|
48
|
+
`Summary: ${s.filesScanned} file(s) scanned; ${s.actionsFound} agent-reachable action(s), ${s.consequentialActions} consequential, ${s.gatedActions} gated; ` +
|
|
49
|
+
`${s.mcpServers} MCP server(s) configured${s.serversWithUnlistedTools ? `, ${s.serversWithUnlistedTools} with tools not listed statically` : ""}; ` +
|
|
50
|
+
`${s.findings} finding(s) (${s.byType.EXPOSED} EXPOSED, ${s.byType.UNGATED} UNGATED, ${s.byType["SELF-REPORTED"]} SELF-REPORTED).`,
|
|
51
|
+
);
|
|
52
|
+
out.push(result.note);
|
|
53
|
+
return out.join("\n") + "\n";
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function formatJson(result) {
|
|
57
|
+
return JSON.stringify(result, null, 2) + "\n";
|
|
58
|
+
}
|