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
@@ -0,0 +1,15 @@
1
+ import { isRecord } from "./guards.js";
2
+ // src/core/formdata.ts
3
+ function toFormData(input) {
4
+ const formData = new FormData();
5
+ if (isRecord(input)) for (const [key, value] of Object.entries(input)) appendValue(formData, key, value);
6
+ return formData;
7
+ }
8
+ function appendValue(formData, key, value) {
9
+ if (value === void 0 || value === null || value === false) return;
10
+ if (value === true) formData.append(key, "on");
11
+ else if (Array.isArray(value)) for (const item of value) appendValue(formData, key, item);
12
+ else if (isRecord(value)) formData.append(key, JSON.stringify(value));
13
+ else formData.append(key, String(value));
14
+ }
15
+ export { toFormData };
@@ -0,0 +1,8 @@
1
+ // src/core/guards.ts
2
+ function isRecord(value) {
3
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4
+ }
5
+ function isNonEmptyString(value) {
6
+ return typeof value === "string" && value.trim().length > 0;
7
+ }
8
+ export { isNonEmptyString, isRecord };
@@ -0,0 +1,16 @@
1
+ // src/core/match.ts
2
+ const SPECIAL_CHARACTERS = /[.+?^${}()|[\]\\]/g;
3
+ function patternToRegExp(pattern) {
4
+ const source = pattern.split("**").map((part) => part.split("*").map((literal) => literal.replace(SPECIAL_CHARACTERS, "\\$&")).join("[^/]*")).join(".*");
5
+ return new RegExp(`^${source}$`);
6
+ }
7
+ function createMatcher(patterns) {
8
+ const expressions = patterns.map(patternToRegExp);
9
+ return (value) => expressions.some((expression) => expression.test(value));
10
+ }
11
+ function createSelector({ include, exclude }) {
12
+ const isIncluded = include ? createMatcher(include) : () => true;
13
+ const isExcluded = exclude ? createMatcher(exclude) : () => false;
14
+ return (value) => isIncluded(value) && !isExcluded(value);
15
+ }
16
+ export { createMatcher, createSelector };
@@ -0,0 +1,51 @@
1
+ // src/core/names.ts
2
+ const TOOL_NAME_PATTERN = /^[A-Za-z0-9_.-]{1,128}$/;
3
+ const NAVIGATE_TOOL_NAME = "navigate";
4
+ const RESERVED_TOOL_NAMES = [
5
+ "snapshot",
6
+ "act",
7
+ "query",
8
+ "pause_hmr",
9
+ "resume_hmr",
10
+ "nextjs_inspect",
11
+ "nextjs_compile_route",
12
+ NAVIGATE_TOOL_NAME
13
+ ];
14
+ function isValidToolName(name) {
15
+ return TOOL_NAME_PATTERN.test(name);
16
+ }
17
+ function isReservedToolName(name) {
18
+ return RESERVED_TOOL_NAMES.includes(name);
19
+ }
20
+ function applyPrefix(name, prefix) {
21
+ return prefix ? `${prefix}${name}` : name;
22
+ }
23
+ function checkToolNames(names) {
24
+ const seen = /* @__PURE__ */ new Set();
25
+ const issues = [];
26
+ for (const name of names) {
27
+ if (!isValidToolName(name)) issues.push({
28
+ code: "AT001",
29
+ name,
30
+ reason: "invalid"
31
+ });
32
+ else if (isReservedToolName(name)) issues.push({
33
+ code: "AT002",
34
+ name,
35
+ reason: "reserved"
36
+ });
37
+ else if (seen.has(name)) issues.push({
38
+ code: "AT002",
39
+ name,
40
+ reason: "duplicate"
41
+ });
42
+ seen.add(name);
43
+ }
44
+ return issues;
45
+ }
46
+ function describeNameIssue(issue) {
47
+ if (issue.reason === "invalid") return `Invalid tool name "${issue.name}". Use 1 to 128 characters from A-Z, a-z, 0-9, "_", "-", and ".".`;
48
+ if (issue.reason === "reserved") return `The tool name "${issue.name}" is reserved.`;
49
+ return `The tool name "${issue.name}" is registered more than once.`;
50
+ }
51
+ export { NAVIGATE_TOOL_NAME, RESERVED_TOOL_NAMES, TOOL_NAME_PATTERN, applyPrefix, checkToolNames, describeNameIssue, isReservedToolName, isValidToolName };
@@ -0,0 +1,18 @@
1
+ import { SchemaIssue } from "./schema.js";
2
+ export type AgentErrorCode = 'invalid_input' | 'unauthorized' | 'failed' | 'declined' | 'blocked' | (string & {});
3
+ export interface AgentError {
4
+ code: AgentErrorCode;
5
+ message: string;
6
+ issues?: SchemaIssue[];
7
+ }
8
+ export type AgentResult<R> = {
9
+ ok: true;
10
+ data: R;
11
+ } | {
12
+ ok: false;
13
+ error: AgentError;
14
+ };
15
+ export declare class AgentToolError extends Error {
16
+ readonly code: string;
17
+ constructor(code: string, message: string);
18
+ }
@@ -0,0 +1,85 @@
1
+ import { isRecord } from "./guards.js";
2
+ // src/core/result.ts
3
+ var AgentToolError = class extends Error {
4
+ code;
5
+ constructor(code, message) {
6
+ super(message);
7
+ this.name = "AgentToolError";
8
+ this.code = code;
9
+ }
10
+ };
11
+ const GENERIC_FAILURE_MESSAGE = "The tool failed.";
12
+ const INVALID_INPUT_MESSAGE = "Invalid input.";
13
+ const INVALID_OUTPUT_MESSAGE = "The tool returned an unexpected output.";
14
+ const DECLINED_MESSAGE = "The user declined this action.";
15
+ const BLOCKED_MESSAGE = "The page blocked this action.";
16
+ function succeed(data) {
17
+ return {
18
+ ok: true,
19
+ data
20
+ };
21
+ }
22
+ function fail(code, message, issues) {
23
+ return {
24
+ ok: false,
25
+ error: issues && issues.length > 0 ? {
26
+ code,
27
+ message,
28
+ issues
29
+ } : {
30
+ code,
31
+ message
32
+ }
33
+ };
34
+ }
35
+ function isAgentResult(value) {
36
+ if (!isRecord(value) || typeof value.ok !== "boolean") return false;
37
+ return value.ok ? "data" in value : isRecord(value.error) && typeof value.error.message === "string";
38
+ }
39
+ function isFrameworkSignal(error) {
40
+ if (typeof error !== "object" || error === null) return false;
41
+ const signal = error;
42
+ return typeof signal.digest === "string" || signal.$$typeof === Symbol.for("react.postpone");
43
+ }
44
+ function normalizeActionResult(raw, adapter) {
45
+ if (isAgentResult(raw)) return toJsonSafe(raw);
46
+ if (isRecord(raw)) {
47
+ if (isPresent(raw.serverError)) return fail("failed", typeof raw.serverError === "string" ? raw.serverError : GENERIC_FAILURE_MESSAGE);
48
+ if (isPresent(raw.validationErrors)) return fail("invalid_input", INVALID_INPUT_MESSAGE, collectIssues(raw.validationErrors, []));
49
+ if (typeof raw.error === "string" && raw.error) return fail("failed", raw.error);
50
+ }
51
+ return succeed(toJsonSafe(adapter === "safe-action" && isRecord(raw) ? raw.data : raw));
52
+ }
53
+ function toJsonSafe(value) {
54
+ if (value === void 0) return void 0;
55
+ try {
56
+ const serialized = JSON.stringify(value, replaceUnserializable);
57
+ return serialized === void 0 ? void 0 : JSON.parse(serialized);
58
+ } catch {
59
+ return String(value);
60
+ }
61
+ }
62
+ function isPresent(value) {
63
+ return value !== void 0 && value !== null;
64
+ }
65
+ function collectIssues(node, path) {
66
+ if (typeof node === "string") return [{
67
+ message: node,
68
+ path: [...path]
69
+ }];
70
+ if (Array.isArray(node)) return node.flatMap((item) => collectIssues(item, path));
71
+ if (!isRecord(node)) return [];
72
+ return Object.entries(node).flatMap(([key, value]) => collectIssues(value, STRUCTURAL_KEYS.has(key) ? path : [...path, key]));
73
+ }
74
+ const STRUCTURAL_KEYS = /* @__PURE__ */ new Set([
75
+ "_errors",
76
+ "formErrors",
77
+ "fieldErrors"
78
+ ]);
79
+ function replaceUnserializable(_key, value) {
80
+ if (typeof value === "bigint") return value.toString();
81
+ if (value instanceof Map) return Object.fromEntries(value);
82
+ if (value instanceof Set) return [...value];
83
+ return value;
84
+ }
85
+ export { AgentToolError, BLOCKED_MESSAGE, DECLINED_MESSAGE, GENERIC_FAILURE_MESSAGE, INVALID_INPUT_MESSAGE, INVALID_OUTPUT_MESSAGE, fail, isAgentResult, isFrameworkSignal, normalizeActionResult, succeed, toJsonSafe };
@@ -0,0 +1,6 @@
1
+ import { StandardSchemaV1 } from "@standard-schema/spec";
2
+ export type AgentSchema<Output = unknown> = StandardSchemaV1<unknown, Output>;
3
+ export interface SchemaIssue {
4
+ message: string;
5
+ path: Array<string | number>;
6
+ }
@@ -0,0 +1,90 @@
1
+ import { isRecord } from "./guards.js";
2
+ // src/core/schema.ts
3
+ const JSON_SCHEMA_TARGET = "draft-2020-12";
4
+ const DEFINITION_REFERENCE = /^#\/\$defs\/(.+)$/;
5
+ var CyclicReferenceError = class extends Error {};
6
+ function convertSchema(schema, direction = "input") {
7
+ const { jsonSchema } = schema["~standard"];
8
+ if (!jsonSchema) return {
9
+ ok: false,
10
+ reason: "The validator does not implement Standard JSON Schema."
11
+ };
12
+ try {
13
+ const converted = sanitizeJsonSchema(jsonSchema[direction]({ target: JSON_SCHEMA_TARGET }));
14
+ if (direction === "input" && converted.type !== "object") return {
15
+ ok: false,
16
+ reason: "A tool input schema must describe an object."
17
+ };
18
+ return {
19
+ ok: true,
20
+ schema: converted
21
+ };
22
+ } catch (error) {
23
+ return {
24
+ ok: false,
25
+ reason: error instanceof Error ? error.message : String(error)
26
+ };
27
+ }
28
+ }
29
+ function sanitizeJsonSchema(schema) {
30
+ const definitions = isRecord(schema.$defs) ? schema.$defs : {};
31
+ try {
32
+ const { $defs: _definitions, ...root } = schema;
33
+ return clean(root, definitions, []);
34
+ } catch (error) {
35
+ if (error instanceof CyclicReferenceError) return clean(schema, void 0, []);
36
+ throw error;
37
+ }
38
+ }
39
+ function clean(node, definitions, expanding) {
40
+ if (Array.isArray(node)) return node.map((item) => clean(item, definitions, expanding));
41
+ if (!isRecord(node)) return node;
42
+ const target = definitions && referencedDefinition(node, definitions);
43
+ if (target) {
44
+ if (expanding.includes(target)) throw new CyclicReferenceError(target);
45
+ const { $ref: _reference, ...siblings } = node;
46
+ const inlined = clean(definitions[target], definitions, [...expanding, target]);
47
+ return {
48
+ ...isRecord(inlined) ? inlined : {},
49
+ ...clean(siblings, definitions, expanding)
50
+ };
51
+ }
52
+ const result = {};
53
+ for (const [key, value] of Object.entries(node)) {
54
+ if (key === "$schema") continue;
55
+ if (key === "description" && typeof value === "string") {
56
+ const description = value.trim();
57
+ if (description) result.description = description;
58
+ continue;
59
+ }
60
+ result[key] = clean(value, definitions, expanding);
61
+ }
62
+ return result;
63
+ }
64
+ function referencedDefinition(node, definitions) {
65
+ if (typeof node.$ref !== "string") return void 0;
66
+ const name = DEFINITION_REFERENCE.exec(node.$ref)?.[1];
67
+ return name !== void 0 && name in definitions ? name : void 0;
68
+ }
69
+ async function validateWithSchema(schema, value) {
70
+ const result = await schema["~standard"].validate(value);
71
+ if (result.issues) return {
72
+ ok: false,
73
+ issues: result.issues.map(toSchemaIssue)
74
+ };
75
+ return {
76
+ ok: true,
77
+ value: result.value
78
+ };
79
+ }
80
+ function toSchemaIssue(issue) {
81
+ const path = (issue.path ?? []).map((segment) => {
82
+ const key = typeof segment === "object" ? segment.key : segment;
83
+ return typeof key === "number" ? key : String(key);
84
+ });
85
+ return {
86
+ message: issue.message,
87
+ path
88
+ };
89
+ }
90
+ export { convertSchema, sanitizeJsonSchema, validateWithSchema };
@@ -0,0 +1,34 @@
1
+ export type ConfirmPolicy = 'always' | 'consequential' | 'never';
2
+ export type ToolAdapter = 'formdata' | 'form' | 'safe-action';
3
+ export type JsonSchema = Record<string, unknown>;
4
+ export interface ToolAnnotations {
5
+ readOnlyHint: boolean;
6
+ consequentialHint: boolean;
7
+ untrustedContentHint: boolean;
8
+ }
9
+ export type ServerFunction = (...args: never[]) => Promise<unknown>;
10
+ export interface SerializableToolDef {
11
+ name: string;
12
+ title?: string;
13
+ description: string;
14
+ inputSchema?: JsonSchema;
15
+ outputSchema?: JsonSchema;
16
+ annotations: ToolAnnotations;
17
+ confirm: ConfirmPolicy;
18
+ adapter?: ToolAdapter;
19
+ action: ServerFunction;
20
+ }
21
+ export interface ToolCall {
22
+ name: string;
23
+ input: unknown;
24
+ annotations: ToolAnnotations;
25
+ source: 'agent';
26
+ }
27
+ export interface RouteEntry {
28
+ pattern: string;
29
+ params: string[];
30
+ catchAll?: string;
31
+ optionalCatchAll?: string;
32
+ title?: string;
33
+ staticParams?: boolean;
34
+ }
@@ -0,0 +1,95 @@
1
+ // src/core/webmcp.ts
2
+ const MAX_NAME_ATTEMPTS = 3;
3
+ const AVAILABILITY_CHECK_DELAYS_MS = [
4
+ 250,
5
+ 1e3,
6
+ 4e3
7
+ ];
8
+ const availabilityListeners = /* @__PURE__ */ new Set();
9
+ let availabilityCheck;
10
+ let pendingPolyfill;
11
+ function getModelContext() {
12
+ if (typeof document === "undefined") return void 0;
13
+ const context = document.modelContext;
14
+ return context && typeof context.registerTool === "function" ? context : void 0;
15
+ }
16
+ function getWebMCPStatus() {
17
+ const context = getModelContext();
18
+ if (!context) return "unavailable";
19
+ return Function.prototype.toString.call(context.registerTool).includes("[native code]") ? "native" : "polyfill";
20
+ }
21
+ function loadPolyfill() {
22
+ pendingPolyfill ??= import("@w3c/webmcp-polyfill").then(({ installWebMCP }) => {
23
+ installWebMCP();
24
+ announceAvailability();
25
+ return getModelContext();
26
+ });
27
+ return pendingPolyfill;
28
+ }
29
+ function announceAvailability() {
30
+ clearTimeout(availabilityCheck);
31
+ availabilityCheck = void 0;
32
+ for (const listener of availabilityListeners) listener();
33
+ availabilityListeners.clear();
34
+ }
35
+ function scheduleAvailabilityCheck(attempt) {
36
+ const delay = AVAILABILITY_CHECK_DELAYS_MS[attempt];
37
+ if (availabilityCheck !== void 0 || delay === void 0) return;
38
+ availabilityCheck = setTimeout(() => {
39
+ availabilityCheck = void 0;
40
+ if (getModelContext()) announceAvailability();
41
+ else scheduleAvailabilityCheck(attempt + 1);
42
+ }, delay);
43
+ }
44
+ function whenModelContextAvailable(signal) {
45
+ const context = getModelContext();
46
+ if (context) return Promise.resolve(context);
47
+ return new Promise((resolve) => {
48
+ const onAbort = () => {
49
+ availabilityListeners.delete(listener);
50
+ if (availabilityListeners.size === 0) {
51
+ clearTimeout(availabilityCheck);
52
+ availabilityCheck = void 0;
53
+ }
54
+ resolve(void 0);
55
+ };
56
+ const listener = () => {
57
+ signal.removeEventListener("abort", onAbort);
58
+ resolve(getModelContext());
59
+ };
60
+ if (signal.aborted) {
61
+ resolve(void 0);
62
+ return;
63
+ }
64
+ availabilityListeners.add(listener);
65
+ signal.addEventListener("abort", onAbort, { once: true });
66
+ scheduleAvailabilityCheck(0);
67
+ });
68
+ }
69
+ function resolveModelContext(polyfill, signal) {
70
+ const context = getModelContext();
71
+ if (context) return Promise.resolve(context);
72
+ return polyfill ? loadPolyfill() : whenModelContextAvailable(signal);
73
+ }
74
+ function registerTools(context, tools, options) {
75
+ const registrations = Promise.allSettled(tools.map((tool) => registerTool(context, tool, options, 1)));
76
+ if (typeof context.waitForToolsUntil === "function") context.waitForToolsUntil(registrations);
77
+ return registrations;
78
+ }
79
+ async function registerTool(context, tool, options, attempt) {
80
+ const name = attempt === 1 ? tool.name : `${tool.name}_${attempt}`;
81
+ const registerOptions = { signal: options.signal };
82
+ if (options.exposedTo) registerOptions.exposedTo = [...options.exposedTo];
83
+ try {
84
+ await context.registerTool({
85
+ ...tool,
86
+ name
87
+ }, registerOptions);
88
+ } catch (error) {
89
+ if (!(error instanceof DOMException && error.name === "InvalidStateError") || options.signal.aborted || attempt >= MAX_NAME_ATTEMPTS) throw error;
90
+ return registerTool(context, tool, options, attempt + 1);
91
+ }
92
+ if (attempt > 1) options.onCollision?.(tool.name, name);
93
+ return name;
94
+ }
95
+ export { AVAILABILITY_CHECK_DELAYS_MS, getModelContext, getWebMCPStatus, loadPolyfill, registerTools, resolveModelContext, whenModelContextAvailable };
@@ -0,0 +1,36 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { join } from "node:path";
4
+ import { analyze, createAnalysisCache } from "../analyzer/index.js";
5
+ import { renderManifest, renderRegistry } from "./render.js";
6
+ // src/generator/index.ts
7
+ const REGISTRY_FILE = "registry.ts";
8
+ const MANIFEST_FILE = "manifest.json";
9
+ async function generate(config, cache = createAnalysisCache()) {
10
+ const startedAt = performance.now();
11
+ const analysis = await analyze(config, cache);
12
+ const files = {
13
+ [REGISTRY_FILE]: renderRegistry(analysis, config),
14
+ [MANIFEST_FILE]: renderManifest(analysis, readNextVersion(config.cwd))
15
+ };
16
+ mkdirSync(config.outDir, { recursive: true });
17
+ return {
18
+ analysis,
19
+ written: Object.entries(files).flatMap(([name, content]) => writeIfChanged(join(config.outDir, name), content) ? [name] : []),
20
+ durationMs: performance.now() - startedAt
21
+ };
22
+ }
23
+ function readNextVersion(cwd) {
24
+ try {
25
+ const manifestPath = createRequire(join(cwd, "package.json")).resolve("next/package.json");
26
+ return JSON.parse(readFileSync(manifestPath, "utf8")).version;
27
+ } catch {
28
+ return "unknown";
29
+ }
30
+ }
31
+ function writeIfChanged(file, content) {
32
+ if (existsSync(file) && readFileSync(file, "utf8") === content) return false;
33
+ writeFileSync(file, content);
34
+ return true;
35
+ }
36
+ export { MANIFEST_FILE, REGISTRY_FILE, createAnalysisCache, generate, readNextVersion };
@@ -0,0 +1,91 @@
1
+ import { posix, relative, sep } from "node:path";
2
+ import { DIAGNOSTIC_RULES } from "../analyzer/diagnostics.js";
3
+ const GENERATED_HEADER = "// @generated by actionmcp. Do not edit.";
4
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
5
+ const IMPORTABLE_EXTENSION = /\.(?:tsx?|jsx?)$/;
6
+ function renderRegistry(analysis, config) {
7
+ const tools = analysis.tools.filter(isRegistrable);
8
+ const modules = [...new Set(tools.map((tool) => tool.source.file))].toSorted();
9
+ const moduleName = (tool) => `m${modules.indexOf(tool.source.file)}`;
10
+ const reference = (tool) => `${moduleName(tool)}${accessor(tool.source.export)}`;
11
+ const agentTools = tools.filter((tool) => tool.kind === "agent");
12
+ const jsdocTools = tools.filter((tool) => tool.kind === "jsdoc");
13
+ const lines = [
14
+ GENERATED_HEADER,
15
+ "import 'server-only'",
16
+ "import { createRegistry } from 'actionmcp/server'"
17
+ ];
18
+ modules.forEach((file, index) => lines.push(`import * as m${index} from ${quote(importPath(config, file))}`));
19
+ if (analysis.registry) lines.push(`import explicit from ${quote(importPath(config, analysis.registry))}`);
20
+ lines.push("", "export default createRegistry({");
21
+ if (agentTools.length > 0) lines.push(" agent: {", ...agentTools.map((tool) => ` ${key(tool.name)}: ${reference(tool)},`), " },");
22
+ if (jsdocTools.length > 0) lines.push(" jsdoc: {", ...jsdocTools.flatMap((tool) => renderJsdocTool(tool, reference(tool))), " },");
23
+ if (analysis.registry) lines.push(" explicit,");
24
+ lines.push(` routes: ${indent(JSON.stringify(analysis.routes, null, 2), 2)},`, "})", "");
25
+ return lines.join("\n");
26
+ }
27
+ function renderManifest(analysis, nextVersion) {
28
+ const manifest = {
29
+ version: 1,
30
+ nextVersion,
31
+ tools: analysis.tools.map(toManifestTool),
32
+ routes: analysis.routes
33
+ };
34
+ return `${JSON.stringify(manifest, null, 2)}\n`;
35
+ }
36
+ function toManifestTool(tool) {
37
+ return {
38
+ name: tool.name,
39
+ kind: tool.kind,
40
+ description: tool.description,
41
+ source: tool.source,
42
+ schemaSource: tool.schemaSource,
43
+ annotations: tool.annotations,
44
+ confirm: tool.confirm,
45
+ ...tool.adapter ? { adapter: tool.adapter } : {},
46
+ validated: tool.validated,
47
+ diagnostics: tool.diagnostics.toSorted()
48
+ };
49
+ }
50
+ function isRegistrable(tool) {
51
+ if (tool.kind !== "agent" && tool.kind !== "jsdoc") return false;
52
+ return !tool.diagnostics.some((code) => DIAGNOSTIC_RULES[code]?.level === "error");
53
+ }
54
+ function renderJsdocTool(tool, reference) {
55
+ const { readOnlyHint, consequentialHint, untrustedContentHint } = tool.annotations;
56
+ const entry = {
57
+ description: tool.description,
58
+ ...tool.inputSchema ? { inputSchema: tool.inputSchema } : {},
59
+ annotations: {
60
+ readOnlyHint,
61
+ consequentialHint,
62
+ untrustedContentHint
63
+ },
64
+ ...tool.adapter ? { adapter: tool.adapter } : {},
65
+ validated: false
66
+ };
67
+ const body = Object.entries(entry).map(([name, value]) => ` ${name}: ${indent(JSON.stringify(value, null, 2), 6)},`);
68
+ return [
69
+ ` ${key(tool.name)}: {`,
70
+ ` action: ${reference},`,
71
+ ...body,
72
+ " },"
73
+ ];
74
+ }
75
+ function importPath(config, file) {
76
+ const path = relative(config.outDir, posix.join(config.cwd.split(sep).join("/"), file)).split(sep).join("/").replace(IMPORTABLE_EXTENSION, "");
77
+ return path.startsWith(".") ? path : `./${path}`;
78
+ }
79
+ function accessor(exportName) {
80
+ return IDENTIFIER.test(exportName) ? `.${exportName}` : `[${quote(exportName)}]`;
81
+ }
82
+ function key(name) {
83
+ return IDENTIFIER.test(name) ? name : quote(name);
84
+ }
85
+ function quote(value) {
86
+ return JSON.stringify(value);
87
+ }
88
+ function indent(text, spaces) {
89
+ return text.split("\n").join(`\n${" ".repeat(spaces)}`);
90
+ }
91
+ export { GENERATED_HEADER, renderManifest, renderRegistry };
@@ -0,0 +1,76 @@
1
+ import { existsSync, watch } from "node:fs";
2
+ import { basename, dirname, join, relative, sep } from "node:path";
3
+ import { findAppDirectory } from "../analyzer/routes.js";
4
+ import { createAnalysisCache } from "../analyzer/index.js";
5
+ import { generate } from "./index.js";
6
+ // src/generator/watch.ts
7
+ const GLOB_CHARACTERS = /[*?{[!]/;
8
+ const IGNORED_SEGMENTS = /* @__PURE__ */ new Set([
9
+ "node_modules",
10
+ ".next",
11
+ ".git"
12
+ ]);
13
+ function watchRoots(config) {
14
+ const candidates = config.scan.map((pattern) => {
15
+ const segments = pattern.split("/");
16
+ const firstDynamic = segments.findIndex((segment) => GLOB_CHARACTERS.test(segment));
17
+ return join(config.cwd, ...segments.slice(0, firstDynamic === -1 ? segments.length - 1 : firstDynamic));
18
+ });
19
+ const appDirectory = findAppDirectory(config.cwd);
20
+ if (appDirectory) candidates.push(appDirectory);
21
+ const existing = [...new Set(candidates)].filter((directory) => existsSync(directory)).toSorted();
22
+ return existing.filter((directory) => !existing.some((other) => other !== directory && isInside(directory, other)));
23
+ }
24
+ function watchProject(config, options) {
25
+ const cache = createAnalysisCache();
26
+ const persistent = options.persistent ?? true;
27
+ const outDir = relative(config.cwd, config.outDir);
28
+ let timer;
29
+ let running = false;
30
+ let queued = false;
31
+ const run = async () => {
32
+ if (running) {
33
+ queued = true;
34
+ return;
35
+ }
36
+ running = true;
37
+ try {
38
+ options.onResult(await generate(config, cache));
39
+ } catch (error) {
40
+ options.onError(error);
41
+ } finally {
42
+ running = false;
43
+ if (queued) {
44
+ queued = false;
45
+ run();
46
+ }
47
+ }
48
+ };
49
+ const schedule = (root, file) => {
50
+ const changed = relative(config.cwd, join(root, file ?? ""));
51
+ const segments = changed.split(sep);
52
+ if (changed === outDir || changed.startsWith(`${outDir}${sep}`) || segments.some((segment) => IGNORED_SEGMENTS.has(segment))) return;
53
+ clearTimeout(timer);
54
+ timer = setTimeout(() => void run(), options.debounceMs ?? 50);
55
+ };
56
+ const watchers = watchRoots(config).map((root) => watch(root, {
57
+ recursive: true,
58
+ persistent
59
+ }, (_event, file) => schedule(root, file)));
60
+ const { registry } = config;
61
+ if (registry) {
62
+ const directory = dirname(registry);
63
+ watchers.push(watch(directory, { persistent }, (_event, file) => {
64
+ if (file === basename(registry)) schedule(directory, file);
65
+ }));
66
+ }
67
+ return { close: () => {
68
+ clearTimeout(timer);
69
+ for (const watcher of watchers) watcher.close();
70
+ } };
71
+ }
72
+ function isInside(directory, parent) {
73
+ const path = relative(parent, directory);
74
+ return path !== "" && !path.startsWith("..");
75
+ }
76
+ export { watchProject, watchRoots };
@@ -0,0 +1,8 @@
1
+ import { AgentTools, AgentToolsProps } from "./react/AgentTools.js";
2
+ import { AgentToolsProvider, AgentToolsProviderProps } from "./react/Provider.js";
3
+ import { AgentToolsDevtools } from "./react/Devtools.js";
4
+ import { ConfirmDialog } from "./react/Confirm.js";
5
+ import { AgentToolsHooks, ConfirmLabels, ConfirmProps } from "./react/context.js";
6
+ import { NavigateOptions } from "./next/routes.js";
7
+ import { RouteEntry, SerializableToolDef, ToolAnnotations, ToolCall } from "./core/types.js";
8
+ export { AgentTools, AgentToolsDevtools, type AgentToolsHooks, type AgentToolsProps, AgentToolsProvider, type AgentToolsProviderProps, ConfirmDialog, type ConfirmLabels, type ConfirmProps, type NavigateOptions, type RouteEntry, type SerializableToolDef, type ToolAnnotations, type ToolCall };
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ import { AgentTools } from "./react/AgentTools.js";
2
+ import { AgentToolsProvider } from "./react/Provider.js";
3
+ import { AgentToolsDevtools } from "./react/Devtools.js";
4
+ import { ConfirmDialog } from "./react/Confirm.js";
5
+ export { AgentTools, AgentToolsDevtools, AgentToolsProvider, ConfirmDialog };