actionmcp 0.1.0 → 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.
package/README.md CHANGED
@@ -12,7 +12,7 @@ The documentation is in the repository: https://github.com/galfrevn/actionmcp#re
12
12
  npm install actionmcp
13
13
  ```
14
14
 
15
- actionmcp requires Next.js 16.x and React 19.2 or later.
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
16
 
17
17
  ## Usage
18
18
 
@@ -76,6 +76,11 @@ const DIAGNOSTIC_RULES = {
76
76
  summary: "Description shorter than 20 characters",
77
77
  fix: "Describe what the tool does, its side effects, and what it returns."
78
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
+ },
79
84
  AT201: {
80
85
  level: "error",
81
86
  summary: "Unsupported Next.js version",
@@ -100,6 +105,11 @@ const DIAGNOSTIC_RULES = {
100
105
  level: "warn",
101
106
  summary: "Explicit tool without an input schema",
102
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."
103
113
  }
104
114
  };
105
115
  function createDiagnostic(code, location, detail, tool) {
@@ -14,24 +14,33 @@ import { inferParameterSchemas } from "./types.js";
14
14
  // src/analyzer/index.ts
15
15
  const SOURCE_FILE = /\.(?:tsx?|jsx?|mts|mjs)$/;
16
16
  const TYPES_CACHE_FILE = "cache/types.json";
17
+ const PACKAGE_MANIFEST = {
18
+ file: "package.json",
19
+ line: 1,
20
+ column: 1
21
+ };
17
22
  function createAnalysisCache() {
18
- return { modules: /* @__PURE__ */ new Map() };
23
+ return {
24
+ modules: /* @__PURE__ */ new Map(),
25
+ pages: /* @__PURE__ */ new Map()
26
+ };
19
27
  }
20
28
  async function analyze(config, cache = createAnalysisCache()) {
21
29
  const files = await listSourceFiles(config);
22
30
  const registryFile = config.registry ? toRelative(config.cwd, config.registry) : void 0;
23
31
  const scans = files.filter((file) => file !== registryFile).flatMap((file) => scanFile(config, cache, file) ?? []);
24
- for (const file of cache.modules.keys()) if (!files.includes(file)) cache.modules.delete(file);
32
+ const listed = new Set(files);
33
+ for (const file of cache.modules.keys()) if (!listed.has(file)) cache.modules.delete(file);
25
34
  const tools = scans.flatMap((scan) => scan.tools);
26
35
  const diagnostics = scans.flatMap((scan) => scan.diagnostics);
27
- await resolveTypes(config, scans, diagnostics);
36
+ resolveTypes(config, scans, diagnostics);
28
37
  if (config.registry && registryFile) {
29
38
  const registry = scanRegistryModule(parseModule(registryFile, readFileSync(config.registry, "utf8")));
30
39
  for (const reference of registry.references) adoptDiscoveredTool(tools, reference);
31
40
  tools.push(...registry.tools);
32
41
  diagnostics.push(...registry.diagnostics);
33
42
  }
34
- const routes = scanRoutes(config.cwd);
43
+ const routes = scanRoutes(config.cwd, cache.pages);
35
44
  if (scans.some((scan) => scan.usesNavigate)) tools.push(navigateTool());
36
45
  diagnostics.push(...checkNames(tools), ...checkToolCount(tools));
37
46
  return {
@@ -69,15 +78,16 @@ function scanFile(config, cache, file) {
69
78
  }
70
79
  return cached.scan ? structuredClone(cached.scan) : void 0;
71
80
  }
72
- async function resolveTypes(config, scans, diagnostics) {
81
+ function resolveTypes(config, scans, diagnostics) {
73
82
  const requests = scans.flatMap((scan) => scan.typeRequests);
74
- const inferences = await inferParameterSchemas(requests.map((request) => ({
83
+ const inferences = inferParameterSchemas(requests.map((request) => ({
75
84
  file: join(config.cwd, request.file),
76
85
  parameterOffset: request.parameterOffset
77
86
  })), {
78
87
  cwd: config.cwd,
79
88
  cacheFile: join(config.outDir, TYPES_CACHE_FILE)
80
89
  });
90
+ let missingToolchain = false;
81
91
  requests.forEach(({ tool, file }, index) => {
82
92
  const inference = inferences[index];
83
93
  if (inference?.ok) {
@@ -85,13 +95,16 @@ async function resolveTypes(config, scans, diagnostics) {
85
95
  return;
86
96
  }
87
97
  tool.schemaSource = "none";
88
- if (!tool.diagnostics.includes("AT101")) tool.diagnostics.push("AT101");
89
- diagnostics.push(createDiagnostic("AT101", {
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, {
90
102
  file,
91
103
  line: tool.source.line,
92
104
  column: 1
93
105
  }, inference?.reason, tool.name));
94
106
  });
107
+ if (missingToolchain) diagnostics.push(createDiagnostic("AT206", PACKAGE_MANIFEST));
95
108
  }
96
109
  function adoptDiscoveredTool(tools, { tool, exportName }) {
97
110
  const matches = tools.filter((candidate) => candidate.kind === "agent" && candidate.source.export === exportName);
@@ -1,5 +1,5 @@
1
1
  import { compareText } from "../core/compare.js";
2
- import { existsSync, readFileSync, readdirSync } from "node:fs";
2
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { parseModule, readObjectLiteral, staticString } from "./source.js";
5
5
  // src/analyzer/routes.ts
@@ -13,29 +13,53 @@ const APP_DIRECTORIES = ["app", "src/app"];
13
13
  function findAppDirectory(cwd) {
14
14
  return APP_DIRECTORIES.map((directory) => join(cwd, directory)).find((directory) => existsSync(directory));
15
15
  }
16
- function scanRoutes(cwd) {
16
+ function scanRoutes(cwd, cache = /* @__PURE__ */ new Map()) {
17
17
  const appDirectory = findAppDirectory(cwd);
18
- if (!appDirectory) return [];
18
+ if (!appDirectory) {
19
+ cache.clear();
20
+ return [];
21
+ }
19
22
  const routes = /* @__PURE__ */ new Map();
20
- visit(appDirectory, [], routes);
23
+ const pages = /* @__PURE__ */ new Set();
24
+ visit(appDirectory, [], {
25
+ routes,
26
+ pages,
27
+ cache
28
+ });
29
+ for (const file of cache.keys()) if (!pages.has(file)) cache.delete(file);
21
30
  return [...routes.values()].toSorted((left, right) => compareText(left.pattern, right.pattern));
22
31
  }
23
- function visit(directory, segments, routes) {
32
+ function visit(directory, segments, scan) {
24
33
  const entries = readdirSync(directory, { withFileTypes: true });
25
34
  const page = entries.find((entry) => entry.isFile() && PAGE_FILE.test(entry.name));
26
35
  if (page) {
27
- const route = toRoute(segments, join(directory, page.name));
28
- if (!routes.has(route.pattern)) routes.set(route.pattern, route);
36
+ const pageFile = join(directory, page.name);
37
+ scan.pages.add(pageFile);
38
+ const route = toRoute(segments, cachedPageMetadata(pageFile, scan.cache));
39
+ if (!scan.routes.has(route.pattern)) scan.routes.set(route.pattern, route);
29
40
  }
30
41
  for (const entry of entries) {
31
42
  if (!entry.isDirectory() || isExcluded(entry.name, segments.length === 0)) continue;
32
- visit(join(directory, entry.name), ROUTE_GROUP.test(entry.name) ? segments : [...segments, entry.name], routes);
43
+ visit(join(directory, entry.name), ROUTE_GROUP.test(entry.name) ? segments : [...segments, entry.name], scan);
44
+ }
45
+ }
46
+ function cachedPageMetadata(pageFile, cache) {
47
+ const { mtimeMs, size } = statSync(pageFile);
48
+ const stamp = `${mtimeMs}:${size}`;
49
+ let cached = cache.get(pageFile);
50
+ if (cached?.stamp !== stamp) {
51
+ cached = {
52
+ stamp,
53
+ metadata: readPageMetadata(pageFile)
54
+ };
55
+ cache.set(pageFile, cached);
33
56
  }
57
+ return cached.metadata;
34
58
  }
35
59
  function isExcluded(name, isRoot) {
36
60
  return name.startsWith("_") || name.startsWith("@") || INTERCEPTING_ROUTE.test(name) || name === "node_modules" || isRoot && name === "api";
37
61
  }
38
- function toRoute(segments, pageFile) {
62
+ function toRoute(segments, metadata) {
39
63
  const route = {
40
64
  pattern: `/${segments.join("/")}`,
41
65
  params: []
@@ -54,7 +78,7 @@ function toRoute(segments, pageFile) {
54
78
  }
55
79
  return {
56
80
  ...route,
57
- ...readPageMetadata(pageFile)
81
+ ...metadata
58
82
  };
59
83
  }
60
84
  function readPageMetadata(pageFile) {
@@ -89,8 +89,20 @@ function isAgentCall(context, node) {
89
89
  return callee.type === "MemberExpression" && callee.object.type === "Identifier" && context.namespaces.has(callee.object.name) && callee.property.type === "Identifier" && callee.property.name === "agent";
90
90
  }
91
91
  function scanAgentCalls(context) {
92
- for (const [localName, node] of context.declarations) if (isAgentCall(context, node)) addAgentTool(context, node, context.exports.get(localName));
93
- for (const statement of context.module.program.body) if (statement.type === "ExportDefaultDeclaration" && isAgentCall(context, statement.declaration)) addAgentTool(context, statement.declaration, "default");
92
+ const registered = /* @__PURE__ */ new Set();
93
+ for (const [localName, node] of context.declarations) {
94
+ if (!isAgentCall(context, node)) continue;
95
+ registered.add(node);
96
+ addAgentTool(context, node, context.exports.get(localName));
97
+ }
98
+ for (const statement of context.module.program.body) if (statement.type === "ExportDefaultDeclaration" && isAgentCall(context, statement.declaration)) {
99
+ registered.add(statement.declaration);
100
+ addAgentTool(context, statement.declaration, "default");
101
+ }
102
+ walk(context.module.program, (node) => {
103
+ if (!isAgentCall(context, node) || registered.has(node)) return;
104
+ context.scan.diagnostics.push(createDiagnostic("AT109", context.module.locate(node.start)));
105
+ });
94
106
  }
95
107
  function addAgentTool(context, call, exportName) {
96
108
  const { module } = context;
@@ -0,0 +1,27 @@
1
+ import { createRequire } from "node:module";
2
+ import { join } from "node:path";
3
+ // src/analyzer/toolchain.ts
4
+ const SCHEMA_GENERATOR_PACKAGE = "ts-json-schema-generator";
5
+ function toolchainOrigins(cwd) {
6
+ return [join(cwd, "package.json"), import.meta.url];
7
+ }
8
+ function loadTypeToolchain(origins, generatorPackage = SCHEMA_GENERATOR_PACKAGE) {
9
+ for (const origin of origins) {
10
+ const entry = resolveFrom(origin, generatorPackage);
11
+ if (entry === void 0) continue;
12
+ const requireFromGenerator = createRequire(entry);
13
+ return {
14
+ generator: requireFromGenerator(entry),
15
+ typescript: requireFromGenerator("typescript")
16
+ };
17
+ }
18
+ }
19
+ function resolveFrom(origin, specifier) {
20
+ try {
21
+ return createRequire(origin).resolve(specifier);
22
+ } catch (error) {
23
+ if (error.code === "MODULE_NOT_FOUND") return void 0;
24
+ throw error;
25
+ }
26
+ }
27
+ export { SCHEMA_GENERATOR_PACKAGE, loadTypeToolchain, toolchainOrigins };
@@ -4,31 +4,40 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
4
  import { dirname, join } from "node:path";
5
5
  import { isRecord } from "../core/guards.js";
6
6
  import { sanitizeJsonSchema } from "../core/schema.js";
7
+ import { SCHEMA_GENERATOR_PACKAGE, loadTypeToolchain, toolchainOrigins } from "./toolchain.js";
7
8
  // src/analyzer/types.ts
8
9
  const CACHE_VERSION = 1;
9
- async function inferParameterSchemas(targets, options) {
10
+ const UNREADABLE_TYPE = {
11
+ ok: false,
12
+ reason: "The type could not be read."
13
+ };
14
+ const MISSING_TOOLCHAIN = {
15
+ ok: false,
16
+ reason: `${SCHEMA_GENERATOR_PACKAGE} is not installed`,
17
+ missingToolchain: true
18
+ };
19
+ function inferParameterSchemas(targets, options) {
10
20
  if (targets.length === 0) return [];
11
21
  const cache = readCache(options.cacheFile);
12
22
  const tsconfig = findTsconfig(options.cwd);
13
23
  const tsconfigText = tsconfig ? readFileSync(tsconfig, "utf8") : "";
14
24
  const hashes = targets.map((target) => hashTarget(target, tsconfigText));
15
- const missing = targets.filter((target, index) => cache.get(cacheKey(target))?.hash !== hashes[index]);
16
- if (missing.length > 0) {
17
- const inferred = await inferWithTypeScript(missing, options.cwd, tsconfig);
18
- missing.forEach((target, index) => {
19
- const inference = inferred[index];
20
- const hash = hashes[targets.indexOf(target)];
21
- if (inference && hash !== void 0) cache.set(cacheKey(target), {
22
- hash,
23
- inference
24
- });
25
+ const isCached = (target, index) => cache.get(cacheKey(target))?.hash === hashes[index];
26
+ const missing = targets.filter((target, index) => !isCached(target, index));
27
+ if (missing.length === 0) return targets.map((target) => cache.get(cacheKey(target))?.inference ?? UNREADABLE_TYPE);
28
+ const toolchain = loadTypeToolchain(toolchainOrigins(options.cwd));
29
+ if (!toolchain) return targets.map((target, index) => (isCached(target, index) ? cache.get(cacheKey(target))?.inference : void 0) ?? MISSING_TOOLCHAIN);
30
+ const inferred = inferWithTypeScript(toolchain, missing, options.cwd, tsconfig);
31
+ missing.forEach((target, index) => {
32
+ const inference = inferred[index];
33
+ const hash = hashes[targets.indexOf(target)];
34
+ if (inference && hash !== void 0) cache.set(cacheKey(target), {
35
+ hash,
36
+ inference
25
37
  });
26
- writeCache(options.cacheFile, cache, targets);
27
- }
28
- return targets.map((target) => cache.get(cacheKey(target))?.inference ?? {
29
- ok: false,
30
- reason: "The type could not be read."
31
38
  });
39
+ writeCache(options.cacheFile, cache, targets);
40
+ return targets.map((target) => cache.get(cacheKey(target))?.inference ?? UNREADABLE_TYPE);
32
41
  }
33
42
  function normalizeTypeSchema(schema) {
34
43
  const { $schema: _dialect, definitions, ...rest } = schema;
@@ -51,9 +60,8 @@ function renameDefinitionReferences(node) {
51
60
  if (!isRecord(node)) return node;
52
61
  return Object.fromEntries(Object.entries(node).map(([key, value]) => [key, key === "$ref" && typeof value === "string" ? value.replace(/^#\/definitions\//, "#/$defs/") : renameDefinitionReferences(value)]));
53
62
  }
54
- async function inferWithTypeScript(targets, cwd, tsconfig) {
55
- const { default: typescript } = await import("typescript");
56
- const { SchemaGenerator, createFormatter, createParser, DEFAULT_CONFIG } = await import("ts-json-schema-generator");
63
+ function inferWithTypeScript({ typescript, generator: generatorModule }, targets, cwd, tsconfig) {
64
+ const { SchemaGenerator, createFormatter, createParser, DEFAULT_CONFIG } = generatorModule;
57
65
  const compilerOptions = {
58
66
  ...readCompilerOptions(typescript, cwd, tsconfig),
59
67
  noEmit: true,
package/dist/client.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { AgentToolsProvider, AgentToolsProviderProps } from "./react/Provider.js";
2
2
  import { AgentToolsDevtools } from "./react/Devtools.js";
3
3
  import { ConfirmDialog } from "./react/Confirm.js";
4
- import { AgentToolsHooks, ConfirmProps } from "./react/context.js";
4
+ import { AgentToolsHooks, ConfirmLabels, ConfirmProps } from "./react/context.js";
5
5
  import { ToolAnnotations, ToolCall } from "./core/types.js";
6
- export { AgentToolsDevtools, type AgentToolsHooks, AgentToolsProvider, type AgentToolsProviderProps, ConfirmDialog, type ConfirmProps, type ToolAnnotations, type ToolCall };
6
+ export { AgentToolsDevtools, type AgentToolsHooks, AgentToolsProvider, type AgentToolsProviderProps, ConfirmDialog, type ConfirmLabels, type ConfirmProps, type ToolAnnotations, type ToolCall };
@@ -1,6 +1,12 @@
1
1
  // src/core/webmcp.ts
2
2
  const MAX_NAME_ATTEMPTS = 3;
3
+ const AVAILABILITY_CHECK_DELAYS_MS = [
4
+ 250,
5
+ 1e3,
6
+ 4e3
7
+ ];
3
8
  const availabilityListeners = /* @__PURE__ */ new Set();
9
+ let availabilityCheck;
4
10
  let pendingPolyfill;
5
11
  function getModelContext() {
6
12
  if (typeof document === "undefined") return void 0;
@@ -15,22 +21,49 @@ function getWebMCPStatus() {
15
21
  function loadPolyfill() {
16
22
  pendingPolyfill ??= import("@w3c/webmcp-polyfill").then(({ installWebMCP }) => {
17
23
  installWebMCP();
18
- for (const listener of availabilityListeners) listener();
19
- availabilityListeners.clear();
24
+ announceAvailability();
20
25
  return getModelContext();
21
26
  });
22
27
  return pendingPolyfill;
23
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
+ }
24
44
  function whenModelContextAvailable(signal) {
25
45
  const context = getModelContext();
26
46
  if (context) return Promise.resolve(context);
27
47
  return new Promise((resolve) => {
28
- const listener = () => resolve(getModelContext());
29
- availabilityListeners.add(listener);
30
- signal.addEventListener("abort", () => {
48
+ const onAbort = () => {
31
49
  availabilityListeners.delete(listener);
50
+ if (availabilityListeners.size === 0) {
51
+ clearTimeout(availabilityCheck);
52
+ availabilityCheck = void 0;
53
+ }
32
54
  resolve(void 0);
33
- }, { once: true });
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);
34
67
  });
35
68
  }
36
69
  function resolveModelContext(polyfill, signal) {
@@ -59,4 +92,4 @@ async function registerTool(context, tool, options, attempt) {
59
92
  if (attempt > 1) options.onCollision?.(tool.name, name);
60
93
  return name;
61
94
  }
62
- export { getModelContext, getWebMCPStatus, loadPolyfill, registerTools, resolveModelContext, whenModelContextAvailable };
95
+ export { AVAILABILITY_CHECK_DELAYS_MS, getModelContext, getWebMCPStatus, loadPolyfill, registerTools, resolveModelContext, whenModelContextAvailable };
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ import { AgentTools, AgentToolsProps } from "./react/AgentTools.js";
2
2
  import { AgentToolsProvider, AgentToolsProviderProps } from "./react/Provider.js";
3
3
  import { AgentToolsDevtools } from "./react/Devtools.js";
4
4
  import { ConfirmDialog } from "./react/Confirm.js";
5
- import { AgentToolsHooks, ConfirmProps } from "./react/context.js";
5
+ import { AgentToolsHooks, ConfirmLabels, ConfirmProps } from "./react/context.js";
6
6
  import { NavigateOptions } from "./next/routes.js";
7
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 };
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 };
@@ -1,5 +1,6 @@
1
1
  import { createMatcher } from "../core/match.js";
2
2
  // src/next/routes.ts
3
+ const DOT_SEGMENTS = /* @__PURE__ */ new Set([".", ".."]);
3
4
  const NAVIGATE_DESCRIPTION = "Navigate this app to one of its pages. Available tools may change after navigating.";
4
5
  function selectRoutes(routes, options) {
5
6
  if (options === true || !options.routes) return routes.filter((route) => route.params.length === 0 || route.staticParams === true);
@@ -36,22 +37,26 @@ function buildHref(routes, input) {
36
37
  }
37
38
  function resolveSegment(segment, params) {
38
39
  const optionalCatchAll = /^\[\[\.\.\.(.+)\]\]$/.exec(segment)?.[1];
39
- if (optionalCatchAll !== void 0) return splitPath(params[optionalCatchAll] ?? "");
40
+ if (optionalCatchAll !== void 0) return splitPath(optionalCatchAll, params[optionalCatchAll] ?? "");
40
41
  const catchAll = /^\[\.\.\.(.+)\]$/.exec(segment)?.[1];
41
42
  if (catchAll !== void 0) {
42
- const parts = splitPath(requireParam(params, catchAll));
43
+ const parts = splitPath(catchAll, requireParam(params, catchAll));
43
44
  if (parts.length === 0) throw new RangeError(`Missing route parameter "${catchAll}".`);
44
45
  return parts;
45
46
  }
46
47
  const dynamic = /^\[(.+)\]$/.exec(segment)?.[1];
47
- return [dynamic === void 0 ? segment : encodeURIComponent(requireParam(params, dynamic))];
48
+ return [dynamic === void 0 ? segment : encodeSegment(dynamic, requireParam(params, dynamic))];
48
49
  }
49
50
  function requireParam(params, name) {
50
51
  const value = params[name];
51
52
  if (typeof value !== "string" || value.length === 0) throw new RangeError(`Missing route parameter "${name}".`);
52
53
  return value;
53
54
  }
54
- function splitPath(value) {
55
- return value.split("/").filter(Boolean).map(encodeURIComponent);
55
+ function splitPath(name, value) {
56
+ return value.split("/").filter(Boolean).map((part) => encodeSegment(name, part));
57
+ }
58
+ function encodeSegment(name, value) {
59
+ if (DOT_SEGMENTS.has(value)) throw new RangeError(`The route parameter "${name}" cannot contain the path segment "${value}".`);
60
+ return encodeURIComponent(value);
56
61
  }
57
62
  export { NAVIGATE_DESCRIPTION, buildHref, navigateInputSchema, selectRoutes };
@@ -1,3 +1,3 @@
1
1
  import { ReactNode } from "react";
2
2
  import { ConfirmProps } from "./context.js";
3
- export declare function ConfirmDialog({ call, title, description, onConfirm, onCancel }: ConfirmProps): ReactNode;
3
+ export declare function ConfirmDialog({ call, title, description, inputSchema, labels, onConfirm, onCancel }: ConfirmProps): ReactNode;
@@ -1,7 +1,16 @@
1
1
  "use client";
2
- import { useEffect, useId, useRef } from "react";
2
+ import { Fragment, useEffect, useId, useRef } from "react";
3
+ import { isRecord } from "../core/guards.js";
3
4
  import { jsx, jsxs } from "react/jsx-runtime";
4
5
  // src/react/Confirm.tsx
6
+ const TOOL_PLACEHOLDER = "{tool}";
7
+ const DEFAULT_CONFIRM_LABELS = {
8
+ title: `Allow “${TOOL_PLACEHOLDER}”?`,
9
+ intro: "An agent wants to run this action.",
10
+ input: "Action input",
11
+ allow: "Allow",
12
+ cancel: "Cancel"
13
+ };
5
14
  const dialogStyle = {
6
15
  maxWidth: "min(28rem, calc(100vw - 2rem))",
7
16
  padding: "1.25rem",
@@ -14,7 +23,7 @@ const dialogStyle = {
14
23
  };
15
24
  const inputStyle = {
16
25
  maxHeight: "12rem",
17
- margin: "0.75rem 0",
26
+ margin: "0.75rem 0 0",
18
27
  padding: "0.5rem",
19
28
  overflow: "auto",
20
29
  border: "1px solid GrayText",
@@ -23,20 +32,57 @@ const inputStyle = {
23
32
  whiteSpace: "pre-wrap",
24
33
  wordBreak: "break-word"
25
34
  };
35
+ const fieldsStyle = {
36
+ display: "grid",
37
+ gridTemplateColumns: "auto 1fr",
38
+ gap: "0.25rem 0.75rem",
39
+ margin: 0
40
+ };
41
+ const fieldNameStyle = { fontWeight: 600 };
42
+ const fieldValueStyle = { margin: 0 };
26
43
  const actionsStyle = {
27
44
  display: "flex",
28
45
  justifyContent: "flex-end",
29
- gap: "0.5rem"
46
+ gap: "0.5rem",
47
+ marginTop: "0.75rem"
30
48
  };
31
49
  const buttonStyle = {
32
50
  padding: "0.375rem 0.875rem",
33
51
  font: "inherit",
34
52
  cursor: "pointer"
35
53
  };
36
- function ConfirmDialog({ call, title, description, onConfirm, onCancel }) {
54
+ function formatValue(value) {
55
+ return typeof value === "string" ? value : JSON.stringify(value, null, 2);
56
+ }
57
+ function fieldLabel(name, inputSchema) {
58
+ const properties = inputSchema?.properties;
59
+ const property = isRecord(properties) ? properties[name] : void 0;
60
+ return isRecord(property) && typeof property.title === "string" && property.title.trim() ? property.title : name;
61
+ }
62
+ function InputSummary({ input, inputSchema }) {
63
+ if (!isRecord(input)) return formatValue(input);
64
+ return /* @__PURE__ */ jsx("dl", {
65
+ style: fieldsStyle,
66
+ children: Object.entries(input).map(([name, value]) => /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("dt", {
67
+ style: fieldNameStyle,
68
+ children: fieldLabel(name, inputSchema)
69
+ }), /* @__PURE__ */ jsx("dd", {
70
+ style: fieldValueStyle,
71
+ children: formatValue(value)
72
+ })] }, name))
73
+ });
74
+ }
75
+ function hasInput(input) {
76
+ return isRecord(input) ? Object.keys(input).length > 0 : input !== void 0 && input !== null;
77
+ }
78
+ function ConfirmDialog({ call, title, description, inputSchema, labels, onConfirm, onCancel }) {
37
79
  const dialog = useRef(null);
38
80
  const cancelButton = useRef(null);
39
81
  const id = useId();
82
+ const text = {
83
+ ...DEFAULT_CONFIRM_LABELS,
84
+ ...labels
85
+ };
40
86
  useEffect(() => {
41
87
  const element = dialog.current;
42
88
  if (element && !element.open) element.showModal();
@@ -54,30 +100,34 @@ function ConfirmDialog({ call, title, description, onConfirm, onCancel }) {
54
100
  onCancel();
55
101
  },
56
102
  children: [
57
- /* @__PURE__ */ jsxs("h2", {
103
+ /* @__PURE__ */ jsx("h2", {
58
104
  id: `${id}-title`,
59
105
  style: {
60
106
  margin: 0,
61
107
  fontSize: "1rem"
62
108
  },
63
- children: [
64
- "Allow “",
65
- title ?? call.name,
66
- "”?"
67
- ]
109
+ children: text.title.replaceAll(TOOL_PLACEHOLDER, title ?? call.name)
68
110
  }),
69
111
  /* @__PURE__ */ jsxs("p", {
70
112
  id: `${id}-description`,
71
113
  style: { margin: "0.5rem 0 0" },
72
- children: ["An agent wants to run this action. ", description]
114
+ children: [
115
+ text.intro,
116
+ " ",
117
+ description
118
+ ]
73
119
  }),
74
- /* @__PURE__ */ jsx("pre", {
120
+ hasInput(call.input) ? /* @__PURE__ */ jsx("div", {
75
121
  tabIndex: 0,
76
122
  role: "group",
77
- "aria-label": "Action input",
123
+ "aria-label": text.input,
124
+ "data-actionmcp-confirm-input": "",
78
125
  style: inputStyle,
79
- children: JSON.stringify(call.input, null, 2)
80
- }),
126
+ children: /* @__PURE__ */ jsx(InputSummary, {
127
+ input: call.input,
128
+ inputSchema
129
+ })
130
+ }) : null,
81
131
  /* @__PURE__ */ jsxs("div", {
82
132
  style: actionsStyle,
83
133
  children: [/* @__PURE__ */ jsx("button", {
@@ -85,15 +135,15 @@ function ConfirmDialog({ call, title, description, onConfirm, onCancel }) {
85
135
  type: "button",
86
136
  style: buttonStyle,
87
137
  onClick: onCancel,
88
- children: "Cancel"
138
+ children: text.cancel
89
139
  }), /* @__PURE__ */ jsx("button", {
90
140
  type: "button",
91
141
  style: buttonStyle,
92
142
  onClick: onConfirm,
93
- children: "Allow"
143
+ children: text.allow
94
144
  })]
95
145
  })
96
146
  ]
97
147
  });
98
148
  }
99
- export { ConfirmDialog };
149
+ export { ConfirmDialog, DEFAULT_CONFIRM_LABELS, TOOL_PLACEHOLDER };
@@ -2,7 +2,7 @@
2
2
  import { useEffect, useState } from "react";
3
3
  import { subscribeToToolCalls } from "../core/events.js";
4
4
  import { getWebMCPStatus, whenModelContextAvailable } from "../core/webmcp.js";
5
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
+ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
6
6
  // src/react/DevtoolsPanel.tsx
7
7
  const HISTORY_LIMIT = 50;
8
8
  const STATUS_LABELS = {
@@ -124,7 +124,7 @@ function DevtoolsPanel() {
124
124
  setOutput(error instanceof Error ? `${error.name}: ${error.message}` : String(error));
125
125
  }
126
126
  };
127
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("button", {
127
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsxs("button", {
128
128
  type: "button",
129
129
  "data-actionmcp-devtools": "toggle",
130
130
  "aria-expanded": open,
@@ -163,7 +163,7 @@ function DevtoolsPanel() {
163
163
  describeAnnotations(tool.annotations)
164
164
  ]
165
165
  }, `${tool.origin}:${tool.name}`)),
166
- selected ? /* @__PURE__ */ jsxs(Fragment, { children: [
166
+ selected ? /* @__PURE__ */ jsxs(Fragment$1, { children: [
167
167
  /* @__PURE__ */ jsx("p", {
168
168
  style: { margin: 0 },
169
169
  children: selected.description
@@ -3,4 +3,4 @@ import { AgentToolsHooks } from "./context.js";
3
3
  export interface AgentToolsProviderProps extends AgentToolsHooks {
4
4
  children: ReactNode;
5
5
  }
6
- export declare function AgentToolsProvider({ children, onBeforeExecute, onAfterExecute, confirmComponent }: AgentToolsProviderProps): ReactNode;
6
+ export declare function AgentToolsProvider({ children, onBeforeExecute, onAfterExecute, confirmComponent, confirmLabels }: AgentToolsProviderProps): ReactNode;
@@ -3,15 +3,17 @@ import { useMemo } from "react";
3
3
  import { AgentToolsContext } from "./context.js";
4
4
  import { jsx } from "react/jsx-runtime";
5
5
  // src/react/Provider.tsx
6
- function AgentToolsProvider({ children, onBeforeExecute, onAfterExecute, confirmComponent }) {
6
+ function AgentToolsProvider({ children, onBeforeExecute, onAfterExecute, confirmComponent, confirmLabels }) {
7
7
  const hooks = useMemo(() => ({
8
8
  onBeforeExecute,
9
9
  onAfterExecute,
10
- confirmComponent
10
+ confirmComponent,
11
+ confirmLabels
11
12
  }), [
12
13
  onBeforeExecute,
13
14
  onAfterExecute,
14
- confirmComponent
15
+ confirmComponent,
16
+ confirmLabels
15
17
  ]);
16
18
  return /* @__PURE__ */ jsx(AgentToolsContext, {
17
19
  value: hooks,
@@ -1,9 +1,18 @@
1
1
  import { ComponentType } from "react";
2
- import { ToolCall } from "../core/types.js";
2
+ import { JsonSchema, ToolCall } from "../core/types.js";
3
+ export interface ConfirmLabels {
4
+ title: string;
5
+ intro: string;
6
+ input: string;
7
+ allow: string;
8
+ cancel: string;
9
+ }
3
10
  export interface ConfirmProps {
4
11
  call: ToolCall;
5
12
  title?: string | undefined;
6
13
  description: string;
14
+ inputSchema?: JsonSchema | undefined;
15
+ labels?: Partial<ConfirmLabels> | undefined;
7
16
  onConfirm: () => void;
8
17
  onCancel: () => void;
9
18
  }
@@ -11,4 +20,5 @@ export interface AgentToolsHooks {
11
20
  onBeforeExecute?: ((call: ToolCall) => boolean | Promise<boolean>) | undefined;
12
21
  onAfterExecute?: ((call: ToolCall, result: unknown) => void) | undefined;
13
22
  confirmComponent?: ComponentType<ConfirmProps> | undefined;
23
+ confirmLabels?: Partial<ConfirmLabels> | undefined;
14
24
  }
@@ -96,6 +96,8 @@ function useAgentTools(tools, registration) {
96
96
  call: current.call,
97
97
  title: current.tool.title,
98
98
  description: current.tool.description,
99
+ inputSchema: current.tool.inputSchema,
100
+ labels: hooks.confirmLabels,
99
101
  onConfirm: () => current.settle(true),
100
102
  onCancel: () => current.settle(false)
101
103
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "actionmcp",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "WebMCP tools from your Server Actions. Opt-in, typed, safe by default.",
5
5
  "license": "MIT",
6
6
  "author": "Valentin Galfre",
@@ -23,7 +23,7 @@
23
23
  "type": "module",
24
24
  "sideEffects": false,
25
25
  "bin": {
26
- "actionmcp": "./dist/cli/bin.js"
26
+ "actionmcp": "dist/cli/bin.js"
27
27
  },
28
28
  "files": [
29
29
  "dist"
@@ -66,15 +66,19 @@
66
66
  "peerDependencies": {
67
67
  "next": "^16.0.0",
68
68
  "react": "^19.2.0",
69
- "react-dom": "^19.2.0"
69
+ "react-dom": "^19.2.0",
70
+ "ts-json-schema-generator": "^2.10.0"
71
+ },
72
+ "peerDependenciesMeta": {
73
+ "ts-json-schema-generator": {
74
+ "optional": true
75
+ }
70
76
  },
71
77
  "dependencies": {
72
78
  "@standard-schema/spec": "^1.1.0",
73
79
  "@w3c/webmcp-polyfill": "^0.2.0",
74
80
  "oxc-parser": "^0.160.0",
75
81
  "tinyglobby": "^0.2.17",
76
- "ts-json-schema-generator": "~2.10.0",
77
- "typescript": "~6.0.3",
78
82
  "webmcp-types": "^0.2.0"
79
83
  },
80
84
  "devDependencies": {
@@ -90,7 +94,9 @@
90
94
  "react": "19.3.1",
91
95
  "react-dom": "19.3.1",
92
96
  "rolldown": "^1.3.3",
97
+ "ts-json-schema-generator": "~2.10.0",
93
98
  "tsdown": "^0.23.7",
99
+ "typescript": "~6.0.3",
94
100
  "valibot": "^1.5.0",
95
101
  "vitest": "^5.0.0",
96
102
  "zod": "^4.6.7"