@agntn/tools 0.2.4 → 0.3.1

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.
@@ -12,8 +12,17 @@ export interface McpServerInfo {
12
12
  /** Project home a client can link to. */
13
13
  readonly websiteUrl?: string;
14
14
  }
15
+ /** What a tool finds in `host` over MCP. The client wrote all of it, so none of it is proof. */
16
+ export interface McpHost {
17
+ readonly mcp: true;
18
+ /** The HTTP request behind the call, headers included. Absent over stdio. */
19
+ readonly request?: Request;
20
+ /** The call's `_meta` as the transport hands it over, such as a harness's session id. */
21
+ readonly meta?: Readonly<Record<string, unknown>>;
22
+ }
15
23
  /**
16
24
  * Maps a tool's title and declared effect to MCP annotations. Claude Code reads its label here.
25
+ * A process the tool starts can delete anything, so `exec` counts as destructive.
17
26
  *
18
27
  * @param tool - Tool to describe.
19
28
  * @returns {ToolAnnotations} Title and hints for the MCP client.
@@ -1,11 +1,21 @@
1
1
  import { Check, Errors } from "./libs/typebox.mjs";
2
2
  import { ToolInputError, indexTools, invokeTool, sanitizeLine, wireSchema } from "./src.mjs";
3
+ import { causeLines } from "./causes.mjs";
3
4
  import { hostAsk, readAnswer } from "./questions.mjs";
5
+ function mcpHost(from) {
6
+ const { request, meta } = from;
7
+ if (request === void 0 && meta === void 0) return {};
8
+ return { host: {
9
+ mcp: true,
10
+ ...request === void 0 ? {} : { request },
11
+ ...meta === void 0 ? {} : { meta }
12
+ } };
13
+ }
4
14
  function toolAnnotations(tool) {
5
15
  return {
6
16
  title: tool.title,
7
17
  readOnlyHint: tool.effect === "read",
8
- destructiveHint: tool.effect === "destructive",
18
+ destructiveHint: tool.effect === "destructive" || tool.effect === "exec",
9
19
  idempotentHint: tool.idempotent ?? tool.effect === "read",
10
20
  openWorldHint: tool.openWorld ?? false
11
21
  };
@@ -45,7 +55,7 @@ async function callTool(info, tools, name, args = {}, context = {}) {
45
55
  return answer(tool, await invokeTool(tool, args, context));
46
56
  } catch (error) {
47
57
  if (error instanceof ToolInputError) return errorResult(...error.lines);
48
- return errorResult(`${tool.name} failed: ${error instanceof Error ? error.message : String(error)}`);
58
+ return errorResult(`${tool.name} failed: ${error instanceof Error ? error.message : String(error)}`, ...causeLines(error));
49
59
  }
50
60
  }
51
61
  function answer(tool, result) {
@@ -180,4 +190,4 @@ function progressSteps(notify) {
180
190
  });
181
191
  };
182
192
  }
183
- export { callAsking, callTool, canAsk, copyIcons, errorResult, listTools, progressSteps, questionRound, toolAnnotations };
193
+ export { callAsking, callTool, canAsk, copyIcons, errorResult, listTools, mcpHost, progressSteps, questionRound, toolAnnotations };
@@ -178,21 +178,37 @@ function schemaAt(root, pointer) {
178
178
  async function invokeTool(tool, args, context = {}) {
179
179
  const checked = validateInput(tool, args);
180
180
  if (!checked.ok) throw new ToolInputError(checked.lines, checked.issues, tool.name);
181
+ const signal = tool.effect === "read" ? context.signal : void 0;
182
+ signal?.throwIfAborted();
181
183
  const { progress, ask } = context;
182
- if (!progress && !ask) return await tool.execute(checked.value, context);
184
+ if (!progress && !ask) return await untilAborted(() => tool.execute(checked.value, context), signal);
183
185
  let settled = false;
184
186
  const questions = ask ? closedAfter(tool, ask, () => settled) : void 0;
187
+ const call = async () => {
188
+ try {
189
+ return await tool.execute(checked.value, {
190
+ ...context,
191
+ ...progress ? { progress: quietAfter(progress, () => settled) } : {},
192
+ ...questions ? { ask: questions.ask } : {}
193
+ });
194
+ } finally {
195
+ await questions?.drained();
196
+ }
197
+ };
185
198
  try {
186
- return await tool.execute(checked.value, {
187
- ...context,
188
- ...progress ? { progress: quietAfter(progress, () => settled) } : {},
189
- ...questions ? { ask: questions.ask } : {}
190
- });
199
+ return await untilAborted(call, signal);
191
200
  } finally {
192
- await questions?.drained();
193
201
  settled = true;
194
202
  }
195
203
  }
204
+ async function untilAborted(start, signal) {
205
+ if (!signal) return await start();
206
+ return await new Promise((resolve, reject) => {
207
+ const abort = () => reject(signal.reason);
208
+ signal.addEventListener("abort", abort, { once: true });
209
+ Promise.try(start).then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
210
+ });
211
+ }
196
212
  function quietAfter(progress, settled) {
197
213
  return (message, amount) => {
198
214
  if (settled()) return;
package/dist/ai.d.mts CHANGED
@@ -1,31 +1,41 @@
1
1
  import { Static, TObject } from "./_chunks/libs/typebox.mjs";
2
2
  import { ToolDefinition } from "./_chunks/index.mjs";
3
3
  import { Tool } from "ai";
4
+ /** An image block of the result, base64 with its MIME type, as MCP sends it. */
5
+ export interface AiToolImage {
6
+ data: string;
7
+ mimeType: string;
8
+ }
4
9
  /**
5
10
  * What an AI SDK tool returns: the executor's details with the text MCP
6
- * clients read. Your code gets the whole object, the model reads only `text`.
11
+ * clients read. Your code gets the whole object, the model reads `text` and `images`.
7
12
  */
8
13
  export type AiToolOutput<Details> = (Details extends object ? Details : {
9
14
  details: Details;
10
15
  }) & {
11
16
  text: string;
17
+ /** The result's image blocks, present only when it has some. */
18
+ images?: AiToolImage[];
12
19
  };
13
20
  /**
14
21
  * Converts one tool, keeping its input and details types.
15
22
  *
16
23
  * A result with `isError` throws its text, which the AI SDK reports to the
17
24
  * model as a tool error, the same as an executor that throws. The model reads
18
- * `text` alone, as on every other host, not the details spelled out a second time.
25
+ * `text` and the images, as on every other host, not the details spelled out a second time.
19
26
  *
20
27
  * @param definition - Tool to convert.
21
28
  * @returns {Tool} AI SDK tool.
22
29
  */
23
30
  export declare function toAiTool<Input extends TObject, Details>(definition: ToolDefinition<Input, Details>): Tool<Static<Input>, AiToolOutput<Details>>;
31
+ /** What {@link toAiTools} returns: each tool under its own name, typed like {@link toAiTool}. */
32
+ export type AiTools<Tools extends readonly ToolDefinition[]> = { [Definition in Tools[number] as Definition["name"]]: Definition extends ToolDefinition<infer Input, infer Details> ? Tool<Static<Input>, AiToolOutput<Details>> : never; };
24
33
  /**
25
- * Builds an AI SDK tool set keyed by tool name.
34
+ * Builds an AI SDK tool set keyed by tool name, typed per tool.
35
+ * `Object.fromEntries` only knows a record, so the result is cast to the `AiTools` it built.
26
36
  *
27
37
  * @param tools - Tools to convert.
28
- * @returns {Record<string, Tool>} AI SDK tools.
38
+ * @returns {AiTools<Tools>} AI SDK tools.
29
39
  * @throws {ToolDefinitionError} When two tools share a name.
30
40
  */
31
- export declare function toAiTools(tools: readonly ToolDefinition[]): Record<string, Tool>;
41
+ export declare function toAiTools<const Tools extends readonly ToolDefinition[]>(tools: Tools): AiTools<Tools>;
package/dist/ai.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { ToolDefinitionError, indexTools, invokeTool, resultText, validateInput, wireSchema } from "./_chunks/src.mjs";
2
+ import { throwWithCauses } from "./_chunks/causes.mjs";
2
3
  import { jsonSchema, tool } from "ai";
3
4
  function toAiTool(definition) {
4
5
  return tool({
@@ -15,33 +16,79 @@ function toAiTool(definition) {
15
16
  };
16
17
  } }),
17
18
  async execute(input, { abortSignal }) {
18
- const result = await invokeTool(definition, input, abortSignal ? { signal: abortSignal } : {});
19
+ const result = await invokeTool(definition, input, abortSignal ? { signal: abortSignal } : {}).catch(throwWithCauses);
19
20
  const text = resultText(result);
20
21
  if (result.isError) throw new Error(text);
21
- const { details } = result;
22
- if (typeof details !== "object" || details === null) return {
23
- details,
24
- text
25
- };
26
- if (Object.hasOwn(details, "text")) throw new ToolDefinitionError(`${definition.name}: details must not have a text field, the AI SDK output adds one`);
27
- return {
28
- ...details,
29
- text
30
- };
22
+ return aiOutput(definition.name, result, text);
31
23
  },
32
24
  toModelOutput: ({ output }) => modelOutput(output)
33
25
  });
34
26
  }
27
+ const ADDED_FIELDS = ["text", "images"];
28
+ function aiOutput(name, result, text) {
29
+ const images = result.content.flatMap((block) => block.type === "image" ? [{
30
+ data: block.data,
31
+ mimeType: block.mimeType
32
+ }] : []);
33
+ const added = images.length > 0 ? {
34
+ text,
35
+ images
36
+ } : { text };
37
+ const { details } = result;
38
+ if (typeof details !== "object" || details === null) return {
39
+ details,
40
+ ...added
41
+ };
42
+ const taken = ADDED_FIELDS.find((field) => Object.hasOwn(details, field));
43
+ if (taken !== void 0) throw new ToolDefinitionError(`${name}: details must not have their own ${taken} field, the AI SDK output adds one`);
44
+ return {
45
+ ...details,
46
+ ...added
47
+ };
48
+ }
35
49
  function modelOutput(output) {
36
- const text = typeof output === "object" && output !== null ? output.text : void 0;
37
- return typeof text === "string" && text !== "" ? {
38
- type: "text",
39
- value: text
40
- } : {
50
+ const { text, images } = outputFields(output);
51
+ if (images.length > 0) {
52
+ const files = images.map((image) => ({
53
+ type: "file",
54
+ data: {
55
+ type: "data",
56
+ data: image.data
57
+ },
58
+ mediaType: image.mimeType
59
+ }));
60
+ return {
61
+ type: "content",
62
+ value: text === "" ? files : [{
63
+ type: "text",
64
+ text
65
+ }, ...files]
66
+ };
67
+ }
68
+ return text === "" ? {
41
69
  type: "json",
42
70
  value: output
71
+ } : {
72
+ type: "text",
73
+ value: text
43
74
  };
44
75
  }
76
+ function outputFields(output) {
77
+ if (typeof output !== "object" || output === null) return {
78
+ text: "",
79
+ images: []
80
+ };
81
+ const { text, images } = output;
82
+ return {
83
+ text: typeof text === "string" ? text : "",
84
+ images: Array.isArray(images) ? images.filter(isImage) : []
85
+ };
86
+ }
87
+ function isImage(value) {
88
+ if (typeof value !== "object" || value === null) return false;
89
+ const { data, mimeType } = value;
90
+ return typeof data === "string" && typeof mimeType === "string";
91
+ }
45
92
  function toAiTools(tools) {
46
93
  indexTools(tools);
47
94
  return Object.fromEntries(tools.map((definition) => [definition.name, toAiTool(definition)]));
package/dist/cli.d.mts CHANGED
@@ -16,7 +16,12 @@ export interface CliOptions {
16
16
  * and leaves `progress` alone: on a terminal its line would sit in front of the rows.
17
17
  */
18
18
  readonly commands?: readonly ToolDefinition[];
19
- /** Command for an empty command line. */
19
+ /**
20
+ * Groups the `cli.command` hints open with a first word, as `servers` in
21
+ * `servers list`: their line in the command list and more words for them.
22
+ */
23
+ readonly groups?: Readonly<Record<string, CliGroup>>;
24
+ /** Command for an empty command line, two words for a command in a group. */
20
25
  readonly default?: string;
21
26
  /** Command for a first word that names no command: `hashes sha256 x` runs `hashes hash sha256 x`. */
22
27
  readonly fallback?: string;
@@ -28,6 +33,12 @@ export interface CliOptions {
28
33
  */
29
34
  readonly expected?: (error: unknown) => boolean;
30
35
  }
36
+ /** A group of commands: `servers` in `servers list` and `servers add`. */
37
+ export interface CliGroup {
38
+ /** Line in the command list. Defaults to the names of its commands. */
39
+ readonly description?: string;
40
+ readonly aliases?: readonly string[];
41
+ }
31
42
  /** What a CLI command finds in `host`: narrow to it and look at `json` before writing a byte. */
32
43
  export interface CliHost {
33
44
  readonly cli: true;
@@ -36,7 +47,8 @@ export interface CliHost {
36
47
  }
37
48
  /**
38
49
  * @param tool - Tool to name.
39
- * @returns {string} The hinted command, or the tool name without its package prefix, in kebab case.
50
+ * @returns {string} The hinted command, two words for one in a group, or the tool name without
51
+ * its package prefix, in kebab case.
40
52
  */
41
53
  export declare function commandName(tool: ToolDefinition): string;
42
54
  /** A built command line interface. */
@@ -50,7 +62,8 @@ export interface Cli {
50
62
  *
51
63
  * @param options - CLI options.
52
64
  * @returns {Cli} The CLI.
53
- * @throws {ToolDefinitionError} When two commands share a name or alias, a hint does not fit its schema, or `default` or `fallback` names no command.
65
+ * @throws {ToolDefinitionError} When two commands share a name or alias, a hint does not fit its
66
+ * schema, `groups` names no group, or `default` or `fallback` names no command.
54
67
  */
55
68
  export declare function createCli(options: CliOptions): Cli;
56
69
  /**
package/dist/cli.mjs CHANGED
@@ -10,6 +10,7 @@ const RESERVED_FLAGS = /* @__PURE__ */ new Set([
10
10
  ]);
11
11
  const TEXT_KINDS = /* @__PURE__ */ new Set(["string", "enum"]);
12
12
  const SHORT_FLAG = /^[a-z]$/i;
13
+ const INLINE_ENUM_WIDTH = 40;
13
14
  const TYPE_KINDS = /* @__PURE__ */ new Map([
14
15
  ["boolean", "boolean"],
15
16
  ["integer", "number"],
@@ -21,7 +22,7 @@ function flagName(key) {
21
22
  return key.replaceAll(/([a-z0-9])([A-Z])/g, "$1-$2").replaceAll("_", "-").toLowerCase();
22
23
  }
23
24
  function commandName(tool) {
24
- if (tool.cli?.command !== void 0) return commandWord(tool.name, tool.cli.command);
25
+ if (tool.cli?.command !== void 0) return commandPath(tool.name, tool.cli.command);
25
26
  const separator = tool.name.indexOf("_");
26
27
  const derived = separator === -1 ? tool.name : tool.name.slice(separator + 1);
27
28
  return commandWord(tool.name, derived.replaceAll("_", "-"));
@@ -31,6 +32,12 @@ function commandWord(owner, word) {
31
32
  if (!COMMAND_WORD.test(word)) throw new ToolDefinitionError(`${owner}: command ${JSON.stringify(word)} must match ${COMMAND_WORD}`);
32
33
  return word;
33
34
  }
35
+ function commandPath(owner, path) {
36
+ const words = path.split(" ");
37
+ if (words.length > 2) throw new ToolDefinitionError(`${owner}: command ${JSON.stringify(path)} takes two words at most`);
38
+ for (const word of words) commandWord(owner, word);
39
+ return path;
40
+ }
34
41
  function fieldKind(schema) {
35
42
  if (Array.isArray(schema.enum) && schema.enum.every((value) => typeof value === "string")) return "enum";
36
43
  if ((Array.isArray(schema.anyOf) ? schema.anyOf : []).some((branch) => fieldKind(branch) === "json")) return "json";
@@ -146,10 +153,11 @@ function assertOneOptionPerSpelling(tool, fields) {
146
153
  }
147
154
  }
148
155
  }
149
- function fieldDescription(field) {
156
+ function fieldDescription(field, values = "") {
150
157
  const { schema } = field;
151
158
  return [
152
159
  typeof schema.description === "string" ? schema.description : "",
160
+ values === "" ? "" : `(one of ${values})`,
153
161
  field.stdin ? "(- reads stdin)" : "",
154
162
  field.required ? "(required)" : ""
155
163
  ].filter((part) => part !== "").join(" ");
@@ -158,8 +166,15 @@ function valueHint(field) {
158
166
  if (field.kind === "enum") return field.schema.enum.join("|");
159
167
  return field.kind === "string" ? field.flag : field.kind;
160
168
  }
161
- function optionSpelling(field) {
162
- return field.kind === "boolean" ? `--[no-]${field.flag}` : `--${field.flag}=<${valueHint(field)}>`;
169
+ function optionSpelling(field, hint = valueHint(field)) {
170
+ return field.kind === "boolean" ? `--[no-]${field.flag}` : `--${field.flag}=<${hint}>`;
171
+ }
172
+ function optionRow(field) {
173
+ const short = field.short === void 0 ? "" : `-${field.short}, `;
174
+ const spelling = `${short}${optionSpelling(field)}`;
175
+ const named = `${short}${optionSpelling(field, field.flag)}`;
176
+ if (field.kind !== "enum" || spelling.length <= INLINE_ENUM_WIDTH || named.length >= spelling.length) return [spelling, fieldDescription(field)];
177
+ return [named, fieldDescription(field, field.schema.enum.join(", "))];
163
178
  }
164
179
  function emptyRecord() {
165
180
  return Object.create(null);
@@ -256,12 +271,12 @@ function longField(spelled, options) {
256
271
  if (name === "help") return "option";
257
272
  const field = Object.hasOwn(options, name) ? options[name] : void 0;
258
273
  if (field !== void 0) return field === "json" ? "option" : field;
259
- return negatesBoolean(name, options) ? "option" : void 0;
274
+ return negatedField(name, options) === void 0 ? void 0 : "option";
260
275
  }
261
- function negatesBoolean(name, options) {
276
+ function negatedField(name, options) {
262
277
  const flag = name.slice(3);
263
278
  const field = name.startsWith("no-") && Object.hasOwn(options, flag) ? options[flag] : void 0;
264
- return field !== void 0 && field !== "json" && field.kind === "boolean";
279
+ return field !== "json" && field?.kind === "boolean" ? field : void 0;
265
280
  }
266
281
  function shortField(word, options) {
267
282
  return Object.values(options).find((field) => field !== "json" && field.short !== void 0 && `-${field.short}` === word);
@@ -285,7 +300,7 @@ function asksHelp(token, word) {
285
300
  }
286
301
  function optionField(options, token, word) {
287
302
  if (asksHelp(token, word)) return "help";
288
- const field = Object.hasOwn(options, token.name) ? options[token.name] : void 0;
303
+ const field = Object.hasOwn(options, token.name) ? options[token.name] : negatedField(token.name, options);
289
304
  if (field === "json") return token.rawName === "--json" ? field : void 0;
290
305
  return field !== void 0 && spells(field, token, word) ? field : void 0;
291
306
  }
@@ -313,7 +328,7 @@ function readOption(options, token, word, seen) {
313
328
  }
314
329
  function optionProblem(field, token, seen) {
315
330
  if (seen) return "given more than once";
316
- if (field.kind === "boolean") return token.inlineValue === true ? "takes no value" : void 0;
331
+ if (field.kind === "boolean") return token.inlineValue === true ? `takes no value; use --${field.flag} or --no-${field.flag}` : void 0;
317
332
  return token.value === void 0 ? "needs a value" : void 0;
318
333
  }
319
334
  function readStdin() {
@@ -363,12 +378,14 @@ function unionBranches(schema) {
363
378
  }));
364
379
  }
365
380
  function wordValue(schema, word) {
366
- const readings = [word, ...unionBranches(schema).flatMap((branch) => {
381
+ const spelled = unionBranches(schema).flatMap((branch) => {
367
382
  const read = branchValue(branch, word);
368
383
  return read === void 0 ? [] : [read.value];
369
- })];
384
+ });
385
+ const readings = [word, ...spelled];
370
386
  const index = readings.findIndex((value) => Check(schema, value));
371
- return index === -1 ? word : readings[index];
387
+ if (index !== -1) return readings[index];
388
+ return spelled.find((value) => typeof value === "number") ?? word;
372
389
  }
373
390
  function fieldValue(field, raw) {
374
391
  if (field.stdin && raw === "-") {
@@ -454,9 +471,9 @@ function detailsJson(details) {
454
471
  return (JSON.stringify(details, (_key, value) => typeof value === "bigint" ? value.toString() : value, 2) ?? "null").replaceAll(JSON_FORGING, (character) => `\\u${(character.codePointAt(0) ?? 0).toString(16).padStart(4, "0")}`);
455
472
  }
456
473
  const JSON_FORGING = /[\u007F-\u009F\u061C\u200E\u200F\u2028\u2029\u202A-\u202E\u2066-\u206F]/g;
457
- const GRAPHEMES = new Intl.Segmenter();
474
+ let graphemes;
458
475
  const WIDE = /^(?:\p{Extended_Pictographic}|[\u1100-\u115F\u231A\u231B\u2329\u232A\u2630-\u2637\u268A-\u268F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DFF\u4E00-\u9FFF\uA000-\uA4CF\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE6F\uFF00-\uFF60\uFFE0-\uFFE6\u{16FE0}-\u{18DFF}\u{1AFF0}-\u{1B2FF}\u{1D15E}-\u{1D164}\u{1D1BB}-\u{1D1C0}\u{1D300}-\u{1D376}\u{1F000}-\u{1FAFF}\u{20000}-\u{3FFFD}])$/u;
459
- const EMOJI = /^\p{RGI_Emoji}$/v;
476
+ let emoji;
460
477
  const ZERO_WIDTH = /^[\p{Mn}\p{Me}]$/u;
461
478
  function pointCells(point) {
462
479
  if (WIDE.test(point)) return 2;
@@ -465,12 +482,14 @@ function pointCells(point) {
465
482
  function graphemeCells(grapheme) {
466
483
  let size = 0;
467
484
  for (const point of grapheme.normalize("NFC")) size += pointCells(point);
468
- return Math.max(EMOJI.test(grapheme) ? 2 : 1, size);
485
+ emoji ??= /^\p{RGI_Emoji}$/v;
486
+ return Math.max(emoji.test(grapheme) ? 2 : 1, size);
469
487
  }
470
488
  function fitLine(text, room) {
471
489
  let fitted = "";
472
490
  let used = 0;
473
- for (const { segment } of GRAPHEMES.segment(text)) {
491
+ graphemes ??= new Intl.Segmenter();
492
+ for (const { segment } of graphemes.segment(text)) {
474
493
  const size = graphemeCells(segment);
475
494
  if (used + size > room) break;
476
495
  fitted += segment;
@@ -510,8 +529,10 @@ function progressLine() {
510
529
  function toolCommand(tool) {
511
530
  const fields = toolFields(tool);
512
531
  const [summary = tool.title] = tool.description.split(/(?<=[.!?])\s/, 1);
532
+ const name = commandName(tool);
513
533
  return {
514
- name: commandName(tool),
534
+ name,
535
+ word: name.slice(name.indexOf(" ") + 1),
515
536
  aliases: (tool.cli?.aliases ?? []).map((alias) => commandWord(tool.name, alias)),
516
537
  summary: tool.cli?.description ?? summary,
517
538
  fields,
@@ -548,13 +569,15 @@ function toolCommand(tool) {
548
569
  function mcpCommand(options) {
549
570
  return {
550
571
  name: "mcp",
572
+ word: "mcp",
551
573
  aliases: [],
552
574
  summary: `Run the ${options.name} MCP server over stdio`,
553
575
  fields: [],
554
576
  json: false,
555
577
  async run() {
556
- const [{ createMcpServer }, { StdioServerTransport }] = await Promise.all([import("./mcp.mjs"), import("@modelcontextprotocol/server/stdio")]);
557
- await createMcpServer(typeof options.mcp === "object" ? options.mcp : options, options.tools).connect(new StdioServerTransport());
578
+ const [{ createMcpServer }, { serveStdio }] = await Promise.all([import("./mcp.mjs"), import("@modelcontextprotocol/server/stdio")]);
579
+ const info = typeof options.mcp === "object" ? options.mcp : options;
580
+ serveStdio(() => createMcpServer(info, options.tools));
558
581
  }
559
582
  };
560
583
  }
@@ -567,19 +590,67 @@ function commandTools(options) {
567
590
  function builtInMcp(options) {
568
591
  return options.mcp !== void 0 && options.mcp !== false && !(options.commands ?? []).some((command) => commandName(command) === "mcp");
569
592
  }
570
- function commandWords(options) {
571
- return [...commandTools(options).flatMap((tool) => [commandName(tool), ...tool.cli?.aliases ?? []]), ...builtInMcp(options) ? ["mcp"] : []];
593
+ function leadWords(options) {
594
+ return [
595
+ ...commandTools(options).flatMap((tool) => {
596
+ const [lead = "", word] = commandName(tool).split(" ");
597
+ return word === void 0 ? [lead, ...tool.cli?.aliases ?? []] : [lead];
598
+ }),
599
+ ...Object.values(options.groups ?? {}).flatMap((group) => group.aliases ?? []),
600
+ ...builtInMcp(options) ? ["mcp"] : []
601
+ ];
602
+ }
603
+ function findEntry(entries, word) {
604
+ return entries.find((entry) => entry.word === word || entry.aliases.includes(word));
605
+ }
606
+ function findCommand(entries, words) {
607
+ const [first, ...rest] = words;
608
+ const entry = first === void 0 ? void 0 : findEntry(entries, first);
609
+ if (entry !== void 0 && "scope" in entry) return findCommand(entry.scope.entries, rest);
610
+ return rest.length === 0 ? entry : void 0;
611
+ }
612
+ function assertUnique(prefix, entries) {
613
+ const words = entries.flatMap((entry) => [entry.word, ...entry.aliases]);
614
+ const repeated = words.find((word, index) => words.indexOf(word) !== index);
615
+ if (repeated !== void 0) throw new ToolDefinitionError(`Two commands are named ${prefix}${repeated}`);
616
+ }
617
+ function commandGroup(options, word, commands) {
618
+ const hints = options.groups?.[word] ?? {};
619
+ assertUnique(`${word} `, commands);
620
+ return {
621
+ word,
622
+ aliases: (hints.aliases ?? []).map((alias) => commandWord(`${options.name} ${word}`, alias)),
623
+ summary: hints.description ?? commands.map((command) => command.word).join(", "),
624
+ scope: {
625
+ words: [word],
626
+ title: `${hints.description ?? `Commands of ${word}`} (${options.name} ${word} v${options.version})`,
627
+ entries: commands
628
+ }
629
+ };
630
+ }
631
+ function rootEntries(options, commands) {
632
+ const entries = [...Map.groupBy(commands, (command) => command.name.split(" ", 1)[0] ?? "")].flatMap(([lead, members]) => {
633
+ const grouped = members.filter((command) => command.name !== command.word);
634
+ const single = members.filter((command) => command.name === command.word);
635
+ return grouped.length === 0 ? single : [...single, commandGroup(options, lead, grouped)];
636
+ });
637
+ const unknown = Object.keys(options.groups ?? {}).find((word) => !entries.some((entry) => "scope" in entry && entry.word === word));
638
+ if (unknown !== void 0) throw new ToolDefinitionError(`${options.name}: no group ${unknown}`);
639
+ assertUnique("", entries);
640
+ return entries;
572
641
  }
573
642
  function createCli(options) {
574
643
  indexTools(options.tools);
575
644
  indexTools(options.commands ?? []);
576
645
  const commands = [...commandTools(options).map((tool) => toolCommand(tool)), ...builtInMcp(options) ? [mcpCommand(options)] : []];
577
- const words = commandWords(options);
578
- const repeated = words.find((word, index) => words.indexOf(word) !== index);
579
- if (repeated !== void 0) throw new ToolDefinitionError(`Two commands are named ${repeated}`);
580
- const missing = [options.default, options.fallback].find((name) => name !== void 0 && !words.includes(name));
646
+ const root = {
647
+ words: [],
648
+ title: `${options.description} (${options.name} v${options.version})`,
649
+ entries: rootEntries(options, commands)
650
+ };
651
+ const missing = [options.default, options.fallback].find((name) => name !== void 0 && findCommand(root.entries, name.split(" ")) === void 0);
581
652
  if (missing !== void 0) throw new ToolDefinitionError(`${options.name}: no command ${missing}`);
582
- return { run: (argv) => dispatch(options, commands, normalizeArgv(options, argv)) };
653
+ return { run: (argv) => dispatch(options, root, normalizeArgv(options, argv)) };
583
654
  }
584
655
  const ROOT_FLAGS = /* @__PURE__ */ new Set([
585
656
  "--help",
@@ -589,22 +660,30 @@ const ROOT_FLAGS = /* @__PURE__ */ new Set([
589
660
  ]);
590
661
  function normalizeArgv(options, argv) {
591
662
  const [first] = argv;
592
- if (first === void 0) return options.default === void 0 ? [] : [options.default];
593
- if (options.fallback === void 0 || ROOT_FLAGS.has(first) || commandWords(options).includes(first)) return [...argv];
594
- return [options.fallback, ...argv];
663
+ if (first === void 0) return options.default?.split(" ") ?? [];
664
+ if (options.fallback === void 0 || ROOT_FLAGS.has(first) || leadWords(options).includes(first)) return [...argv];
665
+ return [...options.fallback.split(" "), ...argv];
595
666
  }
596
- async function dispatch(options, commands, argv) {
597
- const [first, ...rest] = argv;
667
+ async function dispatch(options, root, argv) {
668
+ const [first] = argv;
598
669
  if (argv.length === 1 && (first === "--version" || first === "-v")) writeLine("stdout", sanitizeLine(options.version));
599
- else if (first === "--help" || first === "-h") writeLine("stdout", sanitizeText(mainUsage(options, commands)));
600
- else if (first === void 0) {
601
- writeLine("stderr", sanitizeText(mainUsage(options, commands)));
670
+ else await dispatchIn(options, root, argv);
671
+ }
672
+ async function dispatchIn(options, scope, argv) {
673
+ const [first, ...rest] = argv;
674
+ if (first === void 0) {
675
+ writeLine("stderr", sanitizeText(scopeUsage(options, scope)));
602
676
  fail(["No command specified"]);
603
- } else {
604
- const command = commands.find((each) => each.name === first || each.aliases.includes(first));
605
- if (command === void 0) fail([`Unknown command ${JSON.stringify(first)}`, `Run ${options.name} --help for the commands`]);
606
- else await runCommand(options, command, rest);
677
+ return;
607
678
  }
679
+ if (first === "--help" || first === "-h") {
680
+ writeLine("stdout", sanitizeText(scopeUsage(options, scope)));
681
+ return;
682
+ }
683
+ const entry = findEntry(scope.entries, first);
684
+ if (entry === void 0) fail([`Unknown command ${JSON.stringify([...scope.words, first].join(" "))}`, `Run ${scopePath(options, scope)} --help for the commands`]);
685
+ else if ("scope" in entry) await dispatchIn(options, entry.scope, rest);
686
+ else await runCommand(options, entry, rest);
608
687
  }
609
688
  async function runCommand(options, command, rawArgs) {
610
689
  const words = parseWords(rawArgs, command.fields, command.json);
@@ -623,17 +702,21 @@ function table(rows) {
623
702
  const width = Math.max(0, ...rows.map(([left]) => left.length));
624
703
  return rows.map(([left, right]) => ` ${left.padEnd(width)} ${right}`.trimEnd());
625
704
  }
626
- function mainUsage(options, commands) {
705
+ function scopePath(options, scope) {
706
+ return [options.name, ...scope.words].join(" ");
707
+ }
708
+ function scopeUsage(options, scope) {
709
+ const path = scopePath(options, scope);
627
710
  return [
628
- `${options.description} (${options.name} v${options.version})`,
711
+ scope.title,
629
712
  "",
630
- `USAGE ${options.name} <command> [OPTIONS]`,
713
+ `USAGE ${path} <command> [OPTIONS]`,
631
714
  "",
632
715
  "COMMANDS",
633
716
  "",
634
- ...table(commands.map((command) => [[command.name, ...command.aliases].join(", "), command.summary])),
717
+ ...table(scope.entries.map((entry) => [[entry.word, ...entry.aliases].join(", "), entry.summary])),
635
718
  "",
636
- `Use ${options.name} <command> --help for more information about a command.`
719
+ `Use ${path} <command> --help for more information about a command.`
637
720
  ].join("\n");
638
721
  }
639
722
  function commandUsage(options, command) {
@@ -642,7 +725,7 @@ function commandUsage(options, command) {
642
725
  const takesOptions = flags.length > 0 || command.json;
643
726
  const words = positional.map(fieldWord);
644
727
  const rows = [
645
- ...flags.map((field) => [`${field.short === void 0 ? "" : `-${field.short}, `}${optionSpelling(field)}`, fieldDescription(field)]),
728
+ ...flags.map(optionRow),
646
729
  ...command.json ? [["--json", "Print the details as JSON instead of the text"]] : [],
647
730
  ["-h, --help", "Show this help"]
648
731
  ];
package/dist/h3.d.mts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { ToolDefinition as ToolDefinition$1 } from "./_chunks/index.mjs";
2
+ import { McpHost } from "./_chunks/mcp-answers.mjs";
2
3
  import { JsonSchema, ToolDefinition } from "h3-mcp";
3
4
  /** An h3-mcp tool whose `inputSchema` is the plain JSON Schema `tools/list` sends. */
4
5
  export type H3Tool = ToolDefinition<JsonSchema>;
@@ -12,6 +13,8 @@ export type H3Tool = ToolDefinition<JsonSchema>;
12
13
  * instead. An unknown name never reaches a handler: h3-mcp answers it itself
13
14
  * with a JSON-RPC error.
14
15
  *
16
+ * `host` is an {@link McpHost} with the event's request and the call's raw `_meta`.
17
+ *
15
18
  * `ask` reaches a client with `elicitation` on the 2026 revision only: h3-mcp has no 2025 shim.
16
19
  *
17
20
  * Imports only types from h3-mcp, so the adapter loads neither h3-mcp nor the MCP SDK.
@@ -23,4 +26,5 @@ export type H3Tool = ToolDefinition<JsonSchema>;
23
26
  */
24
27
  export declare function toH3Tools(info: {
25
28
  readonly name: string;
26
- }, tools: readonly ToolDefinition$1[]): H3Tool[];
29
+ }, tools: readonly ToolDefinition$1[]): H3Tool[];
30
+ export type { McpHost };
package/dist/h3.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import "./_chunks/src.mjs";
2
- import { callAsking, canAsk, listTools, progressSteps, questionRound } from "./_chunks/mcp-answers.mjs";
2
+ import { callAsking, canAsk, listTools, mcpHost, progressSteps, questionRound } from "./_chunks/mcp-answers.mjs";
3
3
  function toH3Tools(info, tools) {
4
4
  return listTools(tools).map((entry) => ({
5
5
  name: entry.name,
@@ -16,6 +16,10 @@ function toH3Tools(info, tools) {
16
16
  const progress = mcp?.progressToken === void 0 ? void 0 : mcp.progress;
17
17
  const context = {
18
18
  signal: mcp?.signal,
19
+ ...mcpHost({
20
+ request: event.req,
21
+ meta: mcp?.meta
22
+ }),
19
23
  ...progress === void 0 ? {} : { progress: numbered(progress) }
20
24
  };
21
25
  return await callAsking(info, tools, entry.name, args, context, round);