actionmcp 0.0.0-stage → 0.2.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 (71) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +74 -2
  3. package/dist/analyzer/config.d.ts +15 -0
  4. package/dist/analyzer/config.js +43 -0
  5. package/dist/analyzer/diagnostics.js +136 -0
  6. package/dist/analyzer/explicit.js +128 -0
  7. package/dist/analyzer/index.js +191 -0
  8. package/dist/analyzer/jsdoc.js +32 -0
  9. package/dist/analyzer/options.js +65 -0
  10. package/dist/analyzer/routes.js +105 -0
  11. package/dist/analyzer/scan.js +292 -0
  12. package/dist/analyzer/source.js +100 -0
  13. package/dist/analyzer/toolchain.js +27 -0
  14. package/dist/analyzer/types.js +141 -0
  15. package/dist/cli/bin.d.ts +1 -0
  16. package/dist/cli/bin.js +5 -0
  17. package/dist/cli/commands.js +107 -0
  18. package/dist/cli/environment.js +53 -0
  19. package/dist/cli/index.js +97 -0
  20. package/dist/cli/output.js +27 -0
  21. package/dist/cli/project.js +33 -0
  22. package/dist/client.d.ts +6 -0
  23. package/dist/client.js +4 -0
  24. package/dist/config.d.ts +9 -0
  25. package/dist/config.js +84 -0
  26. package/dist/core/compare.js +6 -0
  27. package/dist/core/events.js +12 -0
  28. package/dist/core/execute.js +70 -0
  29. package/dist/core/formdata.js +15 -0
  30. package/dist/core/guards.js +8 -0
  31. package/dist/core/match.js +16 -0
  32. package/dist/core/names.js +51 -0
  33. package/dist/core/result.d.ts +18 -0
  34. package/dist/core/result.js +85 -0
  35. package/dist/core/schema.d.ts +6 -0
  36. package/dist/core/schema.js +90 -0
  37. package/dist/core/types.d.ts +34 -0
  38. package/dist/core/webmcp.js +95 -0
  39. package/dist/generator/index.js +36 -0
  40. package/dist/generator/render.js +91 -0
  41. package/dist/generator/watch.js +76 -0
  42. package/dist/index.d.ts +8 -0
  43. package/dist/index.js +5 -0
  44. package/dist/next/NavigateTool.js +40 -0
  45. package/dist/next/config-store.js +12 -0
  46. package/dist/next/redirect.js +15 -0
  47. package/dist/next/routes.d.ts +3 -0
  48. package/dist/next/routes.js +62 -0
  49. package/dist/react/AgentTools.d.ts +14 -0
  50. package/dist/react/AgentTools.js +35 -0
  51. package/dist/react/Confirm.d.ts +3 -0
  52. package/dist/react/Confirm.js +149 -0
  53. package/dist/react/Devtools.d.ts +2 -0
  54. package/dist/react/Devtools.js +13 -0
  55. package/dist/react/DevtoolsPanel.js +223 -0
  56. package/dist/react/Provider.d.ts +6 -0
  57. package/dist/react/Provider.js +23 -0
  58. package/dist/react/Registrar.js +12 -0
  59. package/dist/react/context.d.ts +24 -0
  60. package/dist/react/context.js +5 -0
  61. package/dist/react/useAgentTools.js +105 -0
  62. package/dist/registry.d.ts +4 -0
  63. package/dist/registry.js +4 -0
  64. package/dist/server/agent.d.ts +43 -0
  65. package/dist/server/agent.js +34 -0
  66. package/dist/server/index.d.ts +6 -0
  67. package/dist/server/index.js +4 -0
  68. package/dist/server/registry.d.ts +53 -0
  69. package/dist/server/registry.js +93 -0
  70. package/dist/server/resolve.js +68 -0
  71. package/package.json +102 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Valentin Galfre
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,75 @@
1
- # Temporary Holding Version
1
+ # actionmcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ WebMCP tools from your Server Actions.
4
+
5
+ actionmcp turns the Server Functions and routes that you opt in, in a Next.js App Router app, into typed WebMCP tools. Browser agents discover the tools on `document.modelContext` and call them with the user's session.
6
+
7
+ The documentation is in the repository: https://github.com/galfrevn/actionmcp#readme
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install actionmcp
13
+ ```
14
+
15
+ actionmcp requires Next.js 16.x and React 19.2 or later. The experimental `@agent` tag also needs `ts-json-schema-generator` as a development dependency.
16
+
17
+ ## Usage
18
+
19
+ `next.config.ts`:
20
+
21
+ ```ts
22
+ import { withAgentTools } from 'actionmcp/config'
23
+ import type { NextConfig } from 'next'
24
+
25
+ const nextConfig: NextConfig = {}
26
+
27
+ export default withAgentTools()(nextConfig)
28
+ ```
29
+
30
+ `app/todos/actions.ts`:
31
+
32
+ ```ts
33
+ 'use server'
34
+ import { agent } from 'actionmcp/server'
35
+ import { z } from 'zod'
36
+
37
+ export const addTodo = agent(
38
+ {
39
+ description: 'Add an item to the signed-in user’s todo list. Returns the created item.',
40
+ input: z.object({ text: z.string().min(1).max(200) }),
41
+ },
42
+ async ({ text }) => {
43
+ const user = await requireUser()
44
+ return db.todo.create({ data: { text, userId: user.id } })
45
+ },
46
+ )
47
+ ```
48
+
49
+ `app/todos/layout.tsx`:
50
+
51
+ ```tsx
52
+ import { AgentTools } from 'actionmcp'
53
+
54
+ export default function Layout({ children }: { children: React.ReactNode }) {
55
+ return (
56
+ <>
57
+ {children}
58
+ <AgentTools />
59
+ </>
60
+ )
61
+ }
62
+ ```
63
+
64
+ ## Security defaults
65
+
66
+ - Nothing becomes a tool without `agent()`, `tool()`, or `@agent`.
67
+ - A tool is consequential unless it is marked `readOnly`.
68
+ - An in-page dialog asks a human before a consequential tool runs.
69
+ - Tools run through the native Server Function RPC. actionmcp adds no endpoint.
70
+
71
+ The checklist for each tool and the threat model are in [security.md](https://github.com/galfrevn/actionmcp/blob/main/documentation/security.md).
72
+
73
+ ## License
74
+
75
+ MIT
@@ -0,0 +1,15 @@
1
+ export interface AgentToolsConfig {
2
+ registry?: string;
3
+ scan?: string[];
4
+ outDir?: string;
5
+ jsdoc?: boolean;
6
+ auth?: string[];
7
+ }
8
+ export interface ResolvedConfig {
9
+ cwd: string;
10
+ registry: string | undefined;
11
+ scan: string[];
12
+ outDir: string;
13
+ jsdoc: boolean;
14
+ auth: string[];
15
+ }
@@ -0,0 +1,43 @@
1
+ import { existsSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ // src/analyzer/config.ts
4
+ const DEFAULT_SCAN = [
5
+ "app/**",
6
+ "lib/**",
7
+ "src/**"
8
+ ];
9
+ const DEFAULT_OUT_DIR = ".agent-tools";
10
+ const DEFAULT_REGISTRY_FILES = [
11
+ "agent-tools.ts",
12
+ "agent-tools.tsx",
13
+ "agent-tools.js",
14
+ "agent-tools.mjs",
15
+ "src/agent-tools.ts"
16
+ ];
17
+ const DEFAULT_AUTH_FUNCTIONS = [
18
+ "auth",
19
+ "getSession",
20
+ "getServerSession",
21
+ "verifySession",
22
+ "requireUser",
23
+ "requireAuth",
24
+ "requireSession",
25
+ "getUser",
26
+ "getCurrentUser",
27
+ "currentUser"
28
+ ];
29
+ function resolveConfig(config = {}, cwd = process.cwd()) {
30
+ return {
31
+ cwd,
32
+ registry: resolveRegistry(config.registry, cwd),
33
+ scan: config.scan ?? DEFAULT_SCAN,
34
+ outDir: resolve(cwd, config.outDir ?? ".agent-tools"),
35
+ jsdoc: config.jsdoc ?? false,
36
+ auth: config.auth ?? DEFAULT_AUTH_FUNCTIONS
37
+ };
38
+ }
39
+ function resolveRegistry(registry, cwd) {
40
+ if (registry) return resolve(cwd, registry);
41
+ return DEFAULT_REGISTRY_FILES.map((file) => resolve(cwd, file)).find((file) => existsSync(file));
42
+ }
43
+ export { DEFAULT_AUTH_FUNCTIONS, DEFAULT_OUT_DIR, DEFAULT_REGISTRY_FILES, DEFAULT_SCAN, resolveConfig };
@@ -0,0 +1,136 @@
1
+ import { compareText } from "../core/compare.js";
2
+ // src/analyzer/diagnostics.ts
3
+ const DIAGNOSTIC_RULES = {
4
+ AT001: {
5
+ level: "error",
6
+ summary: "Invalid tool name",
7
+ fix: "Use a string literal with 1 to 128 characters from A-Z, a-z, 0-9, \"_\", \"-\", and \".\"."
8
+ },
9
+ AT002: {
10
+ level: "error",
11
+ summary: "Duplicate or reserved tool name",
12
+ fix: "Rename the tool with the `name` option, or remove the duplicate registration."
13
+ },
14
+ AT003: {
15
+ level: "error",
16
+ summary: "Empty description",
17
+ fix: "Describe what the tool does, its side effects, and what it returns."
18
+ },
19
+ AT004: {
20
+ level: "error",
21
+ summary: "Tool is not an exported Server Function",
22
+ fix: "Export the function from a file that starts with the 'use server' directive."
23
+ },
24
+ AT005: {
25
+ level: "error",
26
+ summary: "Tool options are not literals",
27
+ fix: "Pass an object literal with a string literal `description`. Metadata must come from source code, never from data."
28
+ },
29
+ AT006: {
30
+ level: "error",
31
+ summary: "Unknown @agent modifier",
32
+ fix: "Use readonly, consequential, untrusted-output, formdata, or name=<tool-name>."
33
+ },
34
+ AT007: {
35
+ level: "error",
36
+ summary: "Registry file cannot be analyzed",
37
+ fix: "Default-export defineAgentTools({ ... }) with an object literal whose values are tool(...) calls."
38
+ },
39
+ AT101: {
40
+ level: "warn",
41
+ summary: "Schema cannot be converted to JSON Schema",
42
+ fix: "The tool is registered without inputSchema. Use agent() or tool() with a Standard Schema validator."
43
+ },
44
+ AT102: {
45
+ level: "warn",
46
+ summary: "JSDoc tool without detectable runtime validation",
47
+ fix: "Validate the input inside the action, or wrap the action in agent() with an input schema."
48
+ },
49
+ AT103: {
50
+ level: "warn",
51
+ summary: "Consequential tool with confirm: 'never'",
52
+ fix: "Remove confirm: 'never' so the page asks a human before the tool runs."
53
+ },
54
+ AT104: {
55
+ level: "warn",
56
+ summary: "More than 32 tools",
57
+ fix: "Scope tools per route with <AgentTools include={[...]} /> in segment layouts."
58
+ },
59
+ AT105: {
60
+ level: "warn",
61
+ summary: "Action without a detectable authentication call",
62
+ fix: "Call your auth function inside the action, or list its name in the `auth` option."
63
+ },
64
+ AT106: {
65
+ level: "warn",
66
+ summary: "Output with free-form strings without untrustedOutput",
67
+ fix: "Set untrustedOutput: true when the output can contain user-generated or third-party content."
68
+ },
69
+ AT107: {
70
+ level: "warn",
71
+ summary: "Input asks for personal data that the handler does not use",
72
+ fix: "Remove the field from the input schema. Request only identifiers and domain values."
73
+ },
74
+ AT108: {
75
+ level: "warn",
76
+ summary: "Description shorter than 20 characters",
77
+ fix: "Describe what the tool does, its side effects, and what it returns."
78
+ },
79
+ AT109: {
80
+ level: "warn",
81
+ summary: "agent() call that the analyzer cannot register",
82
+ fix: "Assign the agent() call to an exported const in a 'use server' file, or list the function in agent-tools.ts. To share logic, wrap the handler and not the agent() call."
83
+ },
84
+ AT201: {
85
+ level: "error",
86
+ summary: "Unsupported Next.js version",
87
+ fix: "Install Next.js 16.x."
88
+ },
89
+ AT202: {
90
+ level: "error",
91
+ summary: "Unsupported React version",
92
+ fix: "Install React 19.2 or later."
93
+ },
94
+ AT203: {
95
+ level: "warn",
96
+ summary: "Validator without Standard JSON Schema support",
97
+ fix: "Upgrade to Zod 4.2+, ArkType 2.1.28+, or Valibot 1.2+ with @valibot/to-json-schema."
98
+ },
99
+ AT204: {
100
+ level: "warn",
101
+ summary: "Origin trial token is not set",
102
+ fix: "Set NEXT_PUBLIC_WEBMCP_OT_TOKEN, or pass originTrialToken to <AgentTools />, to enable WebMCP in Chrome and Edge without flags."
103
+ },
104
+ AT205: {
105
+ level: "warn",
106
+ summary: "Explicit tool without an input schema",
107
+ fix: "Move the action's schema out of the 'use server' file into a regular module and pass it as `input`."
108
+ },
109
+ AT206: {
110
+ level: "error",
111
+ summary: "The @agent path needs ts-json-schema-generator",
112
+ fix: "Install it as a development dependency: npm install --save-dev ts-json-schema-generator."
113
+ }
114
+ };
115
+ function createDiagnostic(code, location, detail, tool) {
116
+ const rule = DIAGNOSTIC_RULES[code];
117
+ return {
118
+ code,
119
+ level: rule.level,
120
+ message: detail ? `${rule.summary}: ${detail}` : rule.summary,
121
+ fix: rule.fix,
122
+ ...location,
123
+ ...tool === void 0 ? {} : { tool }
124
+ };
125
+ }
126
+ function hasErrors(diagnostics) {
127
+ return diagnostics.some((diagnostic) => diagnostic.level === "error");
128
+ }
129
+ function formatDiagnostic(diagnostic) {
130
+ const location = `${diagnostic.file}:${diagnostic.line}:${diagnostic.column}`;
131
+ return `${diagnostic.level === "error" ? "error" : "warn "} ${diagnostic.code} ${location} ${diagnostic.message}\n fix: ${diagnostic.fix}`;
132
+ }
133
+ function sortDiagnostics(diagnostics) {
134
+ return diagnostics.toSorted((left, right) => compareText(left.file, right.file) || left.line - right.line || left.column - right.column || compareText(left.code, right.code));
135
+ }
136
+ export { DIAGNOSTIC_RULES, createDiagnostic, formatDiagnostic, hasErrors, sortDiagnostics };
@@ -0,0 +1,128 @@
1
+ import { resolveAnnotations } from "../server/registry.js";
2
+ import { createDiagnostic } from "./diagnostics.js";
3
+ import { readToolOptions } from "./options.js";
4
+ import { propertyName, walk } from "./source.js";
5
+ // src/analyzer/explicit.ts
6
+ const SERVER_ENTRY = "actionmcp/server";
7
+ const ADAPTERS = {
8
+ fromFormDataAction: "formdata",
9
+ fromFormAction: "form",
10
+ fromSafeAction: "safe-action"
11
+ };
12
+ function scanRegistryModule(module) {
13
+ const scan = {
14
+ tools: [],
15
+ references: [],
16
+ diagnostics: []
17
+ };
18
+ const imports = importedNames(module);
19
+ const definition = findCall(module.program, imports, "defineAgentTools");
20
+ const [tools] = definition?.arguments ?? [];
21
+ if (tools?.type !== "ObjectExpression") {
22
+ scan.diagnostics.push(createDiagnostic("AT007", module.locate(definition?.start ?? 0), "no defineAgentTools({ ... }) call with an object literal"));
23
+ return scan;
24
+ }
25
+ for (const property of tools.properties) {
26
+ if (property.type === "SpreadElement") {
27
+ scan.diagnostics.push(createDiagnostic("AT007", module.locate(property.start), "spread elements hide the registered tools"));
28
+ continue;
29
+ }
30
+ const key = propertyName(property.key, property.computed);
31
+ if (key === void 0) {
32
+ scan.diagnostics.push(createDiagnostic("AT007", module.locate(property.start), "computed keys hide the tool name"));
33
+ continue;
34
+ }
35
+ addTool(module, scan, imports, key, property.value);
36
+ }
37
+ return scan;
38
+ }
39
+ function addTool(module, scan, imports, key, value) {
40
+ const line = module.locate(value.start).line;
41
+ if (value.type === "Identifier") {
42
+ const tool = {
43
+ name: key,
44
+ kind: "explicit",
45
+ source: {
46
+ file: module.file,
47
+ export: value.name,
48
+ line
49
+ },
50
+ description: "",
51
+ schemaSource: "standard-schema",
52
+ annotations: resolveAnnotations(void 0, void 0, void 0),
53
+ confirm: "consequential",
54
+ validated: true,
55
+ diagnostics: []
56
+ };
57
+ scan.tools.push(tool);
58
+ scan.references.push({
59
+ tool,
60
+ exportName: importedBindings(module).get(value.name) ?? value.name
61
+ });
62
+ return;
63
+ }
64
+ if (!isCallTo(value, imports, "tool")) {
65
+ scan.diagnostics.push(createDiagnostic("AT007", module.locate(value.start), `"${key}" is not a tool(...) call`, key));
66
+ return;
67
+ }
68
+ const [action, options] = value.arguments;
69
+ const adapterName = action?.type === "CallExpression" && action.callee.type === "Identifier" ? imports.get(action.callee.name) : void 0;
70
+ const adapter = adapterName === void 0 ? void 0 : ADAPTERS[adapterName];
71
+ const target = adapter && action?.type === "CallExpression" ? action.arguments[0] : action;
72
+ const reading = readToolOptions(options, value.start);
73
+ const annotations = resolveAnnotations(reading.readOnly, reading.consequential, reading.untrustedOutput);
74
+ const tool = {
75
+ name: reading.name ?? key,
76
+ kind: "explicit",
77
+ source: {
78
+ file: module.file,
79
+ export: target ? module.text(target) : key,
80
+ line
81
+ },
82
+ description: reading.description ?? "",
83
+ schemaSource: reading.input ? "standard-schema" : "none",
84
+ annotations,
85
+ confirm: reading.confirm ?? "consequential",
86
+ validated: false,
87
+ diagnostics: [],
88
+ ...adapter ? { adapter } : {},
89
+ ...reading.input ? { inputSource: module.text(reading.input) } : {}
90
+ };
91
+ const report = (code, offset, detail) => {
92
+ scan.diagnostics.push(createDiagnostic(code, module.locate(offset), detail, tool.name));
93
+ if (!tool.diagnostics.includes(code)) tool.diagnostics.push(code);
94
+ };
95
+ for (const issue of reading.issues) report(issue.code, issue.offset, issue.detail);
96
+ const descriptionLength = tool.description.trim().length;
97
+ if (descriptionLength > 0 && descriptionLength < 20) report("AT108", value.start, `"${tool.description.trim()}"`);
98
+ if (tool.confirm === "never" && annotations.consequentialHint) report("AT103", value.start);
99
+ if (adapter && !reading.input) report("AT205", value.start);
100
+ scan.tools.push(tool);
101
+ }
102
+ function importedNames(module) {
103
+ const names = /* @__PURE__ */ new Map();
104
+ for (const statement of module.program.body) {
105
+ if (statement.type !== "ImportDeclaration" || statement.source.value !== SERVER_ENTRY) continue;
106
+ for (const specifier of statement.specifiers) if (specifier.type === "ImportSpecifier" && specifier.imported.type === "Identifier") names.set(specifier.local.name, specifier.imported.name);
107
+ }
108
+ return names;
109
+ }
110
+ function importedBindings(module) {
111
+ const bindings = /* @__PURE__ */ new Map();
112
+ for (const statement of module.program.body) {
113
+ if (statement.type !== "ImportDeclaration") continue;
114
+ for (const specifier of statement.specifiers) if (specifier.type === "ImportSpecifier" && specifier.imported.type === "Identifier") bindings.set(specifier.local.name, specifier.imported.name);
115
+ }
116
+ return bindings;
117
+ }
118
+ function isCallTo(node, imports, name) {
119
+ return node.type === "CallExpression" && node.callee.type === "Identifier" && imports.get(node.callee.name) === name;
120
+ }
121
+ function findCall(root, imports, name) {
122
+ let found;
123
+ walk(root, (node) => {
124
+ if (!found && isCallTo(node, imports, name)) found = node;
125
+ });
126
+ return found;
127
+ }
128
+ export { scanRegistryModule };
@@ -0,0 +1,191 @@
1
+ import { compareText } from "../core/compare.js";
2
+ import { readFileSync, statSync } from "node:fs";
3
+ import { join, relative, sep } from "node:path";
4
+ import { glob } from "tinyglobby";
5
+ import { NAVIGATE_TOOL_NAME, describeNameIssue, isReservedToolName, isValidToolName } from "../core/names.js";
6
+ import "./config.js";
7
+ import { NAVIGATE_DESCRIPTION } from "../next/routes.js";
8
+ import { createDiagnostic, sortDiagnostics } from "./diagnostics.js";
9
+ import { scanRegistryModule } from "./explicit.js";
10
+ import { scanRoutes } from "./routes.js";
11
+ import { mayContainTools, scanModule } from "./scan.js";
12
+ import { parseModule } from "./source.js";
13
+ import { inferParameterSchemas } from "./types.js";
14
+ // src/analyzer/index.ts
15
+ const SOURCE_FILE = /\.(?:tsx?|jsx?|mts|mjs)$/;
16
+ const TYPES_CACHE_FILE = "cache/types.json";
17
+ const PACKAGE_MANIFEST = {
18
+ file: "package.json",
19
+ line: 1,
20
+ column: 1
21
+ };
22
+ function createAnalysisCache() {
23
+ return {
24
+ modules: /* @__PURE__ */ new Map(),
25
+ pages: /* @__PURE__ */ new Map()
26
+ };
27
+ }
28
+ async function analyze(config, cache = createAnalysisCache()) {
29
+ const files = await listSourceFiles(config);
30
+ const registryFile = config.registry ? toRelative(config.cwd, config.registry) : void 0;
31
+ const scans = files.filter((file) => file !== registryFile).flatMap((file) => scanFile(config, cache, file) ?? []);
32
+ const listed = new Set(files);
33
+ for (const file of cache.modules.keys()) if (!listed.has(file)) cache.modules.delete(file);
34
+ const tools = scans.flatMap((scan) => scan.tools);
35
+ const diagnostics = scans.flatMap((scan) => scan.diagnostics);
36
+ resolveTypes(config, scans, diagnostics);
37
+ if (config.registry && registryFile) {
38
+ const registry = scanRegistryModule(parseModule(registryFile, readFileSync(config.registry, "utf8")));
39
+ for (const reference of registry.references) adoptDiscoveredTool(tools, reference);
40
+ tools.push(...registry.tools);
41
+ diagnostics.push(...registry.diagnostics);
42
+ }
43
+ const routes = scanRoutes(config.cwd, cache.pages);
44
+ if (scans.some((scan) => scan.usesNavigate)) tools.push(navigateTool());
45
+ diagnostics.push(...checkNames(tools), ...checkToolCount(tools));
46
+ return {
47
+ tools: tools.toSorted((left, right) => compareText(left.name, right.name) || compareText(left.source.file, right.source.file)),
48
+ routes,
49
+ diagnostics: sortDiagnostics(diagnostics),
50
+ registry: registryFile
51
+ };
52
+ }
53
+ async function listSourceFiles(config) {
54
+ const outDir = toRelative(config.cwd, config.outDir);
55
+ return (await glob(config.scan, {
56
+ cwd: config.cwd,
57
+ onlyFiles: true,
58
+ ignore: [
59
+ "**/node_modules/**",
60
+ "**/.next/**",
61
+ `${outDir}/**`,
62
+ "**/*.d.ts"
63
+ ]
64
+ })).filter((file) => SOURCE_FILE.test(file)).toSorted();
65
+ }
66
+ function scanFile(config, cache, file) {
67
+ const absolute = join(config.cwd, file);
68
+ const { mtimeMs, size } = statSync(absolute);
69
+ const stamp = `${mtimeMs}:${size}:${config.jsdoc}`;
70
+ let cached = cache.modules.get(file);
71
+ if (cached?.stamp !== stamp) {
72
+ const code = readFileSync(absolute, "utf8");
73
+ cached = {
74
+ stamp,
75
+ scan: mayContainTools(code) ? scanModule(parseModule(file, code), config) : void 0
76
+ };
77
+ cache.modules.set(file, cached);
78
+ }
79
+ return cached.scan ? structuredClone(cached.scan) : void 0;
80
+ }
81
+ function resolveTypes(config, scans, diagnostics) {
82
+ const requests = scans.flatMap((scan) => scan.typeRequests);
83
+ const inferences = inferParameterSchemas(requests.map((request) => ({
84
+ file: join(config.cwd, request.file),
85
+ parameterOffset: request.parameterOffset
86
+ })), {
87
+ cwd: config.cwd,
88
+ cacheFile: join(config.outDir, TYPES_CACHE_FILE)
89
+ });
90
+ let missingToolchain = false;
91
+ requests.forEach(({ tool, file }, index) => {
92
+ const inference = inferences[index];
93
+ if (inference?.ok) {
94
+ tool.inputSchema = inference.schema;
95
+ return;
96
+ }
97
+ tool.schemaSource = "none";
98
+ const code = inference?.missingToolchain ? "AT206" : "AT101";
99
+ if (!tool.diagnostics.includes(code)) tool.diagnostics.push(code);
100
+ if (code === "AT206") missingToolchain = true;
101
+ else diagnostics.push(createDiagnostic(code, {
102
+ file,
103
+ line: tool.source.line,
104
+ column: 1
105
+ }, inference?.reason, tool.name));
106
+ });
107
+ if (missingToolchain) diagnostics.push(createDiagnostic("AT206", PACKAGE_MANIFEST));
108
+ }
109
+ function adoptDiscoveredTool(tools, { tool, exportName }) {
110
+ const matches = tools.filter((candidate) => candidate.kind === "agent" && candidate.source.export === exportName);
111
+ const [discovered] = matches;
112
+ if (!discovered || matches.length > 1) return;
113
+ tools.splice(tools.indexOf(discovered), 1);
114
+ const { name, kind } = tool;
115
+ Object.assign(tool, discovered, {
116
+ name,
117
+ kind
118
+ });
119
+ }
120
+ function navigateTool() {
121
+ return {
122
+ name: NAVIGATE_TOOL_NAME,
123
+ kind: "navigate",
124
+ source: {
125
+ file: "app",
126
+ export: NAVIGATE_TOOL_NAME,
127
+ line: 1
128
+ },
129
+ description: NAVIGATE_DESCRIPTION,
130
+ schemaSource: "none",
131
+ annotations: {
132
+ readOnlyHint: false,
133
+ consequentialHint: false,
134
+ untrustedContentHint: false
135
+ },
136
+ confirm: "never",
137
+ validated: true,
138
+ diagnostics: []
139
+ };
140
+ }
141
+ function checkNames(tools) {
142
+ const firstByName = /* @__PURE__ */ new Map();
143
+ const diagnostics = [];
144
+ for (const tool of tools) {
145
+ if (tool.kind === "navigate" || tool.name === "") continue;
146
+ const first = firstByName.get(tool.name);
147
+ if (!first) firstByName.set(tool.name, tool);
148
+ const issue = nameIssue(tool.name, first !== void 0);
149
+ if (!issue) continue;
150
+ if (!tool.diagnostics.includes(issue.code)) tool.diagnostics.push(issue.code);
151
+ const duplicateOf = first ? ` It is also defined at ${first.source.file}:${first.source.line}.` : "";
152
+ const location = {
153
+ file: tool.source.file,
154
+ line: tool.source.line,
155
+ column: 1
156
+ };
157
+ diagnostics.push(createDiagnostic(issue.code, location, `${describeNameIssue(issue)}${duplicateOf}`, tool.name));
158
+ }
159
+ return diagnostics;
160
+ }
161
+ function nameIssue(name, isDuplicate) {
162
+ if (!isValidToolName(name)) return {
163
+ code: "AT001",
164
+ name,
165
+ reason: "invalid"
166
+ };
167
+ if (isReservedToolName(name)) return {
168
+ code: "AT002",
169
+ name,
170
+ reason: "reserved"
171
+ };
172
+ return isDuplicate ? {
173
+ code: "AT002",
174
+ name,
175
+ reason: "duplicate"
176
+ } : void 0;
177
+ }
178
+ function checkToolCount(tools) {
179
+ const overflow = tools[32];
180
+ if (!overflow) return [];
181
+ const location = {
182
+ file: overflow.source.file,
183
+ line: overflow.source.line,
184
+ column: 1
185
+ };
186
+ return [createDiagnostic("AT104", location, `${tools.length} tools are defined`)];
187
+ }
188
+ function toRelative(cwd, file) {
189
+ return relative(cwd, file).split(sep).join("/");
190
+ }
191
+ export { analyze, createAnalysisCache };
@@ -0,0 +1,32 @@
1
+ // src/analyzer/jsdoc.ts
2
+ const AGENT_TAG = /(?:^|\s)@agent(?![\w-])([^\n]*)/;
3
+ const ANY_TAG = /(?:^|\s)@[A-Za-z]/;
4
+ const NAME_MODIFIER = /^name=(.+)$/;
5
+ function parseAgentTag(comment) {
6
+ const text = comment.split("\n").map((line) => line.replace(/^\s*\*?\s?/, "").trimEnd()).join("\n");
7
+ const match = AGENT_TAG.exec(text);
8
+ if (!match) return void 0;
9
+ const firstTag = ANY_TAG.exec(text)?.index ?? text.length;
10
+ const tag = {
11
+ description: text.slice(0, firstTag).replace(/\s+/g, " ").trim(),
12
+ readOnly: false,
13
+ consequential: false,
14
+ untrustedOutput: false,
15
+ formData: false,
16
+ unknownModifiers: []
17
+ };
18
+ for (const modifier of (match[1] ?? "").split(/\s+/).filter(Boolean)) {
19
+ const name = NAME_MODIFIER.exec(modifier)?.[1];
20
+ if (name !== void 0) tag.name = name;
21
+ else if (modifier === "readonly") tag.readOnly = true;
22
+ else if (modifier === "consequential") tag.consequential = true;
23
+ else if (modifier === "untrusted-output") tag.untrustedOutput = true;
24
+ else if (modifier === "formdata") tag.formData = true;
25
+ else tag.unknownModifiers.push(modifier);
26
+ }
27
+ return tag;
28
+ }
29
+ function formDataAdapter(parameterCount) {
30
+ return parameterCount >= 2 ? "formdata" : "form";
31
+ }
32
+ export { formDataAdapter, parseAgentTag };