@agntn/tools 0.3.2 → 0.4.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/dist/cli.mjs CHANGED
@@ -53,21 +53,25 @@ function takesText(branch) {
53
53
  if (branch.type === "string" || typeof branch.const === "string") return true;
54
54
  return Array.isArray(branch.enum) && branch.enum.every((value) => typeof value === "string");
55
55
  }
56
- function cliHints(tool) {
57
- const cli = tool.cli ?? {};
56
+ function hintDefaults(cli) {
58
57
  const rest = cli.rest === void 0 ? [] : [cli.rest];
59
- const hints = {
58
+ return {
60
59
  positional: [...cli.positional ?? [], ...rest],
61
60
  plain: cli.plain ?? [],
62
61
  rest,
63
62
  short: cli.short ?? {},
63
+ flags: cli.flags ?? {},
64
64
  stdin: cli.stdin ?? []
65
65
  };
66
+ }
67
+ function cliHints(tool) {
68
+ const hints = hintDefaults(tool.cli ?? {});
66
69
  const properties = tool.input.properties;
67
70
  const named = [
68
71
  ...hints.positional,
69
72
  ...hints.plain,
70
73
  ...Object.keys(hints.short),
74
+ ...Object.keys(hints.flags),
71
75
  ...hints.stdin
72
76
  ];
73
77
  for (const key of named) if (!Object.hasOwn(properties, key)) throw new ToolDefinitionError(`${tool.name}: cli hint names unknown property ${key}`);
@@ -81,9 +85,12 @@ function assertPositionals(tool, hints) {
81
85
  const flag = hints.plain.find((key) => !positional.includes(key));
82
86
  if (flag !== void 0) throw new ToolDefinitionError(`${tool.name}: plain property ${flag} must be positional`);
83
87
  }
88
+ function ownEntry(record, key) {
89
+ return Object.hasOwn(record, key) ? record[key] : void 0;
90
+ }
84
91
  function toolFields(tool) {
85
92
  const properties = tool.input.properties;
86
- const { positional, plain, rest, short, stdin } = cliHints(tool);
93
+ const { positional, plain, rest, short, flags: aliases, stdin } = cliHints(tool);
87
94
  const keys = [...positional, ...Object.keys(properties).filter((key) => !positional.includes(key))];
88
95
  const required = tool.input.required ?? [];
89
96
  const flags = /* @__PURE__ */ new Set();
@@ -98,7 +105,8 @@ function toolFields(tool) {
98
105
  plain: plain.includes(key),
99
106
  rest: rest.includes(key),
100
107
  restItems: rest.includes(key) ? textItems(properties[key] ?? {}) : void 0,
101
- short: Object.hasOwn(short, key) ? short[key] : void 0,
108
+ short: ownEntry(short, key),
109
+ aliases: ownEntry(aliases, key) ?? [],
102
110
  stdin: stdin.includes(key)
103
111
  };
104
112
  assertField(tool, field, !field.positional && flags.has(field.flag));
@@ -110,17 +118,22 @@ function toolFields(tool) {
110
118
  assertRequiredPositionalsFirst(tool, fields);
111
119
  return fields;
112
120
  }
113
- function assertFlag(tool, field) {
114
- if (!FLAG_WORD.test(field.flag)) throw new ToolDefinitionError(`${tool.name}: property ${JSON.stringify(field.key)} gives the flag ${JSON.stringify(field.flag)}, which must match ${FLAG_WORD}`);
115
- if (field.kind === "boolean" && field.flag.startsWith("no-")) throw new ToolDefinitionError(`${tool.name}: boolean property ${field.key} cannot take a flag starting with no-; name the positive and --no-${field.flag.slice(3)} negates it`);
116
- if (RESERVED_FLAGS.has(field.flag)) throw new ToolDefinitionError(`${tool.name}: property ${field.key} takes the reserved flag --${field.flag}`);
121
+ function assertFlag(tool, field, flag) {
122
+ if (!FLAG_WORD.test(flag)) throw new ToolDefinitionError(`${tool.name}: property ${JSON.stringify(field.key)} gives the flag ${JSON.stringify(flag)}, which must match ${FLAG_WORD}`);
123
+ if (field.kind === "boolean" && flag.startsWith("no-")) throw new ToolDefinitionError(`${tool.name}: boolean property ${field.key} cannot take a flag starting with no-; name the positive and --no-${flag.slice(3)} negates it`);
124
+ if (RESERVED_FLAGS.has(flag)) throw new ToolDefinitionError(`${tool.name}: property ${field.key} takes the reserved flag --${flag}`);
117
125
  }
118
126
  function assertField(tool, field, taken) {
119
- if (!field.positional) assertFlag(tool, field);
127
+ if (!field.positional) assertFlag(tool, field, field.flag);
128
+ assertAliases(tool, field);
120
129
  if (taken) throw new ToolDefinitionError(`${tool.name}: two properties take the flag --${field.flag}`);
121
130
  if (field.positional && field.kind === "boolean") throw new ToolDefinitionError(`${tool.name}: boolean property ${field.key} cannot be positional`);
122
131
  assertTextHints(tool, field);
123
132
  }
133
+ function assertAliases(tool, field) {
134
+ if (!Array.isArray(field.aliases)) throw new ToolDefinitionError(`${tool.name}: flags of ${field.key} must be a list of names`);
135
+ for (const alias of field.aliases) assertFlag(tool, field, alias);
136
+ }
124
137
  function assertTextHints(tool, field) {
125
138
  if (field.stdin && field.kind !== "string") throw new ToolDefinitionError(`${tool.name}: stdin property ${field.key} must be a string`);
126
139
  if (field.rest && field.restItems === void 0 && !TEXT_KINDS.has(field.kind)) throw new ToolDefinitionError(`${tool.name}: rest property ${field.key} must be a string or an array of strings`);
@@ -139,20 +152,26 @@ function assertRequiredPositionalsFirst(tool, fields) {
139
152
  }
140
153
  function assertOneOptionPerSpelling(tool, fields) {
141
154
  const owners = /* @__PURE__ */ new Map();
142
- for (const field of fields.filter((each) => !each.positional)) {
143
- const negation = field.kind === "boolean" ? [`--no-${field.flag}`] : [];
144
- const short = field.short === void 0 ? [] : [`-${field.short}`];
145
- for (const spelling of [
146
- `--${field.flag}`,
147
- ...negation,
148
- ...short
149
- ]) {
150
- const owner = owners.get(spelling);
151
- if (owner !== void 0) throw new ToolDefinitionError(`${tool.name}: properties ${owner} and ${field.key} both answer to ${spelling}`);
152
- owners.set(spelling, field.key);
153
- }
155
+ for (const field of fields) for (const spelling of spellings(field)) {
156
+ const owner = owners.get(spelling);
157
+ if (owner === field.key) throw new ToolDefinitionError(`${tool.name}: property ${owner} answers to ${spelling} twice`);
158
+ if (owner !== void 0) throw new ToolDefinitionError(`${tool.name}: properties ${owner} and ${field.key} both answer to ${spelling}`);
159
+ owners.set(spelling, field.key);
154
160
  }
155
161
  }
162
+ function longFlags(field) {
163
+ return [...field.positional ? [] : [field.flag], ...field.aliases];
164
+ }
165
+ function spellings(field) {
166
+ const long = longFlags(field);
167
+ const negation = field.kind === "boolean" ? long.map((flag) => `--no-${flag}`) : [];
168
+ const short = field.short === void 0 ? [] : [`-${field.short}`];
169
+ return [
170
+ ...long.map((flag) => `--${flag}`),
171
+ ...negation,
172
+ ...short
173
+ ];
174
+ }
156
175
  function fieldDescription(field, values = "") {
157
176
  const { schema } = field;
158
177
  return [
@@ -164,7 +183,14 @@ function fieldDescription(field, values = "") {
164
183
  }
165
184
  function valueHint(field) {
166
185
  if (field.kind === "enum") return field.schema.enum.join("|");
167
- return field.kind === "string" ? field.flag : field.kind;
186
+ if (field.kind !== "json") return field.kind === "string" ? field.flag : field.kind;
187
+ const word = wordBranch(field.schema);
188
+ if (word === void 0) return "json";
189
+ return `${valueHint({
190
+ ...field,
191
+ schema: word,
192
+ kind: fieldKind(word)
193
+ })}|json`;
168
194
  }
169
195
  function optionSpelling(field, hint = valueHint(field)) {
170
196
  return field.kind === "boolean" ? `--[no-]${field.flag}` : `--${field.flag}=<${hint}>`;
@@ -180,7 +206,7 @@ function emptyRecord() {
180
206
  return Object.create(null);
181
207
  }
182
208
  function parseWords(rawArgs, fields, takesJson) {
183
- const entries = [...fields.filter((field) => !field.positional).map((field) => [field.flag, field]), ...takesJson ? [["json", "json"]] : []];
209
+ const entries = [...fields.flatMap((field) => longFlags(field).map((flag) => [flag, field])), ...takesJson ? [["json", "json"]] : []];
184
210
  const options = Object.fromEntries(entries);
185
211
  const { args, origins, texts, refused } = takeDashedText(rawArgs, fields, options);
186
212
  const { tokens } = parseArgs({
@@ -197,20 +223,22 @@ function parseWords(rawArgs, fields, takesJson) {
197
223
  const ordered = inLineOrder(tokens, origins, texts);
198
224
  const positionals = ordered.map(([, word]) => word);
199
225
  const values = emptyRecord();
200
- const errors = [...landedInPlain(fields, ordered, texts), ...refused].map((word) => unknownOption(options, word));
226
+ const misread = [];
201
227
  const flags = /* @__PURE__ */ new Set();
202
228
  for (const token of tokens) {
203
229
  if (token.kind !== "option") continue;
204
230
  const read = readOption(options, token, args[token.index] ?? "", Object.keys(values));
205
- if ("error" in read) errors.push(read.error);
231
+ if ("error" in read) misread.push(read.error);
206
232
  else if ("flag" in read) flags.add(read.flag);
207
233
  else values[read.key] = read.value;
208
234
  }
235
+ const open = fields.filter((field) => !Object.hasOwn(values, field.key));
236
+ const errors = [...[...landedInPlain(open, ordered, texts), ...refused].map((word) => unknownOption(options, word)), ...misread];
209
237
  return {
210
- values: Object.assign(values, positionalValues(fields, positionals)),
238
+ values: Object.assign(values, positionalValues(open, positionals)),
211
239
  json: flags.has("json"),
212
240
  help: flags.has("help"),
213
- errors: [...new Set(errors.length > 0 ? errors : extraPositionals(fields, positionals))]
241
+ errors: [...new Set(errors.length > 0 ? errors : extraPositionals(open, positionals))]
214
242
  };
215
243
  }
216
244
  function takeDashedText(rawArgs, fields, options) {
@@ -237,15 +265,19 @@ function scanWords(rawArgs, options) {
237
265
  plain: plain + rawArgs.length - index - 1
238
266
  };
239
267
  const kind = wordKind(word, options);
240
- if (kind === "plain") plain++;
241
- else if (kind === "text") dashed.push(index);
242
- else if (kind === "valued") index++;
268
+ if (kind === "text") dashed.push(index);
269
+ else if (kind === "plain" || fillsPositional(word, options)) plain++;
270
+ if (kind === "valued") index++;
243
271
  }
244
272
  return {
245
273
  dashed,
246
274
  plain
247
275
  };
248
276
  }
277
+ function fillsPositional(word, options) {
278
+ const field = word.startsWith("--") ? longField(word.slice(2), options) : void 0;
279
+ return typeof field === "object" && field.positional;
280
+ }
249
281
  function wordKind(word, options) {
250
282
  if (!word.startsWith("-") || word === "-") return "plain";
251
283
  if (word === "-h") return "option";
@@ -305,12 +337,11 @@ function optionField(options, token, word) {
305
337
  return field !== void 0 && spells(field, token, word) ? field : void 0;
306
338
  }
307
339
  function spells(field, token, word) {
308
- if (token.rawName === `--${field.flag}`) return true;
309
340
  if (field.short !== void 0 && token.rawName === `-${field.short}`) return word === token.rawName;
310
- return field.kind === "boolean" && token.rawName === `--no-${field.flag}`;
341
+ return spellings(field).includes(token.rawName);
311
342
  }
312
343
  function unknownOption(options, word) {
313
- const flags = Object.entries(options).map(([flag, each]) => each === "json" || each.short === void 0 ? `--${flag}` : `--${flag} (-${each.short})`);
344
+ const flags = Object.entries(options).filter(([flag, each]) => each === "json" || !each.positional && flag === each.flag).map(([flag, each]) => each === "json" || each.short === void 0 ? `--${flag}` : `--${flag} (-${each.short})`);
314
345
  const takes = flags.length > 0 ? flags.join(", ") : "no options";
315
346
  return `Invalid arguments: unknown option ${JSON.stringify(word)}; takes ${takes}`;
316
347
  }
@@ -318,17 +349,25 @@ function readOption(options, token, word, seen) {
318
349
  const field = optionField(options, token, word);
319
350
  if (field === void 0) return { error: unknownOption(options, word) };
320
351
  if (field === "json" || field === "help") return token.inlineValue === true ? { error: `Invalid arguments: ${token.rawName} takes no value` } : { flag: field };
352
+ const flag = typedFlag(field, token);
321
353
  const problem = optionProblem(field, token, seen.includes(field.key));
322
- if (problem !== void 0) return { error: `Invalid arguments: --${field.flag} ${problem}` };
323
- const value = field.kind === "boolean" ? token.rawName !== `--no-${field.flag}` : token.value;
354
+ if (problem !== void 0) return { error: `Invalid arguments: --${flag} ${problem}` };
355
+ const value = field.kind === "boolean" ? token.rawName !== `--no-${flag}` : token.value;
324
356
  return {
325
357
  key: field.key,
326
358
  value: value ?? ""
327
359
  };
328
360
  }
361
+ function typedFlag(field, token) {
362
+ const typed = (flag) => token.rawName === `--${flag}` || token.rawName === `--no-${flag}`;
363
+ return field.aliases.find(typed) ?? field.flag;
364
+ }
329
365
  function optionProblem(field, token, seen) {
330
366
  if (seen) return "given more than once";
331
- if (field.kind === "boolean") return token.inlineValue === true ? `takes no value; use --${field.flag} or --no-${field.flag}` : void 0;
367
+ if (field.kind === "boolean") {
368
+ const flag = typedFlag(field, token);
369
+ return token.inlineValue === true ? `takes no value; use --${flag} or --no-${flag}` : void 0;
370
+ }
332
371
  return token.value === void 0 ? "needs a value" : void 0;
333
372
  }
334
373
  function readStdin() {
@@ -387,6 +426,23 @@ function wordValue(schema, word) {
387
426
  if (index !== -1) return readings[index];
388
427
  return spelled.find((value) => typeof value === "number") ?? word;
389
428
  }
429
+ function wordBranch(schema) {
430
+ return unionBranches(schema).find((branch) => fieldKind(branch) !== "json" && branch.type !== "null");
431
+ }
432
+ function jsonValue(schema, word) {
433
+ let parsed;
434
+ try {
435
+ parsed = { value: JSON.parse(word) };
436
+ } catch {
437
+ parsed = void 0;
438
+ }
439
+ if (wordBranch(schema) === void 0) return parsed ?? { error: "must be JSON" };
440
+ if (parsed !== void 0 && (quotedJson(parsed.value) || Check(schema, parsed.value))) return parsed;
441
+ return { value: wordValue(schema, word) };
442
+ }
443
+ function quotedJson(value) {
444
+ return typeof value === "string" || typeof value === "object" && value !== null;
445
+ }
390
446
  function fieldValue(field, raw) {
391
447
  if (field.stdin && raw === "-") {
392
448
  const text = readStdin();
@@ -396,11 +452,7 @@ function fieldValue(field, raw) {
396
452
  if (field.kind === "number") return numberValue(field.schema.type === "integer", raw);
397
453
  if (field.kind === "string") return { value: wordValue(field.schema, raw) };
398
454
  if (field.kind !== "json") return { value: raw };
399
- try {
400
- return { value: JSON.parse(raw) };
401
- } catch {
402
- return { error: "must be JSON" };
403
- }
455
+ return jsonValue(field.schema, raw);
404
456
  }
405
457
  function toolInput(fields, values) {
406
458
  const input = emptyRecord();
@@ -429,6 +481,12 @@ function placeIn(field, inner) {
429
481
  return `/${inner.join("/")} of ${fieldWord(field)}`;
430
482
  }
431
483
  function cliIssueLines(fields, issue) {
484
+ const lines = rebuiltLines(fields, issue);
485
+ if (lines === void 0) return [issue.line];
486
+ if (issue.hint === void 0 || lines.length === 0) return lines;
487
+ return [...lines.slice(0, -1), `${lines.at(-1)}. ${issue.hint}`];
488
+ }
489
+ function rebuiltLines(fields, issue) {
432
490
  const byKey = (key) => fields.find((field) => field.key === key);
433
491
  if (issue.at === "" && issue.missing !== void 0) return issue.missing.map((key) => {
434
492
  const field = byKey(key);
@@ -436,7 +494,7 @@ function cliIssueLines(fields, issue) {
436
494
  });
437
495
  const [, first, ...inner] = issue.at.split("/");
438
496
  const field = first === void 0 ? void 0 : byKey(first.replaceAll("~1", "/").replaceAll("~0", "~"));
439
- if (field === void 0) return [issue.line];
497
+ if (field === void 0) return void 0;
440
498
  return [`Invalid arguments at ${placeIn(field, inner)}: ${issue.problem}`];
441
499
  }
442
500
  function cliLines(fields, refusal) {
@@ -532,6 +590,7 @@ function toolCommand(tool) {
532
590
  const fields = toolFields(tool);
533
591
  const [summary = tool.title] = tool.description.split(/(?<=[.!?])\s/, 1);
534
592
  const name = commandName(tool);
593
+ const print = tool.cli?.verbatim === true ? String : sanitizeText;
535
594
  return {
536
595
  name,
537
596
  word: name.slice(name.indexOf(" ") + 1),
@@ -561,7 +620,7 @@ function toolCommand(tool) {
561
620
  process.exitCode = 1;
562
621
  } else if (words.json) writeLine("stdout", detailsJson(result.details));
563
622
  else if (result.content.length > 0) {
564
- writeLine("stdout", sanitizeText(resultText(result)));
623
+ writeLine("stdout", print(resultText(result)));
565
624
  const images = result.content.filter((block) => block.type === "image").length;
566
625
  if (images > 0) writeLine("stderr", `(${images} image block(s) not printed)`);
567
626
  }
@@ -577,7 +636,7 @@ function mcpCommand(options) {
577
636
  fields: [],
578
637
  json: false,
579
638
  async run() {
580
- const [{ createMcpServer }, { serveStdio }] = await Promise.all([import("./mcp.mjs"), import("@modelcontextprotocol/server/stdio")]);
639
+ const [{ createMcpServer }, { serveStdio }] = await Promise.all([import("./mcp.mjs"), import("./stdio.mjs")]);
581
640
  const info = typeof options.mcp === "object" ? options.mcp : options;
582
641
  serveStdio(() => createMcpServer(info, options.tools));
583
642
  }
package/dist/h3.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import "./_chunks/src.mjs";
2
- import { callAsking, canAsk, listTools, mcpHost, progressSteps, questionRound } from "./_chunks/mcp-answers.mjs";
2
+ import { askForm, 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,
@@ -28,7 +28,11 @@ function toH3Tools(info, tools) {
28
28
  }
29
29
  function roundOf(mcp) {
30
30
  if (mcp?.era !== "modern" || !canAsk(mcp.clientCapabilities)) return void 0;
31
- return questionRound(mcp.inputResponses, mcp.requestState);
31
+ const { inputResponses: responses, requestState: state, clientCapabilities } = mcp;
32
+ return questionRound({
33
+ responses,
34
+ state
35
+ }, askForm(clientCapabilities));
32
36
  }
33
37
  function numbered(send) {
34
38
  return progressSteps(({ progress, total, message }) => send(progress, total, message));
@@ -0,0 +1,79 @@
1
+ import { ToolDefinition, ToolEffect } from "./_chunks/index.mjs";
2
+ /** What `GET /` names the server by. */
3
+ export interface HttpServerInfo {
4
+ /** Server name, also the word in the message for an unknown tool. */
5
+ readonly name: string;
6
+ readonly version: string;
7
+ }
8
+ /** Options for {@link createHttpHandler}. */
9
+ export interface HttpHandlerOptions {
10
+ /** Effects served, `["read"]` by default. */
11
+ readonly effects?: readonly ToolEffect[];
12
+ /** Mount path, such as `/http/memory`. The root by default. */
13
+ readonly base?: string;
14
+ /** Largest body in bytes, 4 MiB by default. A bigger one gets 413. */
15
+ readonly maxRequestBodySize?: number;
16
+ }
17
+ /** What a tool finds in `host` over HTTP. The client wrote it, so it proves nothing. */
18
+ export interface HttpHost {
19
+ readonly http: true;
20
+ /** The request behind the call, headers included. */
21
+ readonly request: Request;
22
+ }
23
+ /** One tool as `GET /` lists it. */
24
+ export interface HttpToolEntry {
25
+ readonly name: string;
26
+ readonly title: string;
27
+ readonly description: string;
28
+ readonly effect: ToolEffect;
29
+ readonly inputSchema: Readonly<Record<string, unknown>>;
30
+ }
31
+ /** What `GET /` answers. */
32
+ export interface HttpListing {
33
+ readonly name: string;
34
+ readonly version: string;
35
+ readonly tools: readonly HttpToolEntry[];
36
+ }
37
+ /** What a tool answered: status 200, or 422 when it set `isError`. */
38
+ export interface HttpAnswer {
39
+ /** The text blocks joined by newlines. */
40
+ readonly text: string;
41
+ readonly details: unknown;
42
+ /** The result's image blocks, present only when it has some. */
43
+ readonly images?: readonly {
44
+ readonly data: string;
45
+ readonly mimeType: string;
46
+ }[];
47
+ }
48
+ /** Why the call never got an answer: bad input, an unknown tool, a throw. */
49
+ export interface HttpRefusal {
50
+ /** One line each, cleaned of anything that forges a line. */
51
+ readonly lines: readonly string[];
52
+ }
53
+ /** One `progress` event of a streamed call. Numbers only when the tool gave them. */
54
+ export interface HttpProgress {
55
+ readonly message: string;
56
+ readonly progress?: number;
57
+ readonly total?: number;
58
+ }
59
+ /** The `result` event ending a stream: the plain body plus its status. */
60
+ export type HttpResult = (HttpAnswer | HttpRefusal) & {
61
+ readonly status: number;
62
+ };
63
+ /** A Fetch handler: `Request` in, `Response` out. */
64
+ export interface HttpHandler {
65
+ readonly fetch: (request: Request) => Promise<Response>;
66
+ }
67
+ /**
68
+ * Serves tools as JSON: `GET /` lists them, `POST /<tool name>` calls one.
69
+ * A call with `Accept: text/event-stream` streams its progress before the answer.
70
+ *
71
+ * @param info - Name and version for the listing.
72
+ * @param tools - Tools to serve.
73
+ * @param options - The served effects and the mount path.
74
+ * @returns {HttpHandler} The handler, with `fetch` bound to it.
75
+ * @throws {ToolDefinitionError} When two tools share a name.
76
+ * @throws {TypeError} When `base` or `effects` is malformed.
77
+ * @throws {RangeError} When `maxRequestBodySize` isn't a positive number.
78
+ */
79
+ export declare function createHttpHandler(info: HttpServerInfo, tools: readonly ToolDefinition[], options?: HttpHandlerOptions): HttpHandler;
package/dist/http.mjs ADDED
@@ -0,0 +1,247 @@
1
+ import { ToolInputError, indexTools, invokeTool, resultText, sanitizeLine, wireSchema } from "./_chunks/src.mjs";
2
+ import { causeLines } from "./_chunks/causes.mjs";
3
+ const MAX_BODY = 4194304;
4
+ const EFFECTS = [
5
+ "read",
6
+ "write",
7
+ "destructive",
8
+ "exec"
9
+ ];
10
+ function createHttpHandler(info, tools, options = {}) {
11
+ indexTools(tools);
12
+ const effects = servedEffects(options.effects);
13
+ const listed = tools.filter((tool) => effects.includes(tool.effect)).map(entryOf);
14
+ const served = {
15
+ info,
16
+ base: basePath(options.base),
17
+ maxBody: bodyLimit(options.maxRequestBodySize),
18
+ effects,
19
+ tools: [...tools],
20
+ listing: {
21
+ name: info.name,
22
+ version: info.version,
23
+ tools: listed
24
+ }
25
+ };
26
+ return { fetch: async (request) => await route(served, request) };
27
+ }
28
+ function servedEffects(effects) {
29
+ if (effects === void 0) return ["read"];
30
+ if (!Array.isArray(effects)) throw new TypeError(`effects must be a list, got ${JSON.stringify(effects)}`);
31
+ const stray = effects.find((effect) => !EFFECTS.includes(effect));
32
+ if (stray !== void 0) throw new TypeError(`effects takes ${EFFECTS.join(", ")}, got ${JSON.stringify(stray)}`);
33
+ return [...effects];
34
+ }
35
+ function basePath(base) {
36
+ if (base === void 0) return "";
37
+ if (!base.startsWith("/")) throw new TypeError(`base must start with "/", got ${JSON.stringify(base)}`);
38
+ return new URL(base, "http://localhost").pathname.replace(/\/+$/, "");
39
+ }
40
+ function bodyLimit(size) {
41
+ if (size === void 0) return MAX_BODY;
42
+ if (typeof size !== "number" || !Number.isFinite(size) || size <= 0) throw new RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(size)}`);
43
+ return size;
44
+ }
45
+ function entryOf(tool) {
46
+ const { name, title, description, effect } = tool;
47
+ return {
48
+ name,
49
+ title,
50
+ description,
51
+ effect,
52
+ inputSchema: wireSchema(tool)
53
+ };
54
+ }
55
+ async function route(served, request) {
56
+ const { pathname } = new URL(request.url);
57
+ const name = toolPath(served.base, pathname);
58
+ if (name === "") return request.method === "GET" ? Response.json(served.listing) : wrongMethod("GET");
59
+ if (name === void 0) return refusal(404, `Nothing at ${pathname}`);
60
+ if (request.method !== "POST") return wrongMethod("POST");
61
+ return await call(served, name, request);
62
+ }
63
+ function toolPath(base, pathname) {
64
+ if (!pathname.startsWith(base)) return void 0;
65
+ const rest = pathname.slice(base.length);
66
+ if (rest === "" || rest === "/") return "";
67
+ const name = rest.slice(1);
68
+ return rest.startsWith("/") && name !== "" && !name.includes("/") ? name : void 0;
69
+ }
70
+ async function call(served, name, request) {
71
+ const tool = served.tools.find((candidate) => candidate.name === name);
72
+ if (tool === void 0) return refusal(404, `Unknown ${served.info.name} tool: ${JSON.stringify(name)}`);
73
+ if (!served.effects.includes(tool.effect)) {
74
+ const allowed = served.effects.join(", ") || "nothing";
75
+ return refusal(403, `${tool.name} is a ${tool.effect} tool, and this handler serves ${allowed}`);
76
+ }
77
+ if (!isJson(request.headers.get("content-type"))) return refusal(415, "Send the input as Content-Type: application/json");
78
+ const input = await readInput(request, served.maxBody);
79
+ if (!input.ok) return refusal(input.status, input.line);
80
+ if (wantsStream(request.headers.get("accept"))) return streamed(tool, input.value, request);
81
+ const host = {
82
+ http: true,
83
+ request
84
+ };
85
+ const { status, body } = encoded(tool, await settle(tool, input.value, {
86
+ signal: request.signal,
87
+ host
88
+ }), false);
89
+ return new Response(body, {
90
+ status,
91
+ headers: { "content-type": "application/json" }
92
+ });
93
+ }
94
+ function wantsStream(accept) {
95
+ return (accept ?? "").split(",").some((range) => {
96
+ const [type, ...params] = range.split(";").map((part) => part.trim().toLowerCase());
97
+ return type === "text/event-stream" && !params.some((param) => /^q=0(?:\.0*)?$/u.test(param));
98
+ });
99
+ }
100
+ async function settle(tool, input, context) {
101
+ try {
102
+ const result = await invokeTool(tool, input, context);
103
+ return {
104
+ status: result.isError === true ? 422 : 200,
105
+ body: answerOf(result)
106
+ };
107
+ } catch (error) {
108
+ return failure(tool, error);
109
+ }
110
+ }
111
+ function failure(tool, error) {
112
+ if (error instanceof ToolInputError) return refused(400, ...error.lines);
113
+ const message = error instanceof Error ? error.message : String(error);
114
+ return refused(500, `${tool.name} failed: ${message}`, ...causeLines(error));
115
+ }
116
+ function encoded(tool, settled, withStatus) {
117
+ const text = (ending) => JSON.stringify(withStatus ? {
118
+ status: ending.status,
119
+ ...ending.body
120
+ } : ending.body);
121
+ try {
122
+ return {
123
+ status: settled.status,
124
+ body: text(settled)
125
+ };
126
+ } catch (error) {
127
+ const fallback = failure(tool, error);
128
+ return {
129
+ status: fallback.status,
130
+ body: text(fallback)
131
+ };
132
+ }
133
+ }
134
+ function streamed(tool, input, request) {
135
+ const left = new AbortController();
136
+ const signal = AbortSignal.any([request.signal, left.signal]);
137
+ const host = {
138
+ http: true,
139
+ request
140
+ };
141
+ const encoder = new TextEncoder();
142
+ const body = new ReadableStream({
143
+ start(controller) {
144
+ const send = (event, data) => {
145
+ controller.enqueue(encoder.encode(`event: ${event}\ndata: ${data}\n\n`));
146
+ };
147
+ const progress = (message, amount) => {
148
+ send("progress", JSON.stringify(progressOf(message, amount)));
149
+ };
150
+ settle(tool, input, {
151
+ signal,
152
+ host,
153
+ progress
154
+ }).then((settled) => {
155
+ try {
156
+ send("result", encoded(tool, settled, true).body);
157
+ controller.close();
158
+ } catch {}
159
+ });
160
+ },
161
+ cancel(reason) {
162
+ left.abort(reason);
163
+ }
164
+ });
165
+ return new Response(body, { headers: {
166
+ "content-type": "text/event-stream",
167
+ "cache-control": "no-cache"
168
+ } });
169
+ }
170
+ function progressOf(message, amount) {
171
+ const progress = amount?.progress;
172
+ const total = amount?.total;
173
+ return {
174
+ message,
175
+ ...Number.isFinite(progress) ? { progress } : {},
176
+ ...Number.isFinite(total) ? { total } : {}
177
+ };
178
+ }
179
+ function isJson(type) {
180
+ return type?.split(";", 1)[0]?.trim().toLowerCase() === "application/json";
181
+ }
182
+ async function readInput(request, limit) {
183
+ try {
184
+ const body = await readBody(request, limit);
185
+ if (body === void 0) return {
186
+ ok: false,
187
+ status: 413,
188
+ line: `Body is over ${limit} bytes`
189
+ };
190
+ return {
191
+ ok: true,
192
+ value: body.trim() === "" ? {} : JSON.parse(body)
193
+ };
194
+ } catch (error) {
195
+ return {
196
+ ok: false,
197
+ status: 400,
198
+ line: `Body is not JSON: ${error instanceof Error ? error.message : String(error)}`
199
+ };
200
+ }
201
+ }
202
+ async function readBody(request, limit) {
203
+ if (Number(request.headers.get("content-length")) > limit) return void 0;
204
+ const reader = request.body?.getReader();
205
+ if (reader === void 0) return "";
206
+ const decoder = new TextDecoder();
207
+ let text = "";
208
+ let size = 0;
209
+ for (let read = await reader.read(); !read.done; read = await reader.read()) {
210
+ size += read.value.byteLength;
211
+ if (size > limit) {
212
+ reader.cancel().catch(() => void 0);
213
+ return;
214
+ }
215
+ text += decoder.decode(read.value, { stream: true });
216
+ }
217
+ return text + decoder.decode();
218
+ }
219
+ function answerOf(result) {
220
+ const images = result.content.flatMap((block) => block.type === "image" ? [{
221
+ data: block.data,
222
+ mimeType: block.mimeType
223
+ }] : []);
224
+ return {
225
+ text: resultText(result),
226
+ details: result.details ?? null,
227
+ ...images.length > 0 ? { images } : {}
228
+ };
229
+ }
230
+ function refused(status, ...lines) {
231
+ return {
232
+ status,
233
+ body: { lines: lines.map(sanitizeLine) }
234
+ };
235
+ }
236
+ function refusal(status, ...lines) {
237
+ const { body } = refused(status, ...lines);
238
+ return Response.json(body, { status });
239
+ }
240
+ function wrongMethod(allow) {
241
+ const body = { lines: [`Use ${allow} here`] };
242
+ return Response.json(body, {
243
+ status: 405,
244
+ headers: { allow }
245
+ });
246
+ }
247
+ export { createHttpHandler };