actionmcp 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +74 -2
- package/dist/analyzer/config.d.ts +15 -0
- package/dist/analyzer/config.js +43 -0
- package/dist/analyzer/diagnostics.js +126 -0
- package/dist/analyzer/explicit.js +128 -0
- package/dist/analyzer/index.js +178 -0
- package/dist/analyzer/jsdoc.js +32 -0
- package/dist/analyzer/options.js +65 -0
- package/dist/analyzer/routes.js +81 -0
- package/dist/analyzer/scan.js +280 -0
- package/dist/analyzer/source.js +100 -0
- package/dist/analyzer/types.js +133 -0
- package/dist/cli/bin.d.ts +1 -0
- package/dist/cli/bin.js +5 -0
- package/dist/cli/commands.js +107 -0
- package/dist/cli/environment.js +53 -0
- package/dist/cli/index.js +97 -0
- package/dist/cli/output.js +27 -0
- package/dist/cli/project.js +33 -0
- package/dist/client.d.ts +6 -0
- package/dist/client.js +4 -0
- package/dist/config.d.ts +9 -0
- package/dist/config.js +84 -0
- package/dist/core/compare.js +6 -0
- package/dist/core/events.js +12 -0
- package/dist/core/execute.js +70 -0
- package/dist/core/formdata.js +15 -0
- package/dist/core/guards.js +8 -0
- package/dist/core/match.js +16 -0
- package/dist/core/names.js +51 -0
- package/dist/core/result.d.ts +18 -0
- package/dist/core/result.js +85 -0
- package/dist/core/schema.d.ts +6 -0
- package/dist/core/schema.js +90 -0
- package/dist/core/types.d.ts +34 -0
- package/dist/core/webmcp.js +62 -0
- package/dist/generator/index.js +36 -0
- package/dist/generator/render.js +91 -0
- package/dist/generator/watch.js +76 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +5 -0
- package/dist/next/NavigateTool.js +40 -0
- package/dist/next/config-store.js +12 -0
- package/dist/next/redirect.js +15 -0
- package/dist/next/routes.d.ts +3 -0
- package/dist/next/routes.js +57 -0
- package/dist/react/AgentTools.d.ts +14 -0
- package/dist/react/AgentTools.js +35 -0
- package/dist/react/Confirm.d.ts +3 -0
- package/dist/react/Confirm.js +99 -0
- package/dist/react/Devtools.d.ts +2 -0
- package/dist/react/Devtools.js +13 -0
- package/dist/react/DevtoolsPanel.js +223 -0
- package/dist/react/Provider.d.ts +6 -0
- package/dist/react/Provider.js +21 -0
- package/dist/react/Registrar.js +12 -0
- package/dist/react/context.d.ts +14 -0
- package/dist/react/context.js +5 -0
- package/dist/react/useAgentTools.js +103 -0
- package/dist/registry.d.ts +4 -0
- package/dist/registry.js +4 -0
- package/dist/server/agent.d.ts +43 -0
- package/dist/server/agent.js +34 -0
- package/dist/server/index.d.ts +6 -0
- package/dist/server/index.js +4 -0
- package/dist/server/registry.d.ts +53 -0
- package/dist/server/registry.js +93 -0
- package/dist/server/resolve.js +68 -0
- package/package.json +96 -4
|
@@ -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,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,62 @@
|
|
|
1
|
+
// src/core/webmcp.ts
|
|
2
|
+
const MAX_NAME_ATTEMPTS = 3;
|
|
3
|
+
const availabilityListeners = /* @__PURE__ */ new Set();
|
|
4
|
+
let pendingPolyfill;
|
|
5
|
+
function getModelContext() {
|
|
6
|
+
if (typeof document === "undefined") return void 0;
|
|
7
|
+
const context = document.modelContext;
|
|
8
|
+
return context && typeof context.registerTool === "function" ? context : void 0;
|
|
9
|
+
}
|
|
10
|
+
function getWebMCPStatus() {
|
|
11
|
+
const context = getModelContext();
|
|
12
|
+
if (!context) return "unavailable";
|
|
13
|
+
return Function.prototype.toString.call(context.registerTool).includes("[native code]") ? "native" : "polyfill";
|
|
14
|
+
}
|
|
15
|
+
function loadPolyfill() {
|
|
16
|
+
pendingPolyfill ??= import("@w3c/webmcp-polyfill").then(({ installWebMCP }) => {
|
|
17
|
+
installWebMCP();
|
|
18
|
+
for (const listener of availabilityListeners) listener();
|
|
19
|
+
availabilityListeners.clear();
|
|
20
|
+
return getModelContext();
|
|
21
|
+
});
|
|
22
|
+
return pendingPolyfill;
|
|
23
|
+
}
|
|
24
|
+
function whenModelContextAvailable(signal) {
|
|
25
|
+
const context = getModelContext();
|
|
26
|
+
if (context) return Promise.resolve(context);
|
|
27
|
+
return new Promise((resolve) => {
|
|
28
|
+
const listener = () => resolve(getModelContext());
|
|
29
|
+
availabilityListeners.add(listener);
|
|
30
|
+
signal.addEventListener("abort", () => {
|
|
31
|
+
availabilityListeners.delete(listener);
|
|
32
|
+
resolve(void 0);
|
|
33
|
+
}, { once: true });
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
function resolveModelContext(polyfill, signal) {
|
|
37
|
+
const context = getModelContext();
|
|
38
|
+
if (context) return Promise.resolve(context);
|
|
39
|
+
return polyfill ? loadPolyfill() : whenModelContextAvailable(signal);
|
|
40
|
+
}
|
|
41
|
+
function registerTools(context, tools, options) {
|
|
42
|
+
const registrations = Promise.allSettled(tools.map((tool) => registerTool(context, tool, options, 1)));
|
|
43
|
+
if (typeof context.waitForToolsUntil === "function") context.waitForToolsUntil(registrations);
|
|
44
|
+
return registrations;
|
|
45
|
+
}
|
|
46
|
+
async function registerTool(context, tool, options, attempt) {
|
|
47
|
+
const name = attempt === 1 ? tool.name : `${tool.name}_${attempt}`;
|
|
48
|
+
const registerOptions = { signal: options.signal };
|
|
49
|
+
if (options.exposedTo) registerOptions.exposedTo = [...options.exposedTo];
|
|
50
|
+
try {
|
|
51
|
+
await context.registerTool({
|
|
52
|
+
...tool,
|
|
53
|
+
name
|
|
54
|
+
}, registerOptions);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (!(error instanceof DOMException && error.name === "InvalidStateError") || options.signal.aborted || attempt >= MAX_NAME_ATTEMPTS) throw error;
|
|
57
|
+
return registerTool(context, tool, options, attempt + 1);
|
|
58
|
+
}
|
|
59
|
+
if (attempt > 1) options.onCollision?.(tool.name, name);
|
|
60
|
+
return name;
|
|
61
|
+
}
|
|
62
|
+
export { 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 };
|
package/dist/index.d.ts
ADDED
|
@@ -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, 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 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 };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useRouter } from "next/navigation";
|
|
3
|
+
import { useMemo } from "react";
|
|
4
|
+
import { NAVIGATE_TOOL_NAME } from "../core/names.js";
|
|
5
|
+
import { fail, succeed } from "../core/result.js";
|
|
6
|
+
import { useAgentTools } from "../react/useAgentTools.js";
|
|
7
|
+
import { NAVIGATE_DESCRIPTION, buildHref, navigateInputSchema } from "./routes.js";
|
|
8
|
+
// src/next/NavigateTool.tsx
|
|
9
|
+
function NavigateTool({ routes, name = NAVIGATE_TOOL_NAME, polyfill, exposedTo }) {
|
|
10
|
+
const router = useRouter();
|
|
11
|
+
const tools = useMemo(() => [{
|
|
12
|
+
name,
|
|
13
|
+
description: NAVIGATE_DESCRIPTION,
|
|
14
|
+
inputSchema: navigateInputSchema(routes),
|
|
15
|
+
annotations: {
|
|
16
|
+
readOnlyHint: false,
|
|
17
|
+
consequentialHint: false,
|
|
18
|
+
untrustedContentHint: false
|
|
19
|
+
},
|
|
20
|
+
confirm: "never",
|
|
21
|
+
action: async (input) => {
|
|
22
|
+
try {
|
|
23
|
+
const url = buildHref(routes, input);
|
|
24
|
+
router.push(url);
|
|
25
|
+
return succeed({ url });
|
|
26
|
+
} catch (error) {
|
|
27
|
+
return fail("invalid_input", error instanceof Error ? error.message : String(error));
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}], [
|
|
31
|
+
routes,
|
|
32
|
+
name,
|
|
33
|
+
router
|
|
34
|
+
]);
|
|
35
|
+
return useAgentTools(tools, {
|
|
36
|
+
polyfill,
|
|
37
|
+
exposedTo
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
export { NavigateTool };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// src/next/config-store.ts
|
|
2
|
+
const RECORDED_CONFIG = Symbol.for("actionmcp.config");
|
|
3
|
+
function recordConfig(config) {
|
|
4
|
+
globalThis[RECORDED_CONFIG] = config;
|
|
5
|
+
}
|
|
6
|
+
function readRecordedConfig() {
|
|
7
|
+
return globalThis[RECORDED_CONFIG];
|
|
8
|
+
}
|
|
9
|
+
function clearRecordedConfig() {
|
|
10
|
+
delete globalThis[RECORDED_CONFIG];
|
|
11
|
+
}
|
|
12
|
+
export { clearRecordedConfig, readRecordedConfig, recordConfig };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// src/next/redirect.ts
|
|
2
|
+
const REDIRECT_DIGEST = /^NEXT_REDIRECT;[^;]*;(.*);\d+;$/;
|
|
3
|
+
function readRedirect(error) {
|
|
4
|
+
if (typeof error !== "object" || error === null) return void 0;
|
|
5
|
+
const { digest } = error;
|
|
6
|
+
return typeof digest === "string" ? REDIRECT_DIGEST.exec(digest)?.[1] : void 0;
|
|
7
|
+
}
|
|
8
|
+
function recoverRedirect(error) {
|
|
9
|
+
const navigatedTo = readRedirect(error);
|
|
10
|
+
return navigatedTo === void 0 ? void 0 : {
|
|
11
|
+
ok: true,
|
|
12
|
+
data: { navigatedTo }
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
export { readRedirect, recoverRedirect };
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { createMatcher } from "../core/match.js";
|
|
2
|
+
// src/next/routes.ts
|
|
3
|
+
const NAVIGATE_DESCRIPTION = "Navigate this app to one of its pages. Available tools may change after navigating.";
|
|
4
|
+
function selectRoutes(routes, options) {
|
|
5
|
+
if (options === true || !options.routes) return routes.filter((route) => route.params.length === 0 || route.staticParams === true);
|
|
6
|
+
const isAllowed = createMatcher(options.routes);
|
|
7
|
+
return routes.filter((route) => isAllowed(route.pattern));
|
|
8
|
+
}
|
|
9
|
+
function navigateInputSchema(routes) {
|
|
10
|
+
return {
|
|
11
|
+
type: "object",
|
|
12
|
+
properties: {
|
|
13
|
+
route: {
|
|
14
|
+
type: "string",
|
|
15
|
+
enum: routes.map((route) => route.pattern)
|
|
16
|
+
},
|
|
17
|
+
params: {
|
|
18
|
+
type: "object",
|
|
19
|
+
additionalProperties: { type: "string" }
|
|
20
|
+
},
|
|
21
|
+
query: {
|
|
22
|
+
type: "object",
|
|
23
|
+
additionalProperties: { type: "string" }
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
required: ["route"]
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
function buildHref(routes, input) {
|
|
30
|
+
const route = routes.find((candidate) => candidate.pattern === input.route);
|
|
31
|
+
if (!route) throw new RangeError(`Unknown route "${String(input.route)}".`);
|
|
32
|
+
const params = input.params ?? {};
|
|
33
|
+
const path = route.pattern.split("/").flatMap((segment) => resolveSegment(segment, params)).join("/") || "/";
|
|
34
|
+
const query = new URLSearchParams(input.query ?? {}).toString();
|
|
35
|
+
return query ? `${path}?${query}` : path;
|
|
36
|
+
}
|
|
37
|
+
function resolveSegment(segment, params) {
|
|
38
|
+
const optionalCatchAll = /^\[\[\.\.\.(.+)\]\]$/.exec(segment)?.[1];
|
|
39
|
+
if (optionalCatchAll !== void 0) return splitPath(params[optionalCatchAll] ?? "");
|
|
40
|
+
const catchAll = /^\[\.\.\.(.+)\]$/.exec(segment)?.[1];
|
|
41
|
+
if (catchAll !== void 0) {
|
|
42
|
+
const parts = splitPath(requireParam(params, catchAll));
|
|
43
|
+
if (parts.length === 0) throw new RangeError(`Missing route parameter "${catchAll}".`);
|
|
44
|
+
return parts;
|
|
45
|
+
}
|
|
46
|
+
const dynamic = /^\[(.+)\]$/.exec(segment)?.[1];
|
|
47
|
+
return [dynamic === void 0 ? segment : encodeURIComponent(requireParam(params, dynamic))];
|
|
48
|
+
}
|
|
49
|
+
function requireParam(params, name) {
|
|
50
|
+
const value = params[name];
|
|
51
|
+
if (typeof value !== "string" || value.length === 0) throw new RangeError(`Missing route parameter "${name}".`);
|
|
52
|
+
return value;
|
|
53
|
+
}
|
|
54
|
+
function splitPath(value) {
|
|
55
|
+
return value.split("/").filter(Boolean).map(encodeURIComponent);
|
|
56
|
+
}
|
|
57
|
+
export { NAVIGATE_DESCRIPTION, buildHref, navigateInputSchema, selectRoutes };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { ReactNode } from "react";
|
|
2
|
+
import { NavigateOptions } from "../next/routes.js";
|
|
3
|
+
import { AgentToolRegistry } from "../server/registry.js";
|
|
4
|
+
export interface AgentToolsProps {
|
|
5
|
+
registry?: AgentToolRegistry;
|
|
6
|
+
include?: string[];
|
|
7
|
+
exclude?: string[];
|
|
8
|
+
prefix?: string;
|
|
9
|
+
navigate?: boolean | NavigateOptions;
|
|
10
|
+
exposedTo?: string[];
|
|
11
|
+
polyfill?: boolean;
|
|
12
|
+
originTrialToken?: string;
|
|
13
|
+
}
|
|
14
|
+
export declare function AgentTools({ registry, include, exclude, prefix, navigate, exposedTo, polyfill, originTrialToken }: AgentToolsProps): ReactNode;
|