@cavelon/cli 0.1.5 → 0.1.7

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 (42) hide show
  1. package/README.md +56 -18
  2. package/dist/command.js +10 -0
  3. package/dist/commands/api.js +40 -36
  4. package/dist/commands/chat.js +183 -0
  5. package/dist/commands/docs.js +77 -9
  6. package/dist/commands/fmt.js +61 -6
  7. package/dist/commands/index.js +3 -0
  8. package/dist/commands/init.js +61 -26
  9. package/dist/commands/inventory.js +21 -0
  10. package/dist/commands/limits-set.js +10 -6
  11. package/dist/commands/loops.js +22 -11
  12. package/dist/commands/models.js +11 -7
  13. package/dist/commands/sandboxes.js +11 -5
  14. package/dist/commands/schema.js +230 -48
  15. package/dist/commands/session.js +100 -14
  16. package/dist/commands/setup.js +22 -6
  17. package/dist/commands/solution.js +493 -86
  18. package/dist/commands/tenants.js +43 -10
  19. package/dist/commands/values.js +20 -11
  20. package/dist/commands/work.js +167 -33
  21. package/dist/confirm-token.js +72 -0
  22. package/dist/format.js +4 -4
  23. package/dist/harness-ref.js +17 -4
  24. package/dist/http.js +6 -0
  25. package/dist/kit-codes.js +11 -1
  26. package/dist/local-state.js +46 -10
  27. package/dist/main.js +38 -6
  28. package/dist/mcp.js +65 -14
  29. package/dist/openapi.js +30 -0
  30. package/dist/package-check.js +206 -18
  31. package/dist/package-files.js +98 -40
  32. package/dist/package-format.js +81 -8
  33. package/dist/package-references.js +77 -10
  34. package/dist/results.js +21 -1
  35. package/dist/session.js +9 -0
  36. package/dist/skills/cavelon-authoring/SKILL.md +54 -21
  37. package/dist/skills/cavelon-long-running/SKILL.md +13 -9
  38. package/dist/skills/cavelon-loop/SKILL.md +124 -28
  39. package/dist/skills/cavelon-testing/SKILL.md +69 -16
  40. package/dist/tenant-choice.js +19 -0
  41. package/dist/trace-view.js +172 -0
  42. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  import { closest, displayName, exactMatch } from "./choose.js";
2
2
  import { CavelonError, ExitCode } from "./errors.js";
3
3
  import { callStable } from "./invoke.js";
4
- import { isUuid } from "./session.js";
4
+ import { contextFlags, isUuid } from "./session.js";
5
5
  import { shellWord } from "./shell.js";
6
6
  function notFound(error) {
7
7
  return error instanceof CavelonError && error.status === 404;
@@ -33,14 +33,14 @@ export async function lookupHarness(ctx, ref) {
33
33
  return { harness: hit, candidates: [] };
34
34
  return { candidates: closest(all, ref) };
35
35
  }
36
- export function harnessNotFoundError(ref, candidates, source, command) {
36
+ export function harnessNotFoundError(ref, candidates, source, command, flags = "") {
37
37
  const near = candidates.map(displayName).join(", ");
38
38
  const lines = candidates.map((h) => ` ${command ? command(h.slug) : `--harness ${shellWord(h.slug)}`}`).join("\n");
39
39
  return new CavelonError(ExitCode.failure, {
40
40
  code: "solution_not_found",
41
41
  message: `No solution "${ref}" in this tenant${source ? ` (from ${source})` : ""}.${near ? ` Closest: ${near}.` : ""}`,
42
42
  hint: (candidates.length ? `If you meant one of them:\n${lines}\n` : "") +
43
- "`cavelon harness list` shows this tenant's solutions with name, slug and id; `cavelon harness new <slug>` creates one, and an env file's harness is created by `apply`.",
43
+ `\`cavelon harness list${flags}\` shows this tenant's solutions with name, slug and id; \`cavelon harness new <slug> --name <name>${flags}\` creates one as a draft.`,
44
44
  details: candidates.length ? { candidates: candidates.map((h) => ({ id: h.id, slug: h.slug, name: h.name })) } : undefined,
45
45
  });
46
46
  }
@@ -49,6 +49,19 @@ export async function resolveHarnessId(ctx, ref) {
49
49
  return ref;
50
50
  const { harness, candidates } = await lookupHarness(ctx, ref);
51
51
  if (!harness)
52
- throw harnessNotFoundError(ref, candidates);
52
+ throw harnessNotFoundError(ref, candidates, undefined, undefined, contextFlags(await ctx.session()));
53
53
  return harness.id;
54
54
  }
55
+ export function slugFromName(name) {
56
+ const plain = name.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
57
+ let slug = plain.replace(/[^a-z0-9]+/g, "-");
58
+ while (slug.startsWith("-"))
59
+ slug = slug.slice(1);
60
+ while (slug.endsWith("-"))
61
+ slug = slug.slice(0, -1);
62
+ slug = slug.slice(0, 60);
63
+ while (slug.endsWith("-"))
64
+ slug = slug.slice(0, -1);
65
+ return slug;
66
+ }
67
+ export const SLUG = /^[a-z0-9][a-z0-9-]*$/;
package/dist/http.js CHANGED
@@ -215,6 +215,7 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
215
215
  let details;
216
216
  let blockers;
217
217
  let structured;
218
+ let changed;
218
219
  const pick = (source) => {
219
220
  if (typeof source.code === "string")
220
221
  code = source.code;
@@ -232,6 +233,9 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
232
233
  const detailed = blockerDetails(source.blocker_details);
233
234
  if (detailed.length)
234
235
  structured = detailed;
236
+ const what = Array.isArray(source.changed) ? source.changed.filter((c) => typeof c === "string" && c.trim() !== "") : [];
237
+ if (what.length)
238
+ changed = what;
235
239
  };
236
240
  if (body && typeof body === "object" && !Array.isArray(body)) {
237
241
  const map = body;
@@ -276,6 +280,8 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
276
280
  hint = ceiling.hint;
277
281
  details = details && typeof details === "object" ? { ...details, ...ceiling.details } : ceiling.details;
278
282
  }
283
+ if (changed)
284
+ details = details && typeof details === "object" && !Array.isArray(details) ? { ...details, changed } : { changed };
279
285
  if (status === 400 && !hint && message && /select a tenant|tenant context|X-Tenant-Id/i.test(message)) {
280
286
  hint = "Choose a tenant with `cavelon use` (it lists your tenants), --tenant or CAVELON_TENANT.";
281
287
  }
package/dist/kit-codes.js CHANGED
@@ -34,7 +34,8 @@ export const KIT_ERROR_CODES = [
34
34
  { code: "operation_gone", area: "cli", message: "The operation no longer exists on the instance.", hint: "Start the work again; `cavelon status` lists the running operations." },
35
35
  { code: "stream_error", area: "cli", message: "The event stream of an operation broke off.", hint: "`cavelon wait <op_id>` polls instead." },
36
36
  { code: "no_solution", area: "cli", message: "This folder is not a Cavelon solution (no cavelon.yaml here or above).", hint: "Run `cavelon init`; `cavelon harness list` shows the tenant's solutions." },
37
- { code: "solution_not_found", area: "cli", message: "No solution by that name, slug or id in this tenant.", hint: "`cavelon harness list` shows them; `cavelon apply --env <name>` creates the one an env file names." },
37
+ { code: "solution_not_found", area: "cli", message: "No solution by that name, slug or id in this tenant.", hint: "`cavelon harness list` shows them; `cavelon harness new <slug> --name <name>` creates one as a draft, which apply never does; `cavelon init --harness <name> --new` creates it for a new folder, also beside a similar name." },
38
+ { code: "solution_exists", area: "cli", message: "`init --new` names a solution the tenant already has.", hint: "`cavelon init --harness <slug>` makes the folder that solution's; for a new one, give --new another name." },
38
39
  { code: "project_file_invalid", area: "cli", message: "cavelon.yaml is not a valid YAML mapping.", hint: "Fix the file at the place the message names." },
39
40
  { code: "project_file_has_secret", area: "cli", message: "cavelon.yaml holds a credential; solution files never do.", hint: "Remove it, revoke the token, and use `cavelon login` or CAVELON_TOKEN instead." },
40
41
  { code: "env_file_invalid", area: "cli", message: "An env/<name>.yaml file is invalid (not a mapping, a runtime binding that is not a resource id, or an unknown mode).", hint: "Fix the field the message names." },
@@ -52,6 +53,15 @@ export const KIT_ERROR_CODES = [
52
53
  { code: "preview_unknown", area: "cli", message: "No open preview with that id in this solution.", hint: "Run `cavelon apply` for a new preview and confirm its id; `cavelon status` lists the open ones." },
53
54
  { code: "preview_other_instance", area: "cli", message: "The preview was made on another instance.", hint: "Confirm it with the instance it was made on, or preview again here." },
54
55
  { code: "preview_other_tenant", area: "cli", message: "The preview was made for another tenant than this command acts in.", hint: "Run the confirm command the preview printed (it names --env and --tenant), or preview again here." },
56
+ { code: "preview_files_changed", area: "cli", message: "The package files changed since the preview; nothing was imported.", hint: "Run `cavelon apply` for a preview of the files as they are now, show it, and confirm its id; --allow-stale with --confirm imports what the old preview showed." },
57
+ { code: "preview_superseded", area: "cli", message: "Another preview was imported after this one, so what it showed is no longer what an import would do; nothing was imported.", hint: "Run `cavelon apply` for a new preview, show it, and confirm its id." },
58
+ { code: "preview_applied", area: "cli", message: "The preview was imported already; nothing was imported again.", hint: "`cavelon apply` previews the files as they are now; confirm that preview's id." },
59
+ { code: "preview_discarded", area: "cli", message: "The preview was discarded (apply --discard); nothing was imported.", hint: "Run `cavelon apply` for a new preview, show it, and confirm its id." },
60
+ { code: "preview_expired", area: "cli", message: "The preview is older than the kit keeps previews; nothing was imported.", hint: "Run `cavelon apply` for a new preview, show it, and confirm its id." },
61
+ { code: "confirm_token_required", area: "cli", message: "Over MCP, or run by a coding agent in its shell, a changing command confirms only with the token its preview returned, never with true or a bare --confirm.", hint: "Call the tool (or run the command) without confirm, show the person the preview, then call it again with the same arguments and confirm set to its confirm_token (--confirm <token> in a shell)." },
62
+ { code: "unknown_argument", area: "cli", message: "An MCP tool was called with an argument its schema does not list; nothing was done.", hint: "Call it again with the argument the error names (the tool's schema lists them all), spelled in snake_case." },
63
+ { code: "solution_not_active", area: "cli", message: "Only an active solution can be the tenant's default route; this one is not (a draft, or inactive after a deactivate), so nothing was changed.", hint: "Activate it through the readiness gate and preview the default route in one step: `cavelon activate --harness <slug> --make-default`." },
64
+ { code: "default_route_deactivate", area: "cli", message: "The solution is the tenant's default route, so deactivate refused it; nothing was changed.", hint: "Ask the person which solution should answer in the tenant's chat and widget instead, make it the default (`cavelon harness default <solution>`), then deactivate." },
55
65
  { code: "default_route_unknown", area: "cli", message: "The instance does not say which solution is the tenant's default route (no is_default in its solution list).", hint: "The instance may be older than default routes; check the default in the Admin." },
56
66
  { code: "limit_not_found", area: "cli", message: "The instance lists no limit by that key.", hint: "`cavelon limits` lists the keys." },
57
67
  { code: "limit_changed_by_operator", area: "cli", message: "The limit is not the tenant's to change: the operator sets it; nothing was sent.", hint: "Ask the instance's operator; `cavelon limits --key <key>` says who changes it and how." },
@@ -35,16 +35,25 @@ export async function fileDigests(root, files) {
35
35
  }
36
36
  return digests;
37
37
  }
38
- export async function writePulledFiles(root, files) {
39
- await writeState(root, PULLED_FILES, JSON.stringify({ digests: await fileDigests(root, files) }, null, 2));
38
+ const readPulled = async (root) => (await readJsonFile(path.join(stateDir(root), PULLED_FILES))) ?? {};
39
+ export async function writePulledFiles(root, files, items) {
40
+ const kept = items ?? (await readPulled(root)).items;
41
+ await writeState(root, PULLED_FILES, JSON.stringify({ digests: await fileDigests(root, files), ...(kept ? { items: kept } : {}) }, null, 2));
40
42
  }
41
- export async function rememberAppliedFiles(root, digests) {
42
- const known = await readPulledFiles(root);
43
- await writeState(root, PULLED_FILES, JSON.stringify({ digests: { ...known, ...digests } }, null, 2));
43
+ export async function readItemFiles(root) {
44
+ const items = (await readPulled(root)).items;
45
+ return items && typeof items === "object" && !Array.isArray(items) ? items : {};
46
+ }
47
+ export async function rememberAppliedFiles(root, known, unknown = []) {
48
+ const digests = { ...(await readPulledFiles(root)), ...known };
49
+ for (const file of unknown)
50
+ delete digests[file];
51
+ const items = (await readPulled(root)).items;
52
+ await writeState(root, PULLED_FILES, JSON.stringify({ digests, ...(items ? { items } : {}) }, null, 2));
44
53
  }
45
54
  export async function readPulledFiles(root) {
46
- const stored = await readJsonFile(path.join(stateDir(root), PULLED_FILES));
47
- return stored?.digests && typeof stored.digests === "object" ? stored.digests : {};
55
+ const stored = await readPulled(root);
56
+ return stored.digests && typeof stored.digests === "object" ? stored.digests : {};
48
57
  }
49
58
  export function digest(value) {
50
59
  return createHash("sha256").update(JSON.stringify(value)).digest("hex");
@@ -66,7 +75,33 @@ export async function loadPreview(root, previewId) {
66
75
  export async function deletePreview(root, previewId) {
67
76
  await fs.rm(previewFile(root, previewId), { force: true });
68
77
  }
69
- export async function listPreviews(root) {
78
+ const RETIRED_PREVIEWS = "retired-previews.json";
79
+ const RETIRED_KEPT = 200;
80
+ async function readRetired(root) {
81
+ const stored = await readJsonFile(path.join(stateDir(root), RETIRED_PREVIEWS));
82
+ return Array.isArray(stored) ? stored.filter((r) => typeof r?.preview_id === "string") : [];
83
+ }
84
+ export async function retirePreviews(root, retired) {
85
+ if (!retired.length)
86
+ return;
87
+ for (const r of retired)
88
+ await deletePreview(root, r.preview_id);
89
+ const ids = new Set(retired.map((r) => r.preview_id));
90
+ const kept = (await readRetired(root)).filter((r) => !ids.has(r.preview_id));
91
+ await writeState(root, RETIRED_PREVIEWS, JSON.stringify([...kept, ...retired].slice(-RETIRED_KEPT), null, 2));
92
+ }
93
+ export async function retiredPreview(root, previewId) {
94
+ return (await readRetired(root)).find((r) => r.preview_id === previewId);
95
+ }
96
+ export const PREVIEW_MAX_AGE_MS = 24 * 60 * 60 * 1000;
97
+ export function previewExpiry(createdAt, now) {
98
+ const created = Date.parse(createdAt);
99
+ if (Number.isNaN(created))
100
+ return { expires_at: null, expired: true };
101
+ const expires = created + PREVIEW_MAX_AGE_MS;
102
+ return { expires_at: new Date(expires).toISOString(), expired: now.getTime() >= expires };
103
+ }
104
+ export async function listPreviews(root, now) {
70
105
  const dir = path.join(stateDir(root), "previews");
71
106
  let names;
72
107
  try {
@@ -78,8 +113,9 @@ export async function listPreviews(root) {
78
113
  const out = [];
79
114
  for (const name of names.filter((n) => n.endsWith(".json"))) {
80
115
  const stored = await readJsonFile(path.join(dir, name));
81
- if (stored?.preview_id)
82
- out.push({ preview_id: stored.preview_id, created_at: stored.created_at, env: stored.env, harness: stored.harness });
116
+ if (stored?.preview_id) {
117
+ out.push({ preview_id: stored.preview_id, created_at: stored.created_at, env: stored.env, harness: stored.harness, ...previewExpiry(stored.created_at, now) });
118
+ }
83
119
  }
84
120
  return out.sort((a, b) => (a.created_at < b.created_at ? 1 : -1));
85
121
  }
package/dist/main.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { parseArgs } from "node:util";
2
- import { GLOBAL_OPTIONS } from "./command.js";
2
+ import { GLOBAL_OPTIONS, optionDescription, optionFlag } from "./command.js";
3
3
  import { createContext, withWarnings } from "./context.js";
4
+ import { CONFIRM_TOKEN } from "./confirm-token.js";
4
5
  import { asCavelonError, ExitCode, usageError } from "./errors.js";
5
6
  import { blockerLines } from "./format.js";
6
7
  import { blockerLines as detailedBlockerLines } from "./preview-report.js";
@@ -116,8 +117,9 @@ function parse(spec, args) {
116
117
  }
117
118
  }
118
119
  const options = { ...GLOBAL_OPTIONS, ...spec.options };
120
+ const { rest, tokens } = takeTokens(spec, args);
119
121
  const config = {
120
- args,
122
+ args: rest,
121
123
  allowPositionals: true,
122
124
  strict: true,
123
125
  options: Object.fromEntries(Object.entries(options).map(([name, o]) => [
@@ -140,6 +142,7 @@ function parse(spec, args) {
140
142
  }
141
143
  if (values.help === true)
142
144
  return { positionals: {}, options: { help: true } };
145
+ Object.assign(values, tokens);
143
146
  const named = {};
144
147
  const specs = spec.positionals ?? [];
145
148
  let index = 0;
@@ -161,6 +164,38 @@ function parse(spec, args) {
161
164
  }
162
165
  return { positionals: named, options: values };
163
166
  }
167
+ function takeTokens(spec, args) {
168
+ const names = Object.entries(spec.options ?? {})
169
+ .filter(([, o]) => o.mcpToken && o.type === "boolean")
170
+ .map(([name]) => name);
171
+ const tokens = {};
172
+ if (!names.length)
173
+ return { rest: args, tokens };
174
+ const rest = [];
175
+ for (let i = 0; i < args.length; i++) {
176
+ const arg = args[i];
177
+ if (arg === "--") {
178
+ rest.push(...args.slice(i));
179
+ break;
180
+ }
181
+ const name = names.find((n) => arg === `--${n}` || arg.startsWith(`--${n}=`));
182
+ if (!name) {
183
+ rest.push(arg);
184
+ continue;
185
+ }
186
+ const inline = arg.startsWith(`--${name}=`) ? arg.slice(name.length + 3) : undefined;
187
+ const next = args[i + 1];
188
+ if (inline)
189
+ tokens[name] = inline;
190
+ else if (inline === undefined && next !== undefined && CONFIRM_TOKEN.test(next)) {
191
+ tokens[name] = next;
192
+ i++;
193
+ }
194
+ else
195
+ rest.push(`--${name}`);
196
+ }
197
+ return { rest, tokens };
198
+ }
164
199
  function missing(spec, name) {
165
200
  return usageError(`Missing <${name}>.`, `Usage: ${usageLine(spec)}`);
166
201
  }
@@ -212,10 +247,7 @@ export function usageLine(spec) {
212
247
  return parts.join(" ");
213
248
  }
214
249
  function optionLines(options) {
215
- const rows = Object.entries(options).map(([name, o]) => {
216
- const flag = `${o.short ? `-${o.short}, ` : ""}--${name}${o.type === "string" ? ` ${o.value ?? "<value>"}` : ""}`;
217
- return [flag, o.description + (o.multiple ? " Repeatable." : "")];
218
- });
250
+ const rows = Object.entries(options).map(([name, o]) => [optionFlag(name, o), optionDescription(name, o)]);
219
251
  const width = Math.max(...rows.map(([f]) => f.length));
220
252
  return rows.map(([f, d]) => ` ${f.padEnd(width)} ${d}`);
221
253
  }
package/dist/mcp.js CHANGED
@@ -2,20 +2,26 @@ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
2
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
3
3
  import { MCP_MAX_WAIT_MS } from "./commands/async.js";
4
4
  import { createContext, withWarnings } from "./context.js";
5
- import { asCavelonError, usageError } from "./errors.js";
5
+ import { asCavelonError, CavelonError, ExitCode, usageError } from "./errors.js";
6
+ import { closest } from "./package-references.js";
6
7
  import { KIT_VERSION } from "./version.js";
7
8
  const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a person stored with `cavelon login` " +
8
9
  "(or CAVELON_TOKEN). You never see or pass the token. Tools that start work (kb_upload, test_run, " +
9
10
  "loop_start, sandbox_seed, artifacts_export) return operation ids at once; read them with operation_status, which returns " +
10
11
  `the state at once, or waits up to its timeout (at most ${MCP_MAX_WAIT_MS / 1000} s) when given one, and reports waited_ms, ` +
11
12
  "and follow a loop with loop_iterations. What needs confirmation: apply imports only with confirm set to a preview's id; " +
12
- "limits_set, models_set_limit, loop_cancel, sandbox_seed, trigger_identity, harness_default, activate with make_default, " +
13
+ "limits_set, models_set_limit, loop_cancel, sandbox_seed, trigger_identity, harness_default, activate with make_default, deactivate, " +
13
14
  "and api for an operation that is not read-only, " +
14
- "return what they would do and change nothing without confirm: true; show the person that first. The default route " +
15
+ "return what they would do and a confirm_token, and change nothing until called again with the same arguments and " +
16
+ "confirm set to that token: show the person the preview first. The token confirms exactly the change the preview showed; " +
17
+ "a different change needs a new preview, and confirm: true is refused. The default route " +
15
18
  "(harness_default, activate's make_default) decides which solution the tenant's chat and widget answer with: live traffic, " +
16
- "so ask the person, and confirm only with their yes. " +
19
+ "so ask the person, and confirm only with their yes; the same goes for deactivate, which takes a solution out of live traffic " +
20
+ "(its status becomes inactive), and for apply with tenant_wide, which imports the tenant-wide sections (tenant_settings, " +
21
+ "model_registry, …) for every solution of the tenant. " +
22
+ "chat sends one message to a solution and returns its answer: the way to try one that is not the default route. " +
17
23
  "kb_upload names files that match an active document of the knowledge base; with replace it replaces them, and where the " +
18
- "instance's upload cannot, it returns what it would deactivate and uploads nothing without confirm: true. " +
24
+ "instance's upload cannot, it returns what it would deactivate and uploads nothing without its confirm_token. " +
19
25
  "init, pull and fmt change nothing on the instance (pull only reads it); they write files in the solution folder without confirm " +
20
26
  "(pull refuses to replace a package file that changed since the last pull or apply and is not committed, unless force), " +
21
27
  "and the other changing tools act at once. api refuses, even with confirm, an operation the instance marks for a person " +
@@ -34,27 +40,32 @@ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a pe
34
40
  "to run in their terminal, and never ask for, read or pass a secret value. Never approve or decide an approval; " +
35
41
  "that stays with a person. Use docs_search before guessing, " +
36
42
  "and api_list/api_describe/api for anything without its own tool.";
43
+ const TOKEN_DESCRIPTION = "Over MCP: the confirm_token this tool's preview returned, which confirms exactly the change it showed; true is refused.";
37
44
  export function toolName(spec) {
38
45
  return spec.mcpTool || undefined;
39
46
  }
40
47
  function ownsTenant(spec) {
41
48
  return Boolean(spec.positionals?.some((p) => p.name === "tenant") || spec.options?.tenant);
42
49
  }
50
+ export function propertyName(name) {
51
+ return name.replaceAll("-", "_");
52
+ }
43
53
  export function inputSchema(spec) {
44
54
  const properties = {};
45
55
  const required = [];
46
56
  for (const p of spec.positionals ?? []) {
47
- properties[p.name] = p.variadic
57
+ properties[propertyName(p.name)] = p.variadic
48
58
  ? { type: "array", items: { type: "string" }, description: p.description }
49
59
  : { type: "string", description: p.description };
50
60
  if (p.required)
51
- required.push(p.name);
61
+ required.push(propertyName(p.name));
52
62
  }
53
63
  for (const [name, option] of Object.entries(spec.options ?? {})) {
54
64
  if (option.cliOnly)
55
65
  continue;
56
- properties[name] =
57
- option.type === "boolean" || option.mcpBoolean
66
+ properties[propertyName(name)] = option.mcpToken
67
+ ? { type: "string", description: `${option.description} ${TOKEN_DESCRIPTION}` }
68
+ : option.type === "boolean"
58
69
  ? { type: "boolean", description: option.description }
59
70
  : option.multiple
60
71
  ? { type: "array", items: { type: "string" }, description: option.description }
@@ -80,10 +91,35 @@ export function toolFor(spec) {
80
91
  },
81
92
  };
82
93
  }
94
+ function argumentsOf(spec, args, warn) {
95
+ const properties = Object.keys(inputSchema(spec).properties ?? {});
96
+ const out = {};
97
+ for (const [key, value] of Object.entries(args)) {
98
+ if (properties.includes(key)) {
99
+ out[key] = value;
100
+ continue;
101
+ }
102
+ const spelled = propertyName(key);
103
+ if (spelled !== key && properties.includes(spelled)) {
104
+ warn(`"${key}" is spelled "${spelled}" in this tool's schema; "${key}" is still taken for now and will be refused in a later release.`);
105
+ if (!(spelled in args))
106
+ out[spelled] = value;
107
+ continue;
108
+ }
109
+ const near = closest(key, properties);
110
+ throw new CavelonError(ExitCode.usage, {
111
+ code: "unknown_argument",
112
+ message: `${spec.mcpTool} has no argument "${key}"; nothing was done.${near ? ` Did you mean "${near}"?` : ""}`,
113
+ hint: `Its arguments: ${properties.join(", ")}.`,
114
+ details: { argument: key, ...(near ? { suggestion: near } : {}), arguments: properties },
115
+ });
116
+ }
117
+ return out;
118
+ }
83
119
  function inputFrom(spec, args) {
84
120
  const input = { positionals: {}, options: {} };
85
121
  for (const p of spec.positionals ?? []) {
86
- const value = args[p.name];
122
+ const value = args[propertyName(p.name)];
87
123
  if (value === undefined || value === null)
88
124
  continue;
89
125
  input.positionals[p.name] = p.variadic ? (Array.isArray(value) ? value.map(String) : [String(value)]) : String(value);
@@ -91,10 +127,12 @@ function inputFrom(spec, args) {
91
127
  for (const [name, option] of Object.entries(spec.options ?? {})) {
92
128
  if (option.cliOnly)
93
129
  continue;
94
- const value = args[name];
130
+ const value = args[propertyName(name)];
95
131
  if (value === undefined || value === null)
96
132
  continue;
97
- if (option.type === "boolean" || option.mcpBoolean)
133
+ if (option.mcpToken)
134
+ input.options[name] = value === true || value === "true" ? true : value === false ? false : String(value);
135
+ else if (option.type === "boolean")
98
136
  input.options[name] = value === true || value === "true";
99
137
  else if (option.multiple)
100
138
  input.options[name] = Array.isArray(value) ? value.map(String) : [String(value)];
@@ -104,7 +142,10 @@ function inputFrom(spec, args) {
104
142
  return input;
105
143
  }
106
144
  function missingRequired(spec, args) {
107
- return (spec.positionals ?? []).filter((p) => p.required && (args[p.name] === undefined || args[p.name] === "")).map((p) => p.name);
145
+ return (spec.positionals ?? [])
146
+ .map((p) => ({ ...p, name: propertyName(p.name) }))
147
+ .filter((p) => p.required && (args[p.name] === undefined || args[p.name] === ""))
148
+ .map((p) => p.name);
108
149
  }
109
150
  function mcpIo(io) {
110
151
  return { ...io, stdout: { write: () => true, isTTY: false } };
@@ -116,13 +157,21 @@ export function createMcpServer(io, commands) {
116
157
  server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: tools.map(toolFor) }));
117
158
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
118
159
  const spec = byName.get(request.params.name);
119
- const args = (request.params.arguments ?? {});
160
+ const given = (request.params.arguments ?? {});
120
161
  const fail = (error) => ({
121
162
  isError: true,
122
163
  content: [{ type: "text", text: JSON.stringify({ error: asCavelonError(error).toJSON() }) }],
123
164
  });
124
165
  if (!spec)
125
166
  return fail(new Error(`Unknown tool ${request.params.name}.`));
167
+ const spelling = [];
168
+ let args;
169
+ try {
170
+ args = argumentsOf(spec, given, (message) => spelling.push(message));
171
+ }
172
+ catch (error) {
173
+ return fail(error);
174
+ }
126
175
  const missing = missingRequired(spec, args);
127
176
  if (missing.length) {
128
177
  return fail(usageError(`Missing ${missing.join(", ")}.`));
@@ -130,6 +179,8 @@ export function createMcpServer(io, commands) {
130
179
  const tenant = !ownsTenant(spec) && typeof args.tenant === "string" ? args.tenant : undefined;
131
180
  const solutionEnv = spec.options?.env && typeof args.env === "string" ? args.env : undefined;
132
181
  const ctx = createContext(mcpIo(io), { json: true, tenant, solutionEnv }, "mcp");
182
+ for (const message of spelling)
183
+ ctx.warn(message);
133
184
  try {
134
185
  const result = await spec.run(ctx, inputFrom(spec, args));
135
186
  let data = result.data;
package/dist/openapi.js CHANGED
@@ -226,6 +226,34 @@ export function secretFields(doc, schema, body) {
226
226
  walk(schema, body, "", 0);
227
227
  return [...found];
228
228
  }
229
+ export function secretPaths(doc, schema) {
230
+ const found = new Set();
231
+ let budget = 2_000;
232
+ const list = (value) => (Array.isArray(value) ? value : []);
233
+ const walk = (raw, where, depth) => {
234
+ if (depth > 6 || --budget < 0)
235
+ return;
236
+ const node = deref(doc, raw);
237
+ if (!node || typeof node !== "object")
238
+ return;
239
+ const s = node;
240
+ if (s["x-cavelon-secret"] === true) {
241
+ found.add(where || "(body)");
242
+ return;
243
+ }
244
+ for (const key of ["allOf", "anyOf", "oneOf"])
245
+ for (const sub of list(s[key]))
246
+ walk(sub, where, depth + 1);
247
+ if (s.items)
248
+ walk(s.items, `${where}[]`, depth + 1);
249
+ for (const [key, sub] of Object.entries((s.properties ?? {})))
250
+ walk(sub, where ? `${where}.${key}` : key, depth + 1);
251
+ if (s.additionalProperties && typeof s.additionalProperties === "object")
252
+ walk(s.additionalProperties, where ? `${where}.*` : "*", depth + 1);
253
+ };
254
+ walk(schema, "", 0);
255
+ return [...found];
256
+ }
229
257
  function matches(pattern, key) {
230
258
  try {
231
259
  return new RegExp(pattern, "u").test(key);
@@ -295,6 +323,8 @@ export function describeSchema(doc, schema, depth = 0) {
295
323
  parts.push(`one of ${sub.enum.join(", ")}`);
296
324
  if (sub.default !== undefined)
297
325
  parts.push(`default ${JSON.stringify(sub.default)}`);
326
+ if (secretPaths(doc, p).includes("(body)"))
327
+ parts.push("secret value (x-cavelon-secret): a person enters it");
298
328
  fields[name] = parts.join(", ");
299
329
  if (items && depth < 3)
300
330
  fields[`${name}[]`] = describeSchema(doc, items, depth + 1);