@agntn/tools 0.2.0 → 0.2.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.
package/dist/cli.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.mjs","names":["Value.Convert"],"sources":["../src/cli.ts"],"sourcesContent":["/**\n * CLI adapter: one command per {@link ToolDefinition}, plus the package's own\n * commands and an optional stdio MCP server, with no CLI library underneath.\n *\n * A tool's properties become flags, its {@link ToolCliHints} pick positional\n * arguments and stdin, and every call goes through {@link invokeTool}, so the\n * command line validates and fails like every other surface. A package\n * command is a tool definition too, one that only the CLI gets.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { parseArgs } from \"node:util\";\n\nimport { Value } from \"typebox/value\";\n\nimport { sanitizeText } from \"./escapes.ts\";\nimport {\n indexTools,\n invokeTool,\n resultText,\n sanitizeLine,\n ToolDefinitionError,\n ToolInputError,\n type ToolDefinition,\n} from \"./index.ts\";\n\nexport interface CliOptions {\n /** Executable name, also the MCP server name. */\n readonly name: string;\n readonly version: string;\n readonly description: string;\n readonly tools: readonly ToolDefinition[];\n /**\n * The package's own commands, as tool definitions that only the CLI gets:\n * no MCP, Pi, OMP or AI SDK host sees them. One whose command name matches\n * a generated command, `mcp` included, takes its place. A command that\n * needs bytes, not text, reads `-` from stdin itself in `execute`.\n */\n readonly commands?: readonly ToolDefinition[];\n /** Command for an empty command line. */\n readonly default?: string;\n /** Command for a first word that names no command: `hashes sha256 x` runs `hashes hash sha256 x`. */\n readonly fallback?: string;\n /** Adds `mcp`, the tools as an MCP server over stdio. */\n readonly mcp?: boolean;\n /**\n * Errors the package throws on purpose. They print as one line with exit\n * code 1; any other error keeps its stack trace.\n */\n readonly expected?: (error: unknown) => boolean;\n}\n\n/** A flag `--<flag>` can spell: not empty, no `=`, no space or control, not starting with `-`. */\nconst FLAG_WORD = /^[a-z0-9][a-z0-9.-]*$/;\n\n/** Flags every tool command answers itself. */\nconst RESERVED_FLAGS = new Set([\"help\", \"version\", \"json\"]);\n\ntype FieldKind = \"string\" | \"number\" | \"boolean\" | \"enum\" | \"json\";\n\ninterface Field {\n readonly key: string;\n readonly schema: SchemaNode;\n readonly required: boolean;\n readonly flag: string;\n readonly kind: FieldKind;\n readonly positional: boolean;\n readonly stdin: boolean;\n}\n\ntype SchemaNode = Readonly<Record<string, unknown>>;\n\nconst TYPE_KINDS = new Map<unknown, FieldKind>([\n [\"boolean\", \"boolean\"],\n [\"integer\", \"number\"],\n [\"number\", \"number\"],\n [\"object\", \"json\"],\n [\"array\", \"json\"],\n]);\n\n/**\n * @param key - Property name, `camelCase` or `snake_case`.\n * @returns {string} The flag, in kebab case.\n */\nfunction flagName(key: string): string {\n return key\n .replaceAll(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replaceAll(\"_\", \"-\")\n .toLowerCase();\n}\n\n/**\n * @param tool - Tool to name.\n * @returns {string} The hinted command, or the tool name without its package prefix, in kebab case.\n */\nexport function commandName(tool: ToolDefinition): string {\n if (tool.cli?.command !== undefined) return commandWord(tool.name, tool.cli.command);\n const separator = tool.name.indexOf(\"_\");\n const derived = separator === -1 ? tool.name : tool.name.slice(separator + 1);\n // `pkg__h` would derive `-h` and `pkg_` nothing; neither can be dispatched.\n return commandWord(tool.name, derived.replaceAll(\"_\", \"-\"));\n}\n\n/** A command word the CLI can dispatch to: not empty, not an option, nothing that forges a line. */\nconst COMMAND_WORD = /^[a-z0-9_][a-z0-9_.:-]*$/i;\n\n/**\n * @param owner - Tool or CLI the name belongs to, for the error.\n * @param word - Command name or alias.\n * @returns {string} The word, checked.\n * @throws {ToolDefinitionError} When no command line could reach it.\n */\nfunction commandWord(owner: string, word: string): string {\n if (!COMMAND_WORD.test(word)) {\n throw new ToolDefinitionError(\n `${owner}: command ${JSON.stringify(word)} must match ${COMMAND_WORD}`,\n );\n }\n return word;\n}\n\n/**\n * How a value for this property is read from one command line word.\n *\n * @param schema - Property schema.\n * @returns {FieldKind} The reading.\n */\nfunction fieldKind(schema: SchemaNode): FieldKind {\n if (Array.isArray(schema.enum) && schema.enum.every((value) => typeof value === \"string\")) {\n return \"enum\";\n }\n const branches = Array.isArray(schema.anyOf) ? (schema.anyOf as readonly SchemaNode[]) : [];\n if (branches.some((branch) => fieldKind(branch) === \"json\")) return \"json\";\n return TYPE_KINDS.get(schema.type) ?? \"string\";\n}\n\n/**\n * Reads a tool's schema and hints into command line fields.\n *\n * @param tool - Tool to read.\n * @returns {Field[]} One field per property, positional ones in hint order first.\n * @throws {ToolDefinitionError} When a hint names a property the tool lacks, or two properties share a flag.\n */\nfunction toolFields(tool: ToolDefinition): Field[] {\n const properties = tool.input.properties as Readonly<Record<string, SchemaNode>>;\n const positional = tool.cli?.positional ?? [];\n const stdin = tool.cli?.stdin ?? [];\n for (const key of [...positional, ...stdin]) {\n if (!Object.hasOwn(properties, key)) {\n throw new ToolDefinitionError(`${tool.name}: cli hint names unknown property ${key}`);\n }\n }\n const repeated = positional.find((key, index) => positional.indexOf(key) !== index);\n if (repeated !== undefined) {\n throw new ToolDefinitionError(`${tool.name}: cli hint lists positional ${repeated} twice`);\n }\n\n const keys = [\n ...positional,\n ...Object.keys(properties).filter((key) => !positional.includes(key)),\n ];\n const required = (tool.input.required as readonly string[] | undefined) ?? [];\n const flags = new Set<string>();\n const fields = keys.map((key): Field => {\n const field: Field = {\n key,\n schema: properties[key] ?? {},\n required: required.includes(key),\n flag: flagName(key),\n kind: fieldKind(properties[key] ?? {}),\n positional: positional.includes(key),\n stdin: stdin.includes(key),\n };\n assertField(tool, field, !field.positional && flags.has(field.flag));\n if (!field.positional) flags.add(field.flag);\n return field;\n });\n assertOneOptionPerSpelling(tool, fields);\n assertRequiredPositionalsFirst(tool, fields);\n return fields;\n}\n\n/**\n * @param tool - Tool the field belongs to.\n * @param field - Field to check.\n * @throws {ToolDefinitionError} When no word can spell the flag, or it is reserved or reads as a negation.\n */\nfunction assertFlag(tool: ToolDefinition, field: Field): void {\n if (!FLAG_WORD.test(field.flag)) {\n throw new ToolDefinitionError(\n `${tool.name}: property ${JSON.stringify(field.key)} gives the flag ${JSON.stringify(field.flag)}, which must match ${FLAG_WORD}`,\n );\n }\n if (field.kind === \"boolean\" && field.flag.startsWith(\"no-\")) {\n // `util.parseArgs` reads `--no-cache` as `cache` negated, never as a flag `no-cache`.\n throw new ToolDefinitionError(\n `${tool.name}: boolean property ${field.key} cannot take a flag starting with no-; name the positive and --no-${field.flag.slice(3)} negates it`,\n );\n }\n if (RESERVED_FLAGS.has(field.flag)) {\n throw new ToolDefinitionError(\n `${tool.name}: property ${field.key} takes the reserved flag --${field.flag}`,\n );\n }\n}\n\n/**\n * @param tool - Tool the field belongs to.\n * @param field - Field to check.\n * @param taken - Whether an option before it has the same flag.\n * @throws {ToolDefinitionError} When no word can spell the flag, it is reserved or taken, or a hint does not fit the field.\n */\nfunction assertField(tool: ToolDefinition, field: Field, taken: boolean): void {\n // A positional is never an option: its key needs no flag spelling.\n if (!field.positional) assertFlag(tool, field);\n if (taken) {\n throw new ToolDefinitionError(`${tool.name}: two properties take the flag --${field.flag}`);\n }\n if (field.positional && field.kind === \"boolean\") {\n throw new ToolDefinitionError(\n `${tool.name}: boolean property ${field.key} cannot be positional`,\n );\n }\n if (field.stdin && field.kind !== \"string\") {\n throw new ToolDefinitionError(`${tool.name}: stdin property ${field.key} must be a string`);\n }\n}\n\n/**\n * Words fill the positionals in order, so an optional one before a required\n * one would take the only word given and leave the required one empty.\n *\n * @param tool - Tool the fields belong to.\n * @param fields - The tool's fields.\n * @throws {ToolDefinitionError} When an optional positional comes before a required one.\n */\nfunction assertRequiredPositionalsFirst(tool: ToolDefinition, fields: readonly Field[]): void {\n const positional = fields.filter((field) => field.positional);\n const optional = positional.findIndex((field) => !field.required);\n const late = positional\n .slice(optional === -1 ? positional.length : optional)\n .find((field) => field.required);\n if (late !== undefined) {\n throw new ToolDefinitionError(\n `${tool.name}: required positional ${late.key} comes after an optional one`,\n );\n }\n}\n\n/**\n * Every spelling the CLI reads for an option names one property: a boolean also\n * answers to `--no-<flag>`, so a boolean `cache` and a property `noCache`\n * would both claim `--no-cache`.\n *\n * @param tool - Tool the fields belong to.\n * @param fields - The tool's fields.\n * @throws {ToolDefinitionError} When two options share a spelling.\n */\nfunction assertOneOptionPerSpelling(tool: ToolDefinition, fields: readonly Field[]): void {\n const owners = new Map<string, string>();\n for (const field of fields.filter((each) => !each.positional)) {\n const negation = field.kind === \"boolean\" ? [`no-${field.flag}`] : [];\n for (const spelling of [field.flag, ...negation]) {\n const owner = owners.get(spelling);\n if (owner !== undefined) {\n throw new ToolDefinitionError(\n `${tool.name}: properties ${owner} and ${field.key} both answer to --${spelling}`,\n );\n }\n owners.set(spelling, field.key);\n }\n }\n}\n\n/**\n * @param field - Field to describe.\n * @returns {string} Its line in the usage text, after the flag.\n */\nfunction fieldDescription(field: Field): string {\n const { schema } = field;\n return [\n typeof schema.description === \"string\" ? schema.description : \"\",\n field.stdin ? \"(- reads stdin)\" : \"\",\n field.required ? \"(required)\" : \"\",\n ]\n .filter((part) => part !== \"\")\n .join(\" \");\n}\n\n/**\n * @param field - Option field.\n * @returns {string} What the value looks like in the usage text.\n */\nfunction valueHint(field: Field): string {\n if (field.kind === \"enum\") return (field.schema.enum as string[]).join(\"|\");\n return field.kind === \"string\" ? field.flag : field.kind;\n}\n\n/**\n * A record without a prototype: a property named `toString` reads as unset\n * instead of `Object.prototype.toString`, and `__proto__` is a plain key.\n *\n * @returns {Record<string, T>} An empty record.\n */\nfunction emptyRecord<T>(): Record<string, T> {\n return Object.create(null) as Record<string, T>;\n}\n\ninterface ParsedWords {\n /** Raw values by property: a string, or `true`/`false` for a boolean. */\n readonly values: Readonly<Record<string, string | boolean>>;\n readonly json: boolean;\n /** `--help` or `-h` before any `--`; a value or a word after `--` is not one. */\n readonly help: boolean;\n readonly errors: readonly string[];\n}\n\n/**\n * Reads the words after the command name, on `util.parseArgs` tokens. Only\n * `--flag`, `--flag=value` and, for a boolean, `--no-flag` are options;\n * an unknown option, a single dash before a name, a missing value, a value\n * given twice or a positional too many is a failure, never a skipped word.\n *\n * @param rawArgs - Words after the command name.\n * @param fields - The command's fields.\n * @param takesJson - Whether the command takes `--json`.\n * @returns {ParsedWords} Values by property and the failures, one per line.\n */\nfunction parseWords(\n rawArgs: readonly string[],\n fields: readonly Field[],\n takesJson: boolean,\n): ParsedWords {\n const entries: Array<[string, Field | \"json\"]> = [\n ...fields\n .filter((field) => !field.positional)\n .map((field): [string, Field] => [field.flag, field]),\n ...(takesJson ? [[\"json\", \"json\"] as [string, \"json\"]] : []),\n ];\n const options: Readonly<Record<string, Field | \"json\">> = Object.fromEntries(entries);\n const { tokens } = parseArgs({\n args: [...rawArgs],\n options: Object.fromEntries(\n Object.entries(options).map(([flag, field]) => [\n flag,\n { type: field === \"json\" || field.kind === \"boolean\" ? \"boolean\" : \"string\" },\n ]),\n ) as Record<string, { type: \"boolean\" | \"string\" }>,\n strict: false,\n allowPositionals: true,\n allowNegative: true,\n tokens: true,\n });\n\n const values = emptyRecord<string | boolean>();\n const errors: string[] = [];\n const positionals: string[] = [];\n const flags = new Set<string>();\n for (const token of tokens) {\n if (token.kind === \"positional\") positionals.push(token.value);\n if (token.kind !== \"option\") continue;\n const read = readOption(options, token, rawArgs[token.index] ?? \"\", Object.keys(values));\n if (\"error\" in read) errors.push(read.error);\n else if (\"flag\" in read) flags.add(read.flag);\n else values[read.key] = read.value;\n }\n return {\n values: Object.assign(values, positionalValues(fields, positionals)),\n json: flags.has(\"json\"),\n help: flags.has(\"help\"),\n errors: [...new Set(errors.length > 0 ? errors : extraPositionals(fields, positionals))],\n };\n}\n\n/**\n * @param fields - The command's fields.\n * @param positionals - Positional words in order.\n * @returns {Record<string, string>} Each positional property with its word.\n */\nfunction positionalValues(\n fields: readonly Field[],\n positionals: readonly string[],\n): Record<string, string> {\n const takes = fields.filter((field) => field.positional);\n return Object.assign(\n emptyRecord<string>(),\n Object.fromEntries(\n takes.flatMap((field, index) => {\n const value = positionals[index];\n return value === undefined ? [] : [[field.key, value]];\n }),\n ),\n );\n}\n\n/**\n * @param fields - The command's fields.\n * @param positionals - Positional words in order.\n * @returns {string[]} The failure when there are more words than positional properties.\n */\nfunction extraPositionals(fields: readonly Field[], positionals: readonly string[]): string[] {\n const extra = positionals.length - fields.filter((field) => field.positional).length;\n if (extra <= 0) return [];\n return [`Invalid arguments: ${extra} unexpected positional argument${extra === 1 ? \"\" : \"s\"}`];\n}\n\ninterface OptionToken {\n readonly name: string;\n readonly rawName: string;\n readonly value?: string | undefined;\n readonly inlineValue?: boolean | undefined;\n}\n\ntype OptionRead =\n | { readonly error: string }\n | { readonly flag: \"json\" | \"help\" }\n | { readonly key: string; readonly value: string | boolean };\n\n/**\n * `-xh` expands to `-x` and `-h`; only the whole word `-h` asks for help.\n *\n * @param token - The token `util.parseArgs` made.\n * @param word - The command line word it came from.\n * @returns {boolean} Whether the token is `--help` or the word `-h`.\n */\nfunction asksHelp(token: OptionToken, word: string): boolean {\n return token.rawName === \"--help\" || word === \"-h\";\n}\n\n/**\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @param token - The token `util.parseArgs` made.\n * @param word - The command line word it came from.\n * @returns {Field | \"json\" | \"help\" | undefined} What the token names under a spelling it takes.\n */\nfunction optionField(\n options: Readonly<Record<string, Field | \"json\">>,\n token: OptionToken,\n word: string,\n): Field | \"json\" | \"help\" | undefined {\n if (asksHelp(token, word)) return \"help\";\n const field = Object.hasOwn(options, token.name) ? options[token.name] : undefined;\n if (field === \"json\") return token.rawName === \"--json\" ? field : undefined;\n if (field === undefined || token.rawName === `--${token.name}`) return field;\n return token.rawName === `--no-${token.name}` && field.kind === \"boolean\" ? field : undefined;\n}\n\n/**\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @param token - The token `util.parseArgs` made.\n * @param word - The command line word it came from.\n * @param seen - Properties set by earlier words.\n * @returns {OptionRead} The value it sets, `--json`, or the failure.\n */\nfunction readOption(\n options: Readonly<Record<string, Field | \"json\">>,\n token: OptionToken,\n word: string,\n seen: readonly string[],\n): OptionRead {\n const field = optionField(options, token, word);\n if (field === undefined) {\n const flags = Object.keys(options).map((flag) => `--${flag}`);\n const takes = flags.length > 0 ? flags.join(\", \") : \"no options\";\n return { error: `Invalid arguments: unknown option ${JSON.stringify(word)}; takes ${takes}` };\n }\n if (field === \"json\" || field === \"help\") {\n return token.inlineValue === true\n ? { error: `Invalid arguments: ${token.rawName} takes no value` }\n : { flag: field };\n }\n const problem = optionProblem(field, token, seen.includes(field.key));\n if (problem !== undefined) return { error: `Invalid arguments: --${field.flag} ${problem}` };\n const value = field.kind === \"boolean\" ? token.rawName === `--${field.flag}` : token.value;\n return { key: field.key, value: value ?? \"\" };\n}\n\n/**\n * @param field - The option's field.\n * @param token - Its token.\n * @param seen - Whether an earlier word set the property already.\n * @returns {string | undefined} What is wrong with the option, if anything.\n */\nfunction optionProblem(field: Field, token: OptionToken, seen: boolean): string | undefined {\n if (seen) return \"given more than once\";\n if (field.kind === \"boolean\") return token.inlineValue === true ? \"takes no value\" : undefined;\n return token.value === undefined ? \"needs a value\" : undefined;\n}\n\n/**\n * Reads stdin as strict UTF-8. A lenient decode would turn each invalid byte\n * into U+FFFD, and a tool hashing or encoding the text would answer for other\n * input without a word; binary data needs a command of the package's own.\n *\n * @returns {string | undefined} The text, or nothing when stdin is not UTF-8.\n */\nfunction readStdin(): string | undefined {\n try {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(readFileSync(0));\n } catch (error) {\n if (error instanceof TypeError) return undefined;\n throw error;\n }\n}\n\n/**\n * @param field - Field the word belongs to.\n * @param raw - What {@link parseWords} read for it.\n * @returns {{ value: unknown } | { error: string }} The value before TypeBox conversion, or why there is none.\n */\nfunction fieldValue(field: Field, raw: unknown): { value: unknown } | { error: string } {\n if (field.stdin && raw === \"-\") {\n const text = readStdin();\n return text === undefined ? { error: \"stdin is not UTF-8 text\" } : { value: text };\n }\n if (field.kind !== \"json\" || typeof raw !== \"string\") return { value: raw };\n try {\n return { value: JSON.parse(raw) as unknown };\n } catch {\n return { error: \"must be JSON\" };\n }\n}\n\n/**\n * Builds the tool input from parsed arguments. Numbers and booleans in the\n * schema are converted from their text by TypeBox; objects and arrays are\n * JSON. The result still goes through {@link invokeTool} validation.\n *\n * @param tool - Tool to call.\n * @param fields - The command's fields.\n * @param values - Raw values by property, from {@link parseWords}.\n * @returns {unknown} The input object.\n * @throws {ToolInputError} When a JSON value does not parse.\n */\nfunction toolInput(\n tool: ToolDefinition,\n fields: readonly Field[],\n values: Readonly<Record<string, string | boolean>>,\n): unknown {\n const input = emptyRecord<unknown>();\n const fromStdin = fields.filter((field) => field.stdin && values[field.key] === \"-\");\n if (fromStdin.length > 1) {\n throw new ToolInputError([\n `Invalid arguments: stdin can feed one argument, not ${fromStdin.map((field) => field.key).join(\" and \")}`,\n ]);\n }\n const errors: string[] = [];\n for (const field of fields) {\n const raw = values[field.key];\n if (raw === undefined) continue;\n const read = fieldValue(field, raw);\n if (\"error\" in read) errors.push(`Invalid arguments at /${field.key}: ${read.error}`);\n else input[field.key] = read.value;\n }\n if (errors.length > 0) throw new ToolInputError(errors);\n return Value.Convert(tool.input, input);\n}\n\n/**\n * @param stream - Where to write.\n * @param text - Text, given a trailing newline when it lacks one.\n */\nfunction writeLine(stream: \"stdout\" | \"stderr\", text: string): void {\n process[stream].write(text.endsWith(\"\\n\") ? text : `${text}\\n`);\n}\n\n/**\n * Prints an error the CLI expects and sets exit code 1.\n *\n * @param lines - Failure lines.\n */\nfunction fail(lines: readonly string[]): void {\n writeLine(\"stderr\", lines.map(sanitizeLine).join(\"\\n\"));\n process.exitCode = 1;\n}\n\n/**\n * Turns expected errors into {@link fail}; any other error goes on with its stack.\n *\n * @param options - CLI options.\n * @param error - What the command threw.\n */\nfunction handleError(options: CliOptions, error: unknown): void {\n if (error instanceof ToolInputError) fail(error.lines);\n else if (options.expected?.(error) === true) {\n fail([error instanceof Error ? error.message : String(error)]);\n } else throw error;\n}\n\n/**\n * @param details - Tool details.\n * @returns {string} Pretty JSON; a bigint becomes its decimal string, no details `null`.\n */\nfunction detailsJson(details: unknown): string {\n // `JSON.stringify` answers `undefined`, not a string, for undefined details.\n const json =\n (JSON.stringify(\n details,\n (_key, value: unknown) => (typeof value === \"bigint\" ? value.toString() : value),\n 2,\n ) as string | undefined) ?? \"null\";\n return json.replaceAll(\n JSON_FORGING,\n (character) => `\\\\u${(character.codePointAt(0) ?? 0).toString(16).padStart(4, \"0\")}`,\n );\n}\n\n/**\n * What `JSON.stringify` leaves literal although a terminal acts on it: DEL and\n * C1, the bidi marks, overrides and isolates, and the Unicode line and\n * paragraph separators. They only occur inside strings, so a `\\u` escape\n * keeps the parsed details the same.\n */\nconst JSON_FORGING =\n /* oxlint-disable-next-line no-control-regex */\n /[\\u007F-\\u009F\\u061C\\u200E\\u200F\\u2028\\u2029\\u202A-\\u202E\\u2066-\\u206F]/g;\n\n/** One command the CLI dispatches to: a tool, a package command or `mcp`. */\ninterface Command {\n readonly name: string;\n readonly aliases: readonly string[];\n /** Line in the command list. */\n readonly summary: string;\n readonly fields: readonly Field[];\n /** Takes `--json`: a tool command prints its details; `mcp` has none. */\n readonly json: boolean;\n run(words: ParsedWords): Promise<void>;\n}\n\n/**\n * @param tool - Tool or package command to run.\n * @returns {Command} The command calling it.\n */\nfunction toolCommand(tool: ToolDefinition): Command {\n const fields = toolFields(tool);\n const [summary = tool.title] = tool.description.split(/(?<=[.!?])\\s/, 1);\n return {\n name: commandName(tool),\n aliases: (tool.cli?.aliases ?? []).map((alias) => commandWord(tool.name, alias)),\n summary: tool.cli?.description ?? summary,\n fields,\n json: true,\n async run(words) {\n const result = await invokeTool(tool, toolInput(tool, fields, words.values));\n if (result.isError === true) {\n writeLine(\"stderr\", sanitizeText(resultText(result)));\n process.exitCode = 1;\n } else if (words.json) {\n writeLine(\"stdout\", detailsJson(result.details));\n } else {\n writeLine(\"stdout\", sanitizeText(resultText(result)));\n const images = result.content.filter((block) => block.type === \"image\").length;\n if (images > 0) writeLine(\"stderr\", `(${images} image block(s) not printed)`);\n }\n },\n };\n}\n\n/**\n * @param options - CLI options.\n * @returns {Command} The stdio MCP server command.\n */\nfunction mcpCommand(options: CliOptions): Command {\n return {\n name: \"mcp\",\n aliases: [],\n summary: `Run the ${options.name} MCP server over stdio`,\n fields: [],\n json: false,\n async run() {\n const [{ createMcpServer }, { StdioServerTransport }] = await Promise.all([\n import(\"./mcp.ts\"),\n import(\"@modelcontextprotocol/server/stdio\"),\n ]);\n await createMcpServer(options, options.tools).connect(new StdioServerTransport());\n },\n };\n}\n\n/**\n * The definitions behind the commands, in listing order: the tools, each\n * replaced in place by a package command of its command name, then the rest\n * of the package commands.\n *\n * @param options - CLI options.\n * @returns {ToolDefinition[]} One definition per command but `mcp`.\n */\nfunction commandTools(options: CliOptions): ToolDefinition[] {\n const own = options.commands ?? [];\n const byName = new Map(own.map((command) => [commandName(command), command]));\n const listed = options.tools.map((tool) => byName.get(commandName(tool)) ?? tool);\n return [...listed, ...own.filter((command) => !listed.includes(command))];\n}\n\n/**\n * @param options - CLI options.\n * @returns {boolean} Whether the built-in `mcp` command is on and no package command replaces it.\n */\nfunction builtInMcp(options: CliOptions): boolean {\n return (\n options.mcp === true &&\n !(options.commands ?? []).some((command) => commandName(command) === \"mcp\")\n );\n}\n\n/**\n * @param options - CLI options.\n * @returns {string[]} Every command name and alias, `mcp` included when built in.\n */\nfunction commandWords(options: CliOptions): string[] {\n return [\n ...commandTools(options).flatMap((tool) => [commandName(tool), ...(tool.cli?.aliases ?? [])]),\n ...(builtInMcp(options) ? [\"mcp\"] : []),\n ];\n}\n\n/** A built command line interface. */\nexport interface Cli {\n /** Runs one command line: the words after the executable and script. */\n run(argv: readonly string[]): Promise<void>;\n}\n\n/**\n * Builds the commands and checks every definition, so a broken hint fails at\n * startup and not on the first call that reaches it.\n *\n * @param options - CLI options.\n * @returns {Cli} The CLI.\n * @throws {ToolDefinitionError} When two commands share a name or alias, a hint does not fit its schema, or `default` or `fallback` names no command.\n */\nexport function createCli(options: CliOptions): Cli {\n indexTools(options.tools);\n indexTools(options.commands ?? []);\n const commands = [\n ...commandTools(options).map((tool) => toolCommand(tool)),\n ...(builtInMcp(options) ? [mcpCommand(options)] : []),\n ];\n const words = commandWords(options);\n const repeated = words.find((word, index) => words.indexOf(word) !== index);\n if (repeated !== undefined) throw new ToolDefinitionError(`Two commands are named ${repeated}`);\n const missing = [options.default, options.fallback].find(\n (name) => name !== undefined && !words.includes(name),\n );\n if (missing !== undefined)\n throw new ToolDefinitionError(`${options.name}: no command ${missing}`);\n\n return { run: (argv) => dispatch(options, commands, normalizeArgv(options, argv)) };\n}\n\n/**\n * Applies `default` and `fallback`: an empty command line runs `default`, and\n * a first word that names no command goes to `fallback` as its first\n * argument. A leading option such as `--help` stays at the root; a lone `-`\n * is the stdin word of the fallback's positional, not an option.\n *\n * @param options - CLI options.\n * @param argv - Words after the executable and script.\n * @returns {string[]} The words to dispatch.\n */\nexport function normalizeArgv(options: CliOptions, argv: readonly string[]): string[] {\n const [first] = argv;\n if (first === undefined) return options.default === undefined ? [] : [options.default];\n const option = first.startsWith(\"-\") && first !== \"-\";\n if (options.fallback === undefined || option || commandWords(options).includes(first)) {\n return [...argv];\n }\n return [options.fallback, ...argv];\n}\n\n/**\n * Picks the command by its first word and runs it. `--help` and `-h` count\n * only where the parse finds an option: after `--` or as an option's value\n * they are the tool's words. Every error line goes through\n * {@link sanitizeLine}, an unknown word inside `JSON.stringify`.\n *\n * @param options - CLI options.\n * @param commands - The commands.\n * @param argv - Words after {@link normalizeArgv}.\n */\nasync function dispatch(\n options: CliOptions,\n commands: readonly Command[],\n argv: readonly string[],\n): Promise<void> {\n const [first, ...rest] = argv;\n if (argv.length === 1 && (first === \"--version\" || first === \"-v\")) {\n writeLine(\"stdout\", sanitizeLine(options.version));\n } else if (first === \"--help\" || first === \"-h\") {\n writeLine(\"stdout\", sanitizeText(mainUsage(options, commands)));\n } else if (first === undefined) {\n writeLine(\"stderr\", sanitizeText(mainUsage(options, commands)));\n fail([\"No command specified\"]);\n } else {\n const command = commands.find((each) => each.name === first || each.aliases.includes(first));\n if (command === undefined) {\n fail([\n `Unknown command ${JSON.stringify(first)}`,\n `Run ${options.name} --help for the commands`,\n ]);\n } else {\n await runCommand(options, command, rest);\n }\n }\n}\n\n/**\n * @param options - CLI options.\n * @param command - The chosen command.\n * @param rawArgs - Words after the command name.\n */\nasync function runCommand(\n options: CliOptions,\n command: Command,\n rawArgs: readonly string[],\n): Promise<void> {\n const words = parseWords(rawArgs, command.fields, command.json);\n if (words.help) {\n writeLine(\"stdout\", sanitizeText(commandUsage(options, command)));\n return;\n }\n try {\n if (words.errors.length > 0) throw new ToolInputError(words.errors);\n await command.run(words);\n } catch (error) {\n handleError(options, error);\n }\n}\n\n/**\n * @param rows - Left and right column of each row.\n * @returns {string[]} The rows, indented, with the right column aligned.\n */\nfunction table(rows: readonly (readonly [string, string])[]): string[] {\n const width = Math.max(0, ...rows.map(([left]) => left.length));\n return rows.map(([left, right]) => ` ${left.padEnd(width)} ${right}`.trimEnd());\n}\n\n/**\n * @param options - CLI options.\n * @param commands - The commands.\n * @returns {string} The usage text of the CLI.\n */\nfunction mainUsage(options: CliOptions, commands: readonly Command[]): string {\n return [\n `${options.description} (${options.name} v${options.version})`,\n \"\",\n `USAGE ${options.name} <command> [OPTIONS]`,\n \"\",\n \"COMMANDS\",\n \"\",\n ...table(\n commands.map((command) => [[command.name, ...command.aliases].join(\", \"), command.summary]),\n ),\n \"\",\n `Use ${options.name} <command> --help for more information about a command.`,\n ].join(\"\\n\");\n}\n\n/**\n * @param options - CLI options.\n * @param command - The command.\n * @returns {string} Its usage text.\n */\nfunction commandUsage(options: CliOptions, command: Command): string {\n const positional = command.fields.filter((field) => field.positional);\n const flags = command.fields.filter((field) => !field.positional);\n const takesOptions = flags.length > 0 || command.json;\n const words = positional.map((field) => {\n const name = field.flag.toUpperCase();\n return field.required ? `<${name}>` : `[${name}]`;\n });\n const rows = [\n ...flags.map((field): [string, string] => [\n field.kind === \"boolean\" ? `--[no-]${field.flag}` : `--${field.flag}=<${valueHint(field)}>`,\n fieldDescription(field),\n ]),\n ...(command.json\n ? [[\"--json\", \"Print the details as JSON instead of the text\"] as [string, string]]\n : []),\n [\"-h, --help\", \"Show this help\"] as [string, string],\n ];\n return [\n `${command.summary} (${options.name} ${command.name} v${options.version})`,\n \"\",\n `USAGE ${[options.name, command.name, ...(takesOptions ? [\"[OPTIONS]\"] : []), ...words].join(\" \")}`,\n ...(positional.length > 0\n ? [\n \"\",\n \"ARGUMENTS\",\n \"\",\n ...table(positional.map((field) => [field.flag.toUpperCase(), fieldDescription(field)])),\n ]\n : []),\n \"\",\n \"OPTIONS\",\n \"\",\n ...table(rows),\n ].join(\"\\n\");\n}\n\n/**\n * Ends the process once the reader of stdout or stderr is gone, as after\n * `| head -1`. Node ignores SIGPIPE, so without a listener the next write\n * throws `EPIPE` with a stack trace. The exit code stays what the command set.\n *\n * @param error - The error the stream emitted.\n */\nfunction exitOnClosedPipe(error: Readonly<NodeJS.ErrnoException>): void {\n if (error.code !== \"EPIPE\") throw error;\n process.exit();\n}\n\n/**\n * Runs the CLI on `process.argv`. The CLI writes no colors, so nothing\n * depends on the terminal it writes to.\n *\n * @param options - CLI options.\n * @param argv - Words after the executable and script.\n */\nexport async function runCli(\n options: CliOptions,\n argv: readonly string[] = process.argv.slice(2),\n): Promise<void> {\n process.stdout.on(\"error\", exitOnClosedPipe);\n process.stderr.on(\"error\", exitOnClosedPipe);\n await createCli(options).run(argv);\n}\n"],"mappings":";;;;;;;;;;;CAqDA,CAAA,WAAM,SAAY;;CAGlB,CAAA,UAAM,QAAA;CAA0B,CAAA,UAAA,MAAA;CAAQ,CAAA,SAAA,MAAA;AAAW,CAAA;AAgBnD,SAAM,SAAA,KAAA;CACJ,OAAC,IAAA,WAAoB,sBAAA,OAAA,CAAA,CAAA,WAAA,KAAA,GAAA,CAAA,CAAA,YAAA;AACrB;AAE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Y,WAAU,eAAc"}
1
+ {"version":3,"file":"cli.mjs","names":["Value.Check"],"sources":["../src/cli.ts"],"sourcesContent":["/**\n * CLI adapter: one command per {@link ToolDefinition}, plus the package's own\n * commands and an optional stdio MCP server, with no CLI library underneath.\n *\n * A tool's properties become flags, its {@link ToolCliHints} pick positionals,\n * short flags and stdin, and every call goes through {@link invokeTool}, so the\n * command line validates and fails like every other surface. A package\n * command is a tool definition too, one that only the CLI gets.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { parseArgs } from \"node:util\";\n\nimport { Value } from \"typebox/value\";\n\nimport { sanitizeText } from \"./escapes.ts\";\nimport {\n indexTools,\n invokeTool,\n resultText,\n sanitizeLine,\n ToolDefinitionError,\n ToolInputError,\n type ToolDefinition,\n} from \"./index.ts\";\n\nexport interface CliOptions {\n /** Executable name, also the MCP server name. */\n readonly name: string;\n readonly version: string;\n readonly description: string;\n readonly tools: readonly ToolDefinition[];\n /**\n * The package's own commands, as tool definitions that only the CLI gets:\n * no MCP, Pi, OMP or AI SDK host sees them. One whose command name matches\n * a generated command, `mcp` included, takes its place. Bytes are the\n * command's own business: it reads `-` from stdin itself in `execute`, and\n * writes to stdout itself, answering with no content and `cli.json: false`.\n */\n readonly commands?: readonly ToolDefinition[];\n /** Command for an empty command line. */\n readonly default?: string;\n /** Command for a first word that names no command: `hashes sha256 x` runs `hashes hash sha256 x`. */\n readonly fallback?: string;\n /** Adds `mcp`, the tools as an MCP server over stdio. */\n readonly mcp?: boolean;\n /**\n * Errors the package throws on purpose. They print as one line with exit\n * code 1; any other error keeps its stack trace.\n */\n readonly expected?: (error: unknown) => boolean;\n}\n\n/** A flag `--<flag>` can spell: not empty, no `=`, no space or control, not starting with `-`. */\nconst FLAG_WORD = /^[a-z0-9][a-z0-9.-]*$/;\n\n/** Flags every tool command answers itself. */\nconst RESERVED_FLAGS = new Set([\"help\", \"version\", \"json\"]);\n\n/** Kinds whose value is the text itself: `enum` is string values only. */\nconst TEXT_KINDS = new Set<FieldKind>([\"string\", \"enum\"]);\n\n/** A short flag: one letter, so a negative number never reads as one. */\nconst SHORT_FLAG = /^[a-z]$/i;\n\ntype FieldKind = \"string\" | \"number\" | \"boolean\" | \"enum\" | \"json\";\n\ninterface Field {\n readonly key: string;\n readonly schema: SchemaNode;\n readonly required: boolean;\n readonly flag: string;\n readonly kind: FieldKind;\n readonly positional: boolean;\n /** Takes the words the other positionals leave, so it's always the last one. */\n readonly rest: boolean;\n readonly short: string | undefined;\n readonly stdin: boolean;\n}\n\ntype SchemaNode = Readonly<Record<string, unknown>>;\n\nconst TYPE_KINDS = new Map<unknown, FieldKind>([\n [\"boolean\", \"boolean\"],\n [\"integer\", \"number\"],\n [\"number\", \"number\"],\n [\"object\", \"json\"],\n [\"array\", \"json\"],\n]);\n\n/**\n * @param key - Property name, `camelCase` or `snake_case`.\n * @returns {string} The flag, in kebab case.\n */\nfunction flagName(key: string): string {\n return key\n .replaceAll(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replaceAll(\"_\", \"-\")\n .toLowerCase();\n}\n\n/**\n * @param tool - Tool to name.\n * @returns {string} The hinted command, or the tool name without its package prefix, in kebab case.\n */\nexport function commandName(tool: ToolDefinition): string {\n if (tool.cli?.command !== undefined) return commandWord(tool.name, tool.cli.command);\n const separator = tool.name.indexOf(\"_\");\n const derived = separator === -1 ? tool.name : tool.name.slice(separator + 1);\n // `pkg__h` would derive `-h` and `pkg_` nothing; neither can be dispatched.\n return commandWord(tool.name, derived.replaceAll(\"_\", \"-\"));\n}\n\n/** A command word the CLI can dispatch to: not empty, not an option, nothing that forges a line. */\nconst COMMAND_WORD = /^[a-z0-9_][a-z0-9_.:-]*$/i;\n\n/**\n * @param owner - Tool or CLI the name belongs to, for the error.\n * @param word - Command name or alias.\n * @returns {string} The word, checked.\n * @throws {ToolDefinitionError} When no command line could reach it.\n */\nfunction commandWord(owner: string, word: string): string {\n if (!COMMAND_WORD.test(word)) {\n throw new ToolDefinitionError(\n `${owner}: command ${JSON.stringify(word)} must match ${COMMAND_WORD}`,\n );\n }\n return word;\n}\n\n/**\n * How a value for this property is read from one command line word.\n *\n * @param schema - Property schema.\n * @returns {FieldKind} The reading.\n */\nfunction fieldKind(schema: SchemaNode): FieldKind {\n if (Array.isArray(schema.enum) && schema.enum.every((value) => typeof value === \"string\")) {\n return \"enum\";\n }\n const branches = Array.isArray(schema.anyOf) ? (schema.anyOf as readonly SchemaNode[]) : [];\n if (branches.some((branch) => fieldKind(branch) === \"json\")) return \"json\";\n return TYPE_KINDS.get(schema.type) ?? \"string\";\n}\n\ninterface CliHints {\n /** The `positional` hint with `rest` at the end. */\n readonly positional: readonly string[];\n readonly rest: readonly string[];\n readonly short: Readonly<Record<string, string>>;\n readonly stdin: readonly string[];\n}\n\n/**\n * @param tool - Tool to read.\n * @returns {CliHints} Its hints, every key a property of the tool.\n * @throws {ToolDefinitionError} When a hint names a property the tool lacks, or a positional twice.\n */\nfunction cliHints(tool: ToolDefinition): CliHints {\n const cli = tool.cli ?? {};\n const rest = cli.rest === undefined ? [] : [cli.rest];\n const hints = {\n positional: [...(cli.positional ?? []), ...rest],\n rest,\n short: cli.short ?? {},\n stdin: cli.stdin ?? [],\n };\n const properties = tool.input.properties as Readonly<Record<string, unknown>>;\n for (const key of [...hints.positional, ...Object.keys(hints.short), ...hints.stdin]) {\n if (!Object.hasOwn(properties, key)) {\n throw new ToolDefinitionError(`${tool.name}: cli hint names unknown property ${key}`);\n }\n }\n const { positional } = hints;\n const repeated = positional.find((key, index) => positional.indexOf(key) !== index);\n if (repeated !== undefined) {\n throw new ToolDefinitionError(`${tool.name}: cli hint lists positional ${repeated} twice`);\n }\n return hints;\n}\n\n/**\n * Reads a tool's schema and hints into command line fields.\n *\n * @param tool - Tool to read.\n * @returns {Field[]} One field per property, positional ones in hint order first.\n * @throws {ToolDefinitionError} When a hint names a property the tool lacks, or two properties share a flag.\n */\nfunction toolFields(tool: ToolDefinition): Field[] {\n const properties = tool.input.properties as Readonly<Record<string, SchemaNode>>;\n const { positional, rest, short, stdin } = cliHints(tool);\n const keys = [\n ...positional,\n ...Object.keys(properties).filter((key) => !positional.includes(key)),\n ];\n const required = (tool.input.required as readonly string[] | undefined) ?? [];\n const flags = new Set<string>();\n const fields = keys.map((key): Field => {\n const field: Field = {\n key,\n schema: properties[key] ?? {},\n required: required.includes(key),\n flag: flagName(key),\n kind: fieldKind(properties[key] ?? {}),\n positional: positional.includes(key),\n rest: rest.includes(key),\n short: Object.hasOwn(short, key) ? short[key] : undefined,\n stdin: stdin.includes(key),\n };\n assertField(tool, field, !field.positional && flags.has(field.flag));\n assertShort(tool, field);\n if (!field.positional) flags.add(field.flag);\n return field;\n });\n assertOneOptionPerSpelling(tool, fields);\n assertRequiredPositionalsFirst(tool, fields);\n return fields;\n}\n\n/**\n * @param tool - Tool the field belongs to.\n * @param field - Field to check.\n * @throws {ToolDefinitionError} When no word can spell the flag, or it is reserved or reads as a negation.\n */\nfunction assertFlag(tool: ToolDefinition, field: Field): void {\n if (!FLAG_WORD.test(field.flag)) {\n throw new ToolDefinitionError(\n `${tool.name}: property ${JSON.stringify(field.key)} gives the flag ${JSON.stringify(field.flag)}, which must match ${FLAG_WORD}`,\n );\n }\n if (field.kind === \"boolean\" && field.flag.startsWith(\"no-\")) {\n // `util.parseArgs` reads `--no-cache` as `cache` negated, never as a flag `no-cache`.\n throw new ToolDefinitionError(\n `${tool.name}: boolean property ${field.key} cannot take a flag starting with no-; name the positive and --no-${field.flag.slice(3)} negates it`,\n );\n }\n if (RESERVED_FLAGS.has(field.flag)) {\n throw new ToolDefinitionError(\n `${tool.name}: property ${field.key} takes the reserved flag --${field.flag}`,\n );\n }\n}\n\n/**\n * @param tool - Tool the field belongs to.\n * @param field - Field to check.\n * @param taken - Whether an option before it has the same flag.\n * @throws {ToolDefinitionError} When no word can spell the flag, it is reserved or taken, or a hint does not fit the field.\n */\nfunction assertField(tool: ToolDefinition, field: Field, taken: boolean): void {\n // A positional is never an option: its key needs no flag spelling.\n if (!field.positional) assertFlag(tool, field);\n if (taken) {\n throw new ToolDefinitionError(`${tool.name}: two properties take the flag --${field.flag}`);\n }\n if (field.positional && field.kind === \"boolean\") {\n throw new ToolDefinitionError(\n `${tool.name}: boolean property ${field.key} cannot be positional`,\n );\n }\n if (field.stdin && field.kind !== \"string\") {\n throw new ToolDefinitionError(`${tool.name}: stdin property ${field.key} must be a string`);\n }\n if (field.rest && !TEXT_KINDS.has(field.kind)) {\n throw new ToolDefinitionError(`${tool.name}: rest property ${field.key} must be a string`);\n }\n}\n\n/**\n * @param tool - Tool the field belongs to.\n * @param field - Field to check.\n * @throws {ToolDefinitionError} When the short flag is no letter, is `h` or sits on a positional.\n */\nfunction assertShort(tool: ToolDefinition, field: Field): void {\n if (field.short === undefined) return;\n if (field.positional) {\n throw new ToolDefinitionError(\n `${tool.name}: positional property ${field.key} takes no short flag`,\n );\n }\n if (!SHORT_FLAG.test(field.short)) {\n throw new ToolDefinitionError(\n `${tool.name}: short flag ${JSON.stringify(field.short)} of ${field.key} must match ${SHORT_FLAG}`,\n );\n }\n if (field.short === \"h\") {\n throw new ToolDefinitionError(\n `${tool.name}: property ${field.key} takes -h, which asks for help`,\n );\n }\n}\n\n/**\n * Words fill the positionals in order, so an optional one before a required\n * one would take the only word given and leave the required one empty.\n *\n * @param tool - Tool the fields belong to.\n * @param fields - The tool's fields.\n * @throws {ToolDefinitionError} When an optional positional comes before a required one.\n */\nfunction assertRequiredPositionalsFirst(tool: ToolDefinition, fields: readonly Field[]): void {\n const positional = fields.filter((field) => field.positional);\n const optional = positional.findIndex((field) => !field.required);\n const late = positional\n .slice(optional === -1 ? positional.length : optional)\n .find((field) => field.required);\n if (late !== undefined) {\n throw new ToolDefinitionError(\n `${tool.name}: required positional ${late.key} comes after an optional one`,\n );\n }\n}\n\n/**\n * Every spelling the CLI reads for an option names one property: a boolean also\n * answers to `--no-<flag>`, so a boolean `cache` and a property `noCache`\n * would both claim `--no-cache`, and two short flags can land on one letter.\n *\n * @param tool - Tool the fields belong to.\n * @param fields - The tool's fields.\n * @throws {ToolDefinitionError} When two options share a spelling.\n */\nfunction assertOneOptionPerSpelling(tool: ToolDefinition, fields: readonly Field[]): void {\n const owners = new Map<string, string>();\n for (const field of fields.filter((each) => !each.positional)) {\n const negation = field.kind === \"boolean\" ? [`--no-${field.flag}`] : [];\n const short = field.short === undefined ? [] : [`-${field.short}`];\n for (const spelling of [`--${field.flag}`, ...negation, ...short]) {\n const owner = owners.get(spelling);\n if (owner !== undefined) {\n throw new ToolDefinitionError(\n `${tool.name}: properties ${owner} and ${field.key} both answer to ${spelling}`,\n );\n }\n owners.set(spelling, field.key);\n }\n }\n}\n\n/**\n * @param field - Field to describe.\n * @returns {string} Its line in the usage text, after the flag.\n */\nfunction fieldDescription(field: Field): string {\n const { schema } = field;\n return [\n typeof schema.description === \"string\" ? schema.description : \"\",\n field.stdin ? \"(- reads stdin)\" : \"\",\n field.required ? \"(required)\" : \"\",\n ]\n .filter((part) => part !== \"\")\n .join(\" \");\n}\n\n/**\n * @param field - Option field.\n * @returns {string} What the value looks like in the usage text.\n */\nfunction valueHint(field: Field): string {\n if (field.kind === \"enum\") return (field.schema.enum as string[]).join(\"|\");\n return field.kind === \"string\" ? field.flag : field.kind;\n}\n\n/**\n * @param field - Option field.\n * @returns {string} Its long spelling in the usage text.\n */\nfunction optionSpelling(field: Field): string {\n return field.kind === \"boolean\"\n ? `--[no-]${field.flag}`\n : `--${field.flag}=<${valueHint(field)}>`;\n}\n\n/**\n * A record without a prototype: a property named `toString` reads as unset\n * instead of `Object.prototype.toString`, and `__proto__` is a plain key.\n *\n * @returns {Record<string, T>} An empty record.\n */\nfunction emptyRecord<T>(): Record<string, T> {\n return Object.create(null) as Record<string, T>;\n}\n\ninterface ParsedWords {\n /** Raw values by property: a string, or `true`/`false` for a boolean. */\n readonly values: Readonly<Record<string, string | boolean>>;\n readonly json: boolean;\n /** `--help` or `-h` before any `--`; a value or a word after `--` is not one. */\n readonly help: boolean;\n readonly errors: readonly string[];\n}\n\n/**\n * Reads the words after the command name, on `util.parseArgs` tokens. Only\n * `--flag`, `--flag=value`, for a boolean `--no-flag`, and a short flag as\n * a whole word are options. A dashed word that spells none fills a free\n * positional ({@link takeDashedText}); past that, an unknown option, a missing\n * value, a value given twice or a positional too many is a failure, never a\n * skipped word.\n *\n * @param rawArgs - Words after the command name.\n * @param fields - The command's fields.\n * @param takesJson - Whether the command takes `--json`.\n * @returns {ParsedWords} Values by property and the failures, one per line.\n */\nfunction parseWords(\n rawArgs: readonly string[],\n fields: readonly Field[],\n takesJson: boolean,\n): ParsedWords {\n const entries: Array<[string, Field | \"json\"]> = [\n ...fields\n .filter((field) => !field.positional)\n .map((field): [string, Field] => [field.flag, field]),\n ...(takesJson ? [[\"json\", \"json\"] as [string, \"json\"]] : []),\n ];\n const options: Readonly<Record<string, Field | \"json\">> = Object.fromEntries(entries);\n const { args, origins, texts, refused } = takeDashedText(rawArgs, fields, options);\n const { tokens } = parseArgs({\n args,\n options: Object.fromEntries(\n Object.entries(options).map(([flag, field]) => [\n flag,\n field === \"json\"\n ? { type: \"boolean\" }\n : {\n type: field.kind === \"boolean\" ? \"boolean\" : \"string\",\n ...(field.short === undefined ? {} : { short: field.short }),\n },\n ]),\n ) as Record<string, { type: \"boolean\" | \"string\"; short?: string }>,\n strict: false,\n allowPositionals: true,\n allowNegative: true,\n tokens: true,\n });\n\n const values = emptyRecord<string | boolean>();\n const errors = refused.map((word) => unknownOption(options, word));\n const flags = new Set<string>();\n for (const token of tokens) {\n if (token.kind !== \"option\") continue;\n const read = readOption(options, token, args[token.index] ?? \"\", Object.keys(values));\n if (\"error\" in read) errors.push(read.error);\n else if (\"flag\" in read) flags.add(read.flag);\n else values[read.key] = read.value;\n }\n const positionals = inLineOrder(tokens, origins, texts);\n return {\n values: Object.assign(values, positionalValues(fields, positionals)),\n json: flags.has(\"json\"),\n help: flags.has(\"help\"),\n errors: [...new Set(errors.length > 0 ? errors : extraPositionals(fields, positionals))],\n };\n}\n\n/** The line for `util.parseArgs` without the dashed text, and where each word stood. */\ninterface DashedText {\n readonly args: string[];\n /** Index on the original line of each word in `args`. */\n readonly origins: readonly number[];\n /** Dashed words read as positionals, with their index on the original line. */\n readonly texts: ReadonlyArray<readonly [number, string]>;\n /** Dashed words no positional is left for, which fail as unknown options. */\n readonly refused: readonly string[];\n}\n\n/**\n * Morse, PGP armor and `-5` take a positional the plain words leave free, or fail as unknown\n * options. Neither reaches `util.parseArgs`, which reads the inner `-` of `-.-.` as `--`.\n *\n * @param rawArgs - Words after the command name.\n * @param fields - The command's fields.\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @returns {DashedText} The words left for `util.parseArgs` and the dashed text.\n */\nfunction takeDashedText(\n rawArgs: readonly string[],\n fields: readonly Field[],\n options: Readonly<Record<string, Field | \"json\">>,\n): DashedText {\n const { dashed, plain } = scanWords(rawArgs, options);\n const free = fields.filter((field) => field.positional).length - plain;\n const taken = dashed.slice(0, Math.max(free, 0));\n const skipped = new Set(dashed);\n const origins = rawArgs.flatMap((_, index) => (skipped.has(index) ? [] : [index]));\n const word = (index: number): string => rawArgs[index] ?? \"\";\n return {\n args: origins.map(word),\n origins,\n texts: taken.map((index) => [index, word(index)] as const),\n refused: dashed.slice(taken.length).map(word),\n };\n}\n\n/**\n * @param rawArgs - Words after the command name.\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @returns {{ dashed: number[]; plain: number }} Dashed words that spell no option, plain words.\n */\nfunction scanWords(\n rawArgs: readonly string[],\n options: Readonly<Record<string, Field | \"json\">>,\n): { dashed: number[]; plain: number } {\n const dashed: number[] = [];\n let plain = 0;\n for (let index = 0; index < rawArgs.length; index++) {\n const word = rawArgs[index] ?? \"\";\n if (word === \"--\") return { dashed, plain: plain + rawArgs.length - index - 1 };\n const kind = wordKind(word, options);\n if (kind === \"plain\") plain++;\n else if (kind === \"text\") dashed.push(index);\n else if (kind === \"valued\") index++;\n }\n return { dashed, plain };\n}\n\n/**\n * Reads a whole word the way {@link optionField} takes its tokens.\n *\n * @param word - One word before `--`.\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @returns {\"plain\" | \"option\" | \"valued\" | \"text\"} `valued` takes the next word as its value.\n */\nfunction wordKind(\n word: string,\n options: Readonly<Record<string, Field | \"json\">>,\n): \"plain\" | \"option\" | \"valued\" | \"text\" {\n if (!word.startsWith(\"-\") || word === \"-\") return \"plain\";\n if (word === \"-h\") return \"option\";\n const field = word.startsWith(\"--\")\n ? longField(word.slice(2), options)\n : shortField(word, options);\n if (field === undefined) return \"text\";\n if (field === \"option\" || field.kind === \"boolean\" || word.includes(\"=\")) return \"option\";\n return \"valued\";\n}\n\n/**\n * @param tokens - Tokens of the line without the dashed text.\n * @param origins - Index on the original line of each word `util.parseArgs` read.\n * @param texts - The dashed text with its index on the original line.\n * @returns {string[]} Every positional word, in the order the line gave them.\n */\nfunction inLineOrder(\n tokens: ReadonlyArray<Readonly<{ kind: string; index: number; value?: string | undefined }>>,\n origins: readonly number[],\n texts: ReadonlyArray<readonly [number, string]>,\n): string[] {\n const read = tokens.flatMap((token) =>\n token.kind === \"positional\" ? [[origins[token.index] ?? 0, token.value ?? \"\"] as const] : [],\n );\n return [...texts, ...read].toSorted(([a], [b]) => a - b).map(([, word]) => word);\n}\n\n/**\n * @param spelled - A long option without its `--`, maybe with `=value`.\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @returns {Field | \"option\" | undefined} The field, or `option` for help, json, `--no-`.\n */\nfunction longField(\n spelled: string,\n options: Readonly<Record<string, Field | \"json\">>,\n): Field | \"option\" | undefined {\n const [name = \"\"] = spelled.split(\"=\", 1);\n if (name === \"help\") return \"option\";\n const field = Object.hasOwn(options, name) ? options[name] : undefined;\n if (field !== undefined) return field === \"json\" ? \"option\" : field;\n return negatesBoolean(name, options) ? \"option\" : undefined;\n}\n\n/**\n * @param name - A long option name without its `--`.\n * @param options - Option fields by flag.\n * @returns {boolean} Whether the name is the `no-` form of a boolean flag.\n */\nfunction negatesBoolean(name: string, options: Readonly<Record<string, Field | \"json\">>): boolean {\n const flag = name.slice(3);\n const field = name.startsWith(\"no-\") && Object.hasOwn(options, flag) ? options[flag] : undefined;\n return field !== undefined && field !== \"json\" && field.kind === \"boolean\";\n}\n\n/**\n * @param word - A word with one leading dash.\n * @param options - Option fields by flag.\n * @returns {Field | undefined} The field whose short flag the whole word is.\n */\nfunction shortField(\n word: string,\n options: Readonly<Record<string, Field | \"json\">>,\n): Field | undefined {\n return Object.values(options).find(\n (field): field is Field =>\n field !== \"json\" && field.short !== undefined && `-${field.short}` === word,\n );\n}\n\n/**\n * @param fields - The command's fields.\n * @param positionals - Positional words in order.\n * @returns {Record<string, string>} Each positional property with its word, `rest` with the others.\n */\nfunction positionalValues(\n fields: readonly Field[],\n positionals: readonly string[],\n): Record<string, string> {\n const takes = fields.filter((field) => field.positional);\n return Object.assign(\n emptyRecord<string>(),\n Object.fromEntries(\n takes.flatMap((field, index) => {\n const words = field.rest ? positionals.slice(index) : positionals.slice(index, index + 1);\n return words.length === 0 ? [] : [[field.key, words.join(\" \")]];\n }),\n ),\n );\n}\n\n/**\n * @param fields - The command's fields.\n * @param positionals - Positional words in order.\n * @returns {string[]} The failure for words no positional takes.\n */\nfunction extraPositionals(fields: readonly Field[], positionals: readonly string[]): string[] {\n if (fields.some((field) => field.rest)) return [];\n const extra = positionals.length - fields.filter((field) => field.positional).length;\n if (extra <= 0) return [];\n return [`Invalid arguments: ${extra} unexpected positional argument${extra === 1 ? \"\" : \"s\"}`];\n}\n\ninterface OptionToken {\n readonly name: string;\n readonly rawName: string;\n readonly value?: string | undefined;\n readonly inlineValue?: boolean | undefined;\n}\n\ntype OptionRead =\n | { readonly error: string }\n | { readonly flag: \"json\" | \"help\" }\n | { readonly key: string; readonly value: string | boolean };\n\n/**\n * `-xh` expands to `-x` and `-h`; only the whole word `-h` asks for help.\n *\n * @param token - The token `util.parseArgs` made.\n * @param word - The command line word it came from.\n * @returns {boolean} Whether the token is `--help` or the word `-h`.\n */\nfunction asksHelp(token: OptionToken, word: string): boolean {\n return token.rawName === \"--help\" || word === \"-h\";\n}\n\n/**\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @param token - The token `util.parseArgs` made.\n * @param word - The command line word it came from.\n * @returns {Field | \"json\" | \"help\" | undefined} What the token names under a spelling it takes.\n */\nfunction optionField(\n options: Readonly<Record<string, Field | \"json\">>,\n token: OptionToken,\n word: string,\n): Field | \"json\" | \"help\" | undefined {\n if (asksHelp(token, word)) return \"help\";\n const field = Object.hasOwn(options, token.name) ? options[token.name] : undefined;\n if (field === \"json\") return token.rawName === \"--json\" ? field : undefined;\n return field !== undefined && spells(field, token, word) ? field : undefined;\n}\n\n/**\n * `--flag`, `--no-flag` for a boolean, or the short flag as a whole word only,\n * since `util.parseArgs` would read a mistyped `-provider` as `-p rovider`.\n *\n * @param field - Field the token's name points to.\n * @param token - The token `util.parseArgs` made.\n * @param word - The command line word it came from.\n * @returns {boolean} Whether the token is a spelling the field takes.\n */\nfunction spells(field: Field, token: OptionToken, word: string): boolean {\n if (token.rawName === `--${field.flag}`) return true;\n if (field.short !== undefined && token.rawName === `-${field.short}`)\n return word === token.rawName;\n return field.kind === \"boolean\" && token.rawName === `--no-${field.flag}`;\n}\n\n/**\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @param word - The command line word that names no option.\n * @returns {string} The failure, with every flag the command takes.\n */\nfunction unknownOption(options: Readonly<Record<string, Field | \"json\">>, word: string): string {\n const flags = Object.entries(options).map(([flag, each]) =>\n each === \"json\" || each.short === undefined ? `--${flag}` : `--${flag} (-${each.short})`,\n );\n const takes = flags.length > 0 ? flags.join(\", \") : \"no options\";\n return `Invalid arguments: unknown option ${JSON.stringify(word)}; takes ${takes}`;\n}\n\n/**\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @param token - The token `util.parseArgs` made.\n * @param word - The command line word it came from.\n * @param seen - Properties set by earlier words.\n * @returns {OptionRead} The value it sets, `--json`, or the failure.\n */\nfunction readOption(\n options: Readonly<Record<string, Field | \"json\">>,\n token: OptionToken,\n word: string,\n seen: readonly string[],\n): OptionRead {\n const field = optionField(options, token, word);\n if (field === undefined) return { error: unknownOption(options, word) };\n if (field === \"json\" || field === \"help\") {\n return token.inlineValue === true\n ? { error: `Invalid arguments: ${token.rawName} takes no value` }\n : { flag: field };\n }\n const problem = optionProblem(field, token, seen.includes(field.key));\n if (problem !== undefined) return { error: `Invalid arguments: --${field.flag} ${problem}` };\n const value = field.kind === \"boolean\" ? token.rawName !== `--no-${field.flag}` : token.value;\n return { key: field.key, value: value ?? \"\" };\n}\n\n/**\n * @param field - The option's field.\n * @param token - Its token.\n * @param seen - Whether an earlier word set the property already.\n * @returns {string | undefined} What is wrong with the option, if anything.\n */\nfunction optionProblem(field: Field, token: OptionToken, seen: boolean): string | undefined {\n if (seen) return \"given more than once\";\n if (field.kind === \"boolean\") return token.inlineValue === true ? \"takes no value\" : undefined;\n return token.value === undefined ? \"needs a value\" : undefined;\n}\n\n/**\n * Reads stdin as strict UTF-8. A lenient decode would turn each invalid byte\n * into U+FFFD, and a tool hashing or encoding the text would answer for other\n * input without a word; binary data needs a command of the package's own.\n *\n * @returns {string | undefined} The text, or nothing when stdin is not UTF-8.\n */\nfunction readStdin(): string | undefined {\n try {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(readFileSync(0));\n } catch (error) {\n if (error instanceof TypeError) return undefined;\n throw error;\n }\n}\n\n/** An `integer` word: decimal digits, maybe signed. */\nconst DECIMAL_INTEGER = /^[+-]?\\d+$/;\n\n/** A `number` word: decimal, with an optional fraction and exponent. */\nconst DECIMAL_NUMBER = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i;\n\n/**\n * Reads a number word as written: `Number` alone takes `0x10`, and an empty word as zero.\n *\n * @param integer - Whether the schema wants an `integer` rather than any `number`.\n * @param word - The word.\n * @returns {{ value: number } | { error: string }} The number, or the core's type error.\n */\nfunction numberValue(integer: boolean, word: string): { value: number } | { error: string } {\n const value = Number(word);\n const written = (integer ? DECIMAL_INTEGER : DECIMAL_NUMBER).test(word);\n if (written && Number.isFinite(value)) return { value };\n return { error: integer ? \"must be integer\" : \"must be number\" };\n}\n\n/** Literal values a word can spell; an object or array never comes from one word. */\nconst LITERAL_TYPES = new Set([\"string\", \"number\", \"boolean\"]);\n\n/** Types whose every value is a literal a word spells. */\nconst TYPE_LITERALS = new Map<unknown, readonly unknown[]>([\n [\"null\", [null]],\n [\"boolean\", [true, false]],\n]);\n\n/**\n * @param values - Every value the branch allows, from `const`, `enum` or its type.\n * @param word - The word.\n * @returns {{ value: unknown } | undefined} The literal the word spells exactly, if any.\n */\nfunction literalValue(values: readonly unknown[], word: string): { value: unknown } | undefined {\n const spelled = (item: unknown) =>\n (item === null || LITERAL_TYPES.has(typeof item)) && String(item) === word;\n return values.some(spelled) ? { value: values.find(spelled) } : undefined;\n}\n\n/**\n * @param branch - One branch of a union.\n * @param word - The word.\n * @returns {{ value: unknown } | undefined} What the branch reads the word as, if it takes it at all.\n */\nfunction branchValue(branch: SchemaNode, word: string): { value: unknown } | undefined {\n if (Object.hasOwn(branch, \"const\")) return literalValue([branch.const], word);\n if (Array.isArray(branch.enum)) return literalValue(branch.enum, word);\n const literals = TYPE_LITERALS.get(branch.type);\n if (literals !== undefined) return literalValue(literals, word);\n if (TYPE_KINDS.get(branch.type) !== \"number\") return undefined;\n const read = numberValue(branch.type === \"integer\", word);\n return \"value\" in read ? read : undefined;\n}\n\n/**\n * @param schema - Property schema.\n * @returns {readonly SchemaNode[]} Its branches, with nested combinators and type lists opened.\n */\nfunction unionBranches(schema: SchemaNode): readonly SchemaNode[] {\n const union = schema.anyOf ?? schema.oneOf ?? schema.allOf;\n if (Array.isArray(union)) return (union as readonly SchemaNode[]).flatMap(unionBranches);\n if (!Array.isArray(schema.type)) return [schema];\n return (schema.type as readonly unknown[]).map((type) => ({ ...schema, type }));\n}\n\n/**\n * The first reading of the word the schema accepts: the text itself, then what each branch spells.\n *\n * @param schema - Property schema, a union or not.\n * @param word - The word.\n * @returns {unknown} The value, or the word for validation to judge.\n */\nfunction wordValue(schema: SchemaNode, word: string): unknown {\n const readings = [\n word,\n ...unionBranches(schema).flatMap((branch) => {\n const read = branchValue(branch, word);\n return read === undefined ? [] : [read.value];\n }),\n ];\n const index = readings.findIndex((value) => Value.Check(schema, value));\n return index === -1 ? word : readings[index];\n}\n\n/**\n * @param field - Field the word belongs to.\n * @param raw - What {@link parseWords} read for it.\n * @returns {{ value: unknown } | { error: string }} The value, or why there is none.\n */\nfunction fieldValue(field: Field, raw: unknown): { value: unknown } | { error: string } {\n if (field.stdin && raw === \"-\") {\n const text = readStdin();\n return text === undefined ? { error: \"stdin is not UTF-8 text\" } : { value: text };\n }\n if (typeof raw !== \"string\") return { value: raw };\n if (field.kind === \"number\") return numberValue(field.schema.type === \"integer\", raw);\n if (field.kind === \"string\") return { value: wordValue(field.schema, raw) };\n if (field.kind !== \"json\") return { value: raw };\n try {\n return { value: JSON.parse(raw) as unknown };\n } catch {\n return { error: \"must be JSON\" };\n }\n}\n\n/**\n * Builds the tool input from parsed arguments. Numbers are read as decimals,\n * booleans come from the flag, objects and arrays are JSON, any other word is\n * its first reading the schema accepts, and nothing is bent to fit it:\n * {@link invokeTool} validates as on every surface.\n *\n * @param fields - The command's fields.\n * @param values - Raw values by property, from {@link parseWords}.\n * @returns {unknown} The input object.\n * @throws {ToolInputError} When a number or a JSON value does not read.\n */\nfunction toolInput(\n fields: readonly Field[],\n values: Readonly<Record<string, string | boolean>>,\n): unknown {\n const input = emptyRecord<unknown>();\n const fromStdin = fields.filter((field) => field.stdin && values[field.key] === \"-\");\n if (fromStdin.length > 1) {\n throw new ToolInputError([\n `Invalid arguments: stdin can feed one argument, not ${fromStdin.map((field) => field.key).join(\" and \")}`,\n ]);\n }\n const errors: string[] = [];\n for (const field of fields) {\n const raw = values[field.key];\n if (raw === undefined) continue;\n const read = fieldValue(field, raw);\n if (\"error\" in read) errors.push(`Invalid arguments at /${field.key}: ${read.error}`);\n else input[field.key] = read.value;\n }\n if (errors.length > 0) throw new ToolInputError(errors);\n return input;\n}\n\n/**\n * @param stream - Where to write.\n * @param text - Text, given a trailing newline when it lacks one.\n */\nfunction writeLine(stream: \"stdout\" | \"stderr\", text: string): void {\n process[stream].write(text.endsWith(\"\\n\") ? text : `${text}\\n`);\n}\n\n/**\n * Prints an error the CLI expects and sets exit code 1.\n *\n * @param lines - Failure lines.\n */\nfunction fail(lines: readonly string[]): void {\n writeLine(\"stderr\", lines.map(sanitizeLine).join(\"\\n\"));\n process.exitCode = 1;\n}\n\n/**\n * Turns expected errors into {@link fail}; any other error goes on with its stack.\n *\n * @param options - CLI options.\n * @param error - What the command threw.\n */\nfunction handleError(options: CliOptions, error: unknown): void {\n if (error instanceof ToolInputError) fail(error.lines);\n else if (options.expected?.(error) === true) {\n fail([error instanceof Error ? error.message : String(error)]);\n } else throw error;\n}\n\n/**\n * @param details - Tool details.\n * @returns {string} Pretty JSON; a bigint becomes its decimal string, no details `null`.\n */\nfunction detailsJson(details: unknown): string {\n // `JSON.stringify` answers `undefined`, not a string, for undefined details.\n const json =\n (JSON.stringify(\n details,\n (_key, value: unknown) => (typeof value === \"bigint\" ? value.toString() : value),\n 2,\n ) as string | undefined) ?? \"null\";\n return json.replaceAll(\n JSON_FORGING,\n (character) => `\\\\u${(character.codePointAt(0) ?? 0).toString(16).padStart(4, \"0\")}`,\n );\n}\n\n/**\n * What `JSON.stringify` leaves literal although a terminal acts on it: DEL and\n * C1, the bidi marks, overrides and isolates, and the Unicode line and\n * paragraph separators. They only occur inside strings, so a `\\u` escape\n * keeps the parsed details the same.\n */\nconst JSON_FORGING =\n /* oxlint-disable-next-line no-control-regex */\n /[\\u007F-\\u009F\\u061C\\u200E\\u200F\\u2028\\u2029\\u202A-\\u202E\\u2066-\\u206F]/g;\n\n/** One command the CLI dispatches to: a tool, a package command or `mcp`. */\ninterface Command {\n readonly name: string;\n readonly aliases: readonly string[];\n /** Line in the command list. */\n readonly summary: string;\n readonly fields: readonly Field[];\n /** Takes `--json`: a tool command prints its details; `mcp` has none. */\n readonly json: boolean;\n run(words: ParsedWords): Promise<void>;\n}\n\n/**\n * @param tool - Tool or package command to run.\n * @returns {Command} The command calling it.\n */\nfunction toolCommand(tool: ToolDefinition): Command {\n const fields = toolFields(tool);\n const [summary = tool.title] = tool.description.split(/(?<=[.!?])\\s/, 1);\n return {\n name: commandName(tool),\n aliases: (tool.cli?.aliases ?? []).map((alias) => commandWord(tool.name, alias)),\n summary: tool.cli?.description ?? summary,\n fields,\n json: tool.cli?.json !== false,\n async run(words) {\n const result = await invokeTool(tool, toolInput(fields, words.values));\n if (result.isError === true) {\n writeLine(\"stderr\", sanitizeText(resultText(result)));\n process.exitCode = 1;\n } else if (words.json) {\n writeLine(\"stdout\", detailsJson(result.details));\n } else if (result.content.length > 0) {\n writeLine(\"stdout\", sanitizeText(resultText(result)));\n const images = result.content.filter((block) => block.type === \"image\").length;\n if (images > 0) writeLine(\"stderr\", `(${images} image block(s) not printed)`);\n }\n },\n };\n}\n\n/**\n * @param options - CLI options.\n * @returns {Command} The stdio MCP server command.\n */\nfunction mcpCommand(options: CliOptions): Command {\n return {\n name: \"mcp\",\n aliases: [],\n summary: `Run the ${options.name} MCP server over stdio`,\n fields: [],\n json: false,\n async run() {\n const [{ createMcpServer }, { StdioServerTransport }] = await Promise.all([\n import(\"./mcp.ts\"),\n import(\"@modelcontextprotocol/server/stdio\"),\n ]);\n await createMcpServer(options, options.tools).connect(new StdioServerTransport());\n },\n };\n}\n\n/**\n * The definitions behind the commands, in listing order: the tools, each\n * replaced in place by a package command of its command name, then the rest\n * of the package commands.\n *\n * @param options - CLI options.\n * @returns {ToolDefinition[]} One definition per command but `mcp`.\n */\nfunction commandTools(options: CliOptions): ToolDefinition[] {\n const own = options.commands ?? [];\n const byName = new Map(own.map((command) => [commandName(command), command]));\n const listed = options.tools.map((tool) => byName.get(commandName(tool)) ?? tool);\n return [...listed, ...own.filter((command) => !listed.includes(command))];\n}\n\n/**\n * @param options - CLI options.\n * @returns {boolean} Whether the built-in `mcp` command is on and no package command replaces it.\n */\nfunction builtInMcp(options: CliOptions): boolean {\n return (\n options.mcp === true &&\n !(options.commands ?? []).some((command) => commandName(command) === \"mcp\")\n );\n}\n\n/**\n * @param options - CLI options.\n * @returns {string[]} Every command name and alias, `mcp` included when built in.\n */\nfunction commandWords(options: CliOptions): string[] {\n return [\n ...commandTools(options).flatMap((tool) => [commandName(tool), ...(tool.cli?.aliases ?? [])]),\n ...(builtInMcp(options) ? [\"mcp\"] : []),\n ];\n}\n\n/** A built command line interface. */\nexport interface Cli {\n /** Runs one command line: the words after the executable and script. */\n run(argv: readonly string[]): Promise<void>;\n}\n\n/**\n * Builds the commands and checks every definition, so a broken hint fails at\n * startup and not on the first call that reaches it.\n *\n * @param options - CLI options.\n * @returns {Cli} The CLI.\n * @throws {ToolDefinitionError} When two commands share a name or alias, a hint does not fit its schema, or `default` or `fallback` names no command.\n */\nexport function createCli(options: CliOptions): Cli {\n indexTools(options.tools);\n indexTools(options.commands ?? []);\n const commands = [\n ...commandTools(options).map((tool) => toolCommand(tool)),\n ...(builtInMcp(options) ? [mcpCommand(options)] : []),\n ];\n const words = commandWords(options);\n const repeated = words.find((word, index) => words.indexOf(word) !== index);\n if (repeated !== undefined) throw new ToolDefinitionError(`Two commands are named ${repeated}`);\n const missing = [options.default, options.fallback].find(\n (name) => name !== undefined && !words.includes(name),\n );\n if (missing !== undefined)\n throw new ToolDefinitionError(`${options.name}: no command ${missing}`);\n\n return { run: (argv) => dispatch(options, commands, normalizeArgv(options, argv)) };\n}\n\n/**\n * Applies `default` and `fallback`: an empty command line runs `default`, and\n * a first word that names no command goes to `fallback` as its first\n * argument. A leading option such as `--help` stays at the root; a lone `-`\n * is the stdin word of the fallback's positional, not an option.\n *\n * @param options - CLI options.\n * @param argv - Words after the executable and script.\n * @returns {string[]} The words to dispatch.\n */\nexport function normalizeArgv(options: CliOptions, argv: readonly string[]): string[] {\n const [first] = argv;\n if (first === undefined) return options.default === undefined ? [] : [options.default];\n const option = first.startsWith(\"-\") && first !== \"-\";\n if (options.fallback === undefined || option || commandWords(options).includes(first)) {\n return [...argv];\n }\n return [options.fallback, ...argv];\n}\n\n/**\n * Picks the command by its first word and runs it. `--help` and `-h` count\n * only where the parse finds an option: after `--` or as an option's value\n * they are the tool's words. Every error line goes through\n * {@link sanitizeLine}, an unknown word inside `JSON.stringify`.\n *\n * @param options - CLI options.\n * @param commands - The commands.\n * @param argv - Words after {@link normalizeArgv}.\n */\nasync function dispatch(\n options: CliOptions,\n commands: readonly Command[],\n argv: readonly string[],\n): Promise<void> {\n const [first, ...rest] = argv;\n if (argv.length === 1 && (first === \"--version\" || first === \"-v\")) {\n writeLine(\"stdout\", sanitizeLine(options.version));\n } else if (first === \"--help\" || first === \"-h\") {\n writeLine(\"stdout\", sanitizeText(mainUsage(options, commands)));\n } else if (first === undefined) {\n writeLine(\"stderr\", sanitizeText(mainUsage(options, commands)));\n fail([\"No command specified\"]);\n } else {\n const command = commands.find((each) => each.name === first || each.aliases.includes(first));\n if (command === undefined) {\n fail([\n `Unknown command ${JSON.stringify(first)}`,\n `Run ${options.name} --help for the commands`,\n ]);\n } else {\n await runCommand(options, command, rest);\n }\n }\n}\n\n/**\n * @param options - CLI options.\n * @param command - The chosen command.\n * @param rawArgs - Words after the command name.\n */\nasync function runCommand(\n options: CliOptions,\n command: Command,\n rawArgs: readonly string[],\n): Promise<void> {\n const words = parseWords(rawArgs, command.fields, command.json);\n if (words.help) {\n writeLine(\"stdout\", sanitizeText(commandUsage(options, command)));\n return;\n }\n try {\n if (words.errors.length > 0) throw new ToolInputError(words.errors);\n await command.run(words);\n } catch (error) {\n handleError(options, error);\n }\n}\n\n/**\n * @param rows - Left and right column of each row.\n * @returns {string[]} The rows, indented, with the right column aligned.\n */\nfunction table(rows: readonly (readonly [string, string])[]): string[] {\n const width = Math.max(0, ...rows.map(([left]) => left.length));\n return rows.map(([left, right]) => ` ${left.padEnd(width)} ${right}`.trimEnd());\n}\n\n/**\n * @param options - CLI options.\n * @param commands - The commands.\n * @returns {string} The usage text of the CLI.\n */\nfunction mainUsage(options: CliOptions, commands: readonly Command[]): string {\n return [\n `${options.description} (${options.name} v${options.version})`,\n \"\",\n `USAGE ${options.name} <command> [OPTIONS]`,\n \"\",\n \"COMMANDS\",\n \"\",\n ...table(\n commands.map((command) => [[command.name, ...command.aliases].join(\", \"), command.summary]),\n ),\n \"\",\n `Use ${options.name} <command> --help for more information about a command.`,\n ].join(\"\\n\");\n}\n\n/**\n * @param options - CLI options.\n * @param command - The command.\n * @returns {string} Its usage text.\n */\nfunction commandUsage(options: CliOptions, command: Command): string {\n const positional = command.fields.filter((field) => field.positional);\n const flags = command.fields.filter((field) => !field.positional);\n const takesOptions = flags.length > 0 || command.json;\n const words = positional.map((field) => {\n const name = `${field.flag.toUpperCase()}${field.rest ? \"...\" : \"\"}`;\n return field.required ? `<${name}>` : `[${name}]`;\n });\n const rows = [\n ...flags.map((field): [string, string] => [\n `${field.short === undefined ? \"\" : `-${field.short}, `}${optionSpelling(field)}`,\n fieldDescription(field),\n ]),\n ...(command.json\n ? [[\"--json\", \"Print the details as JSON instead of the text\"] as [string, string]]\n : []),\n [\"-h, --help\", \"Show this help\"] as [string, string],\n ];\n return [\n `${command.summary} (${options.name} ${command.name} v${options.version})`,\n \"\",\n `USAGE ${[options.name, command.name, ...(takesOptions ? [\"[OPTIONS]\"] : []), ...words].join(\" \")}`,\n ...(positional.length > 0\n ? [\n \"\",\n \"ARGUMENTS\",\n \"\",\n ...table(positional.map((field) => [field.flag.toUpperCase(), fieldDescription(field)])),\n ]\n : []),\n \"\",\n \"OPTIONS\",\n \"\",\n ...table(rows),\n ].join(\"\\n\");\n}\n\n/**\n * Ends the process once the reader of stdout or stderr is gone, as after\n * `| head -1`. Node ignores SIGPIPE, so without a listener the next write\n * throws `EPIPE` with a stack trace. The exit code stays what the command set.\n *\n * @param error - The error the stream emitted.\n */\nfunction exitOnClosedPipe(error: Readonly<NodeJS.ErrnoException>): void {\n if (error.code !== \"EPIPE\") throw error;\n process.exit();\n}\n\n/**\n * Runs the CLI on `process.argv`. The CLI writes no colors, so nothing\n * depends on the terminal it writes to.\n *\n * @param options - CLI options.\n * @param argv - Words after the executable and script.\n */\nexport async function runCli(\n options: CliOptions,\n argv: readonly string[] = process.argv.slice(2),\n): Promise<void> {\n process.stdout.on(\"error\", exitOnClosedPipe);\n process.stderr.on(\"error\", exitOnClosedPipe);\n await createCli(options).run(argv);\n}\n"],"mappings":";;;;;;;;;;AAsDA,MAAM,6BAAY,IAAA,IAAA,CAAA,UAAA,MAAA,CAAA;AAGlB,MAAM,aAAA;AAA0B,MAAA,6BAAA,IAAA,IAAA;CAAQ,CAAA,WAAA,SAAA;CAAW,CAAA,WAAA,QAAA;CAAO,CAAA,UAAA,QAAA;;CAG1D,CAAA,SAAM,MAAA;;AAsBN,SAAM,SAAA,KAAA;CACJ,OAAC,IAAA,WAAoB,sBAAA,OAAA,CAAA,CAAA,WAAA,KAAA,GAAA,CAAA,CAAA,YAAA;AACrB;AAEA,SAAC,YAAgB,MAAA;CACjB,IAAC,KAAA,KAAS,YAAM,KAAA,GAAA,OAAA,YAAA,KAAA,MAAA,KAAA,IAAA,OAAA;CACjB,MAAA,YAAA,KAAA,KAAA,QAAA,GAAA;;;;AAMD,MAAA,eAAkB;AAKlB,SAAA,YAAA,OAAA,MAAA;;;;AAMA,SAAgB,UAAA,QAA0C;CACxD,IAAI,MAAK,QAAK,OAAA,IAAY,KAAW,OAAO,KAAA,OAAY,UAAK,OAAW,UAAW,QAAA,GAAA,OAAA;CACnF,KAAA,MAAM,QAAY,OAAK,KAAK,IAAA,OAAW,QAAA,CAAA,EAAA,CAAA,MAAA,WAAA,UAAA,MAAA,MAAA,MAAA,GAAA,OAAA;CACvC,OAAM,WAAU,IAAA,OAAA,IAAc,KAAK;AAEnC;;CAIF,MAAM,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AAQ,GAAI,QAAA,KAAA,IAAA,QAAA,QAAA;EACrC;EACD,SACH;GACA,QAAM;GACN,QAAO;GACT,GAAA,eAAA,CAAA,WAAA,IAAA,CAAA;;;;;;GAOA;GACE,GAAI,MAAM,WAAS,KAAQ,UAAK,CAAA,MAAA,KAAA,YAAA,GAAA,iBAAA,KAAA,CAAA,CAAA,CAAA;EAC9B,IAAA,CAAA;EACA;EACF;EACA;EACA,GAAI,MAAM,IAAA;CACV,CAAA,CAAA,KAAI,IAAM;AACV;AAEE,SAAO,iBAAc,OAAS;CAChC,IAAA,MAAQ,SAAA,SAAA,MAAA;CACN,QAAO,KAAE;AACX"}
package/dist/h3.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { ToolDefinition as ToolDefinition$1 } from "./index.mjs";
1
+ import { ToolDefinition as ToolDefinition$1 } from "./_chunks/index.mjs";
2
2
  import { JsonSchema, ToolDefinition } from "h3-mcp";
3
3
  /** An h3-mcp tool whose `inputSchema` is the plain JSON Schema `tools/list` sends. */
4
4
  export type H3Tool = ToolDefinition<JsonSchema>;
package/dist/h3.mjs CHANGED
@@ -5,6 +5,7 @@ function toH3Tools(info, tools) {
5
5
  name: entry.name,
6
6
  title: entry.title,
7
7
  description: entry.description,
8
+ ...entry.icons === void 0 ? {} : { icons: entry.icons },
8
9
  inputSchema: entry.inputSchema,
9
10
  annotations: entry.annotations,
10
11
  handler: (args, event) => {
package/dist/h3.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"h3.mjs","names":[],"sources":["../src/h3.ts"],"sourcesContent":["/**\n * h3-mcp adapter: hands {@link ToolDefinition}s to `defineMcpHandler` from h3-mcp.\n */\n\nimport type { JsonSchema, ToolDefinition as H3ToolDefinition } from \"h3-mcp\";\n\nimport { type ToolCallContext, type ToolDefinition } from \"./index.ts\";\nimport { callTool, listTools, progressSteps } from \"./mcp-answers.ts\";\n\n/** An h3-mcp tool whose `inputSchema` is the plain JSON Schema `tools/list` sends. */\nexport type H3Tool = H3ToolDefinition<JsonSchema>;\n\n/**\n * Turns tools into h3-mcp tool definitions for `defineMcpHandler({ tools })`.\n *\n * Each entry carries what `listTools` lists, and its handler answers through\n * `callTool`, so the text, the validation lines and the sanitized errors are the\n * ones every other MCP transport gives. The schema goes out as plain JSON\n * Schema, which h3-mcp passes through without validating; the core validates\n * instead. An unknown name never reaches a handler: h3-mcp answers it itself\n * with a JSON-RPC error.\n *\n * Imports only types from h3-mcp, so the adapter loads neither h3-mcp nor the MCP SDK.\n *\n * @param info - Server info; `name` is the word in the message for an unknown tool.\n * @param tools - Tools to serve.\n * @returns {H3Tool[]} Tool definitions in the order given.\n * @throws {ToolDefinitionError} When two tools share a name.\n */\nexport function toH3Tools(\n info: { readonly name: string },\n tools: readonly ToolDefinition[],\n): H3Tool[] {\n return listTools(tools).map((entry) => ({\n name: entry.name,\n title: entry.title,\n description: entry.description,\n inputSchema: entry.inputSchema as JsonSchema,\n annotations: entry.annotations,\n handler: (args, event) => {\n // Read now: a legacy batch shares one context between its calls.\n const mcp = event.context.mcp;\n const context: ToolCallContext = {\n signal: mcp?.signal,\n ...(mcp?.progressToken === undefined || mcp.progress === undefined\n ? {}\n : {\n progress: progressSteps(({ progress, total, message }) =>\n mcp.progress?.(progress, total, message),\n ),\n }),\n };\n return callTool(info, tools, entry.name, args, context);\n },\n }));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA6BA;AAKI,SAAM"}
1
+ {"version":3,"file":"h3.mjs","names":[],"sources":["../src/h3.ts"],"sourcesContent":["/**\n * h3-mcp adapter: hands {@link ToolDefinition}s to `defineMcpHandler` from h3-mcp.\n */\n\nimport type { JsonSchema, ToolDefinition as H3ToolDefinition } from \"h3-mcp\";\n\nimport { type ToolCallContext, type ToolDefinition } from \"./index.ts\";\nimport { callTool, listTools, progressSteps } from \"./mcp-answers.ts\";\n\n/** An h3-mcp tool whose `inputSchema` is the plain JSON Schema `tools/list` sends. */\nexport type H3Tool = H3ToolDefinition<JsonSchema>;\n\n/**\n * Turns tools into h3-mcp tool definitions for `defineMcpHandler({ tools })`.\n *\n * Each entry carries what `listTools` lists, and its handler answers through\n * `callTool`, so the text, the validation lines and the sanitized errors are the\n * ones every other MCP transport gives. The schema goes out as plain JSON\n * Schema, which h3-mcp passes through without validating; the core validates\n * instead. An unknown name never reaches a handler: h3-mcp answers it itself\n * with a JSON-RPC error.\n *\n * Imports only types from h3-mcp, so the adapter loads neither h3-mcp nor the MCP SDK.\n *\n * @param info - Server info; `name` is the word in the message for an unknown tool.\n * @param tools - Tools to serve.\n * @returns {H3Tool[]} Tool definitions in the order given.\n * @throws {ToolDefinitionError} When two tools share a name.\n */\nexport function toH3Tools(\n info: { readonly name: string },\n tools: readonly ToolDefinition[],\n): H3Tool[] {\n return listTools(tools).map((entry) => ({\n name: entry.name,\n title: entry.title,\n description: entry.description,\n ...(entry.icons === undefined ? {} : { icons: entry.icons }),\n inputSchema: entry.inputSchema as JsonSchema,\n annotations: entry.annotations,\n handler: (args, event) => {\n // Read now: a legacy batch shares one context between its calls.\n const mcp = event.context.mcp;\n const context: ToolCallContext = {\n signal: mcp?.signal,\n ...(mcp?.progressToken === undefined || mcp.progress === undefined\n ? {}\n : {\n progress: progressSteps(({ progress, total, message }) =>\n mcp.progress?.(progress, total, message),\n ),\n }),\n };\n return callTool(info, tools, entry.name, args, context);\n },\n }));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;CA6BA,EAAA;AAIE;AAEE,SAAO"}
package/dist/index.d.mts CHANGED
@@ -1,177 +1,3 @@
1
- import { AddImmutable, AddImmutableDeferred, AddOptional, AddOptionalDeferred, AddReadonly, AddReadonlyDeferred, Any, ArrayOptions, BigInt, BigIntPattern, Boolean, Broaden, Call, CallConstruct, CanComposite, Capitalize, CapitalizeAction, CapitalizeDeferred, CapitalizeInstantiate, Codec, CollapseToObject, Compare, CompareResultDisjoint, CompareResultEqual, CompareResultLeftInside, CompareResultRightInside, Composite, Conditional, ConditionalAction, ConditionalDeferred, ConditionalInstantiate, Constructor, ConstructorOptions, ConstructorParameters, ConstructorParametersAction, ConstructorParametersDeferred, ConstructorParametersInstantiate, ConvertToIntegerKey, Cyclic, CyclicCandidates, CyclicCheck, CyclicDependencies, CyclicExtends, CyclicOptions, CyclicTarget, Decode, DecodeBuilder, Deferred, Dependent, DependentOptions, Distribute, Encode, EncodeBuilder, Enum, Evaluate, EvaluateAction, EvaluateDeferred, EvaluateDependent, EvaluateEnum, EvaluateInstantiate, EvaluateIntersect, EvaluateTemplateLiteral, EvaluateType, EvaluateUnion, EvaluateUnionFast, Exclude, ExcludeAction, ExcludeDeferred, ExcludeInstantiate, Extends, Extract, ExtractAction, ExtractDeferred, ExtractInstantiate, Flatten, FunctionOptions, Generic, Identifier, Immutable, Index, IndexAction, IndexDeferred, IndexInstantiate, Infer, InstanceType, InstanceTypeAction, InstanceTypeDeferred, InstanceTypeInstantiate, Instantiate, InstantiateCyclic, Integer, IntegerKey, IntegerPattern, Interface, InterfaceAction, InterfaceDeferred, InterfaceInstantiate, Intersect, IntersectOptions, InvalidLiteralValue, IsAny, IsArray, IsBigInt, IsBoolean, IsCall, IsCodec, IsConstructor, IsCyclic, IsDeferred, IsDependent, IsEnum, IsEnumValue, IsFunction, IsGeneric, IsIdentifier, IsImmutable, IsInfer, IsInteger, IsInterfaceDeferred, IsIntersect, IsKind, IsLiteral, IsLiteralBigInt, IsLiteralBoolean, IsLiteralNumber, IsLiteralString, IsLiteralValue, IsNever, IsNull, IsNumber, IsObject, IsOptional, IsParameter, IsReadonly, IsRecord, IsRef, IsRefine, IsRefinement, IsRest, IsSchema, IsString, IsSymbol, IsTemplateLiteral, IsTemplateLiteralDeferred, IsTemplateLiteralFinite, IsTemplateLiteralPattern, IsThis, IsTuple, IsTypeScriptEnumLike, IsUndefined, IsUnion, IsUnknown, IsUnsafe, IsVoid, KeyOf, KeyOfAction, KeyOfDeferred, KeyOfInstantiate, KeysToIndexer, Literal, LiteralTypeName, Lowercase, LowercaseAction, LowercaseDeferred, LowercaseInstantiate, Mapped, MappedAction, MappedDeferred, MappedInstantiate, Module, ModuleDeferred, ModuleInstantiate, Narrow, Never, NeverPattern, NonNullable, NonNullableAction, NonNullableDeferred, NonNullableInstantiate, Null, Number, NumberKey, NumberPattern, ObjectOptions, Omit, OmitAction, OmitDeferred, OmitInstantiate, Optional, Parameter, Parameters, ParametersAction, ParametersDeferred, ParametersInstantiate, ParsePatternIntoTypes, ParseTemplateIntoTypes, Partial, PartialAction, PartialDeferred, PartialInstantiate, Pick, PickAction, PickDeferred, PickInstantiate, Priority, PropertyKeys, PropertyValues, Readonly, ReadonlyObject, ReadonlyObjectAction, ReadonlyObjectDeferred, ReadonlyObjectInstantiate, ReadonlyType, Record as Record$1, RecordAction, RecordDeferred, RecordFromPattern, RecordInstantiate, RecordKey, RecordOptions, RecordPattern, RecordPatternToType, RecordValue, Ref, RefInstantiate, Refine, RefineAdd, RemoveImmutable, RemoveImmutableDeferred, RemoveOptional, RemoveOptionalDeferred, RemoveReadonly, RemoveReadonlyDeferred, Required, RequiredAction, RequiredArray, RequiredDeferred, RequiredInstantiate, Rest, ReturnType, ReturnTypeAction, ReturnTypeDeferred, ReturnTypeInstantiate, Script, Static, StaticAny, StaticArray, StaticBigInt, StaticBoolean, StaticCodec, StaticConstructor, StaticCyclic, StaticDecode, StaticDependent, StaticDirection, StaticEncode, StaticEnum, StaticEvaluate, StaticFunction, StaticInstantiatedParameters, StaticInteger, StaticIntersect, StaticLiteral, StaticNever, StaticNull, StaticNumber, StaticObject, StaticParse, StaticProperties, StaticRecord, StaticRef, StaticString, StaticSymbol, StaticTemplateLiteral, StaticThis, StaticTuple, StaticType, StaticUndefined, StaticUnion, StaticUnknown, StaticUnsafe, StaticVoid, String, StringKey, StringPattern, Symbol, TAddImmutable, TAddImmutableDeferred, TAddOptional, TAddOptionalDeferred, TAddReadonly, TAddReadonlyDeferred, TAny, TArray, TArrayOptions, TBigInt, TBoolean, TBroaden, TCall, TCallConstruct, TCanComposite, TCapitalize, TCapitalizeAction, TCapitalizeDeferred, TCapitalizeInstantiate, TCodec, TCollapseToObject, TCompare, TCompareResult, TComposite, TConditional, TConditionalAction, TConditionalDeferred, TConditionalInstantiate, TConstructor, TConstructorParameters, TConstructorParametersAction, TConstructorParametersDeferred, TConstructorParametersInstantiate, TConvertToIntegerKey, TCyclic, TCyclicCandidates, TCyclicCheck, TCyclicDependencies, TCyclicExtends, TCyclicTarget, TDecodeCallback, TDeferred, TDependent, TDistribute, TEncodeCallback, TEnum, TEnumValue, TEvaluate, TEvaluateAction, TEvaluateDeferred, TEvaluateDependent, TEvaluateEnum, TEvaluateInstantiate, TEvaluateIntersect, TEvaluateTemplateLiteral, TEvaluateType, TEvaluateUnion, TEvaluateUnionFast, TExclude, TExcludeAction, TExcludeDeferred, TExcludeInstantiate, TExtends, TExtract, TExtractAction, TExtractDeferred, TExtractInstantiate, TFlatten, TFormat, TFunction, TGeneric, TIdentifier, TImmutable, TIndex, TIndexAction, TIndexDeferred, TIndexInstantiate, TInfer, TInstanceType, TInstanceTypeAction, TInstanceTypeDeferred, TInstanceTypeInstantiate, TInstantiate, TInstantiateCyclic, TInteger, TIntegerKey, TInterface, TInterfaceAction, TInterfaceDeferred, TInterfaceInstantiate, TIntersect, TIntersectOptions, TIsTemplateLiteralFinite, TIsTemplateLiteralPattern, TKeyOf, TKeyOfAction, TKeyOfDeferred, TKeyOfInstantiate, TKeysToIndexer, TLiteral, TLiteralTypeName, TLiteralValue, TLowercase, TLowercaseAction, TLowercaseDeferred, TLowercaseInstantiate, TMapped, TMappedAction, TMappedDeferred, TMappedInstantiate, TModule, TModuleDeferred, TModuleInstantiate, TNarrow, TNever, TNonNullable, TNonNullableAction, TNonNullableDeferred, TNonNullableInstantiate, TNull, TNumber, TNumberKey, TNumberOptions, TObject, TObjectOptions, TOmit, TOmitAction, TOmitDeferred, TOmitInstantiate, TOptional, TParameter, TParameters, TParametersAction, TParametersDeferred, TParametersInstantiate, TParsePatternIntoTypes, TParseTemplateIntoTypes, TPartial, TPartialAction, TPartialDeferred, TPartialInstantiate, TPick, TPickAction, TPickDeferred, TPickInstantiate, TPriority, TProperties, TPropertyKeys, TPropertyValues, TReadonly, TReadonlyObject, TReadonlyObjectAction, TReadonlyObjectDeferred, TReadonlyObjectInstantiate, TRecord, TRecordAction, TRecordDeferred, TRecordInstantiate, TRecordKey, TRecordPattern, TRecordPatternToType, TRecordValue, TRef, TRefInstantiate, TRefine, TRefineAdd, TRefineCheckCallback, TRefineErrorCallback, TRefinement, TRemoveImmutable, TRemoveImmutableDeferred, TRemoveOptional, TRemoveOptionalDeferred, TRemoveReadonly, TRemoveReadonlyDeferred, TRequired, TRequiredAction, TRequiredArray, TRequiredDeferred, TRequiredInstantiate, TRest, TReturnType, TReturnTypeAction, TReturnTypeDeferred, TReturnTypeInstantiate, TSchema, TSchemaOptions, TScript, TScriptOptions, TStaticElements, TString, TStringKey, TStringOptions, TSymbol, TTemplateLiteral, TTemplateLiteralDecode, TTemplateLiteralDecodeUnsafe, TTemplateLiteralDeferred, TTemplateLiteralEncode, TTemplateLiteralFromString, TTemplateLiteralFromTypes, TTemplateLiteralStatic, TThis, TTuple, TTupleOptions, TTupleToIntersect, TTupleToUnion, TTypeScriptEnumLike, TTypeScriptEnumToEnumValues, TUncapitalize, TUncapitalizeAction, TUncapitalizeDeferred, TUncapitalizeInstantiate, TUndefined, TUnion, TUnionLast, TUnionToIntersect, TUnionToTuple, TUnknown, TUnsafe, TUppercase, TUppercaseAction, TUppercaseDeferred, TUppercaseInstantiate, TVoid, TWith, TWithAction, TWithDeferred, TWithInstantiate, TemplateLiteral, TemplateLiteralCreate, TemplateLiteralDecode, TemplateLiteralDecodeUnsafe, TemplateLiteralDeferred, TemplateLiteralEncode, TemplateLiteralFromString, TemplateLiteralFromTypes, This, Tuple, TupleOptions, TypeScriptEnumToEnumValues, Uncapitalize, UncapitalizeAction, UncapitalizeDeferred, UncapitalizeInstantiate, Undefined, Union, UnionOptions, Unknown, Unsafe, Uppercase, UppercaseAction, UppercaseDeferred, UppercaseInstantiate, Void, With, WithAction, WithDeferred, WithInstantiate, _Array_, _Function_, _Object_, index_d_exports, result_d_exports } from "./_chunks/libs/typebox.mjs";
2
- /** Content block understood by MCP, Pi and OMP alike. */
3
- export type ToolContent = {
4
- type: "text";
5
- text: string;
6
- } | {
7
- type: "image";
8
- data: string;
9
- mimeType: string;
10
- };
11
- /** Text for the model plus details for the harness. */
12
- export interface ToolResult<Details = unknown> {
13
- content: ToolContent[];
14
- details: Details;
15
- /** Set when the tool could not answer. Each adapter carries it to its host. */
16
- isError?: boolean;
17
- }
18
- /**
19
- * What a call does to the world, mapped to MCP annotations and OMP approval.
20
- *
21
- * - `read` changes nothing.
22
- * - `write` changes state that the next call can undo or overwrite.
23
- * - `destructive` deletes or overwrites what cannot be recovered.
24
- */
25
- export type ToolEffect = "read" | "write" | "destructive";
26
- /**
27
- * How a tool reads on the command line. Without hints the command is the tool
28
- * name without its package prefix, in kebab case, and every property is a flag.
29
- */
30
- export interface ToolCliHints {
31
- /** Command name instead of the derived one. */
32
- readonly command?: string;
33
- readonly aliases?: readonly string[];
34
- /** Line in the command list. Defaults to the first sentence of `description`. */
35
- readonly description?: string;
36
- /** Properties taken in this order as positional arguments instead of flags. */
37
- readonly positional?: readonly string[];
38
- /** String properties that read stdin when given as `-`. */
39
- readonly stdin?: readonly string[];
40
- }
41
- /** How far a long call has come, for hosts that draw it. */
42
- export interface ToolProgress {
43
- /** Work done so far. MCP skips an update where it doesn't grow. */
44
- readonly progress: number;
45
- /** All the work there is, when the tool knows it. */
46
- readonly total?: number;
47
- }
48
- /** Per-call context the adapters hand to `execute`. */
49
- export interface ToolCallContext {
50
- signal?: AbortSignal;
51
- /** Says the call is still at it. Absent where the host can't show it, so call `progress?.()`. */
52
- progress?: (message: string, amount?: ToolProgress) => void;
53
- }
54
- export interface ToolDefinition<Input extends TObject = TObject, Details = unknown> {
55
- /** Wire name, `<package>_<operation>`. */
56
- readonly name: string;
57
- /** Human label: MCP `title` and `annotations.title`, Pi and OMP `label`. */
58
- readonly title: string;
59
- /** Complete instruction for the model. MCP clients see nothing else. */
60
- readonly description: string;
61
- /** Pi `promptSnippet`. */
62
- readonly snippet?: string;
63
- /** Pi `promptGuidelines`. Must not promise anything `description` lacks. */
64
- readonly guidelines?: readonly string[];
65
- readonly effect: ToolEffect;
66
- /** Repeating the call with the same input has no further effect. Defaults to `effect === "read"`. */
67
- readonly idempotent?: boolean;
68
- /** The call reaches outside the local machine. */
69
- readonly openWorld?: boolean;
70
- readonly input: Input;
71
- /** Command line shape for `@agntn/tools/cli`. No other surface reads it. */
72
- readonly cli?: ToolCliHints;
73
- /**
74
- * Runs the tool on input that already passed {@link validateInput}.
75
- *
76
- * Method syntax on purpose: it keeps the parameter bivariant, so a list of
77
- * tools with different inputs is still a `readonly ToolDefinition[]`.
78
- */
79
- execute(input: Static<Input>, context: ToolCallContext): ToolResult<Details> | Promise<ToolResult<Details>>;
80
- }
81
- /** Thrown when a tool definition breaks a contract every surface relies on. */
82
- export declare class ToolDefinitionError extends Error {
83
- name: string;
84
- }
85
- /** Thrown by {@link invokeTool} when the arguments fail the tool schema. */
86
- export declare class ToolInputError extends Error {
87
- name: string;
88
- /** One validation failure per line. Only these line breaks are the core's own. */
89
- readonly lines: readonly string[];
90
- /**
91
- * @param lines - One validation failure per line.
92
- */
93
- constructor(lines: readonly string[]);
94
- }
95
- /**
96
- * Declares a tool and checks the schema rules every surface depends on.
97
- *
98
- * @param tool - Tool definition.
99
- * @returns {ToolDefinition<Input, Details>} The same definition, typed.
100
- */
101
- export declare function defineTool<const Input extends TObject, Details>(tool: ToolDefinition<Input, Details>): ToolDefinition<Input, Details>;
102
- /**
103
- * The input schema as the plain JSON Schema object every host receives.
104
- *
105
- * TypeBox 1.x schemas are plain objects already; this only drops the static
106
- * type, which lacks the index signature host APIs declare.
107
- *
108
- * @param tool - Tool whose schema to emit.
109
- * @returns {Record<string, unknown>} JSON Schema document.
110
- */
111
- export declare function wireSchema(tool: ToolDefinition): Record<string, unknown>;
112
- /**
113
- * Indexes tools by name.
114
- *
115
- * A `Map`, not a plain object: a lookup of `toString` in a `Record` finds
116
- * `Object.prototype.toString` and skips the unknown-tool branch.
117
- *
118
- * @param tools - Tools to index.
119
- * @returns {ReadonlyMap<string, ToolDefinition>} Tools by wire name.
120
- */
121
- export declare function indexTools(tools: readonly ToolDefinition[]): ReadonlyMap<string, ToolDefinition>;
122
- export type InputCheck<Input extends TObject> = {
123
- ok: true;
124
- value: Static<Input>;
125
- } | {
126
- ok: false;
127
- lines: readonly string[];
128
- };
129
- /**
130
- * Validates arguments against the tool schema, reporting every failure.
131
- *
132
- * Runs on every surface, not only MCP: a host may skip its own validation, and
133
- * OMP's omptype drops `pattern` from the schema it emits. The message has one
134
- * line per failure: an undeclared key names itself with the keys its object
135
- * takes, at any depth, and an enum failure names the allowed values, so the
136
- * caller does not go back to the tool list and guess. Format from agntn/hashes
137
- * (#58). TypeBox stops at eight errors, so root keys are read off the arguments.
138
- *
139
- * @param tool - Tool whose schema applies.
140
- * @param args - Arguments as received from the host.
141
- * @returns {InputCheck<Input>} The typed value, or the failures, one per line.
142
- */
143
- export declare function validateInput<Input extends TObject>(tool: ToolDefinition<Input, unknown>, args: unknown): InputCheck<Input>;
144
- /**
145
- * Validates and runs a tool. Every adapter calls through here.
146
- *
147
- * Progress is best effort: a line after the call settles goes nowhere, and a host that throws on
148
- * one doesn't fail the call.
149
- *
150
- * @param tool - Tool to run.
151
- * @param args - Arguments as received from the host.
152
- * @param context - Per-call context.
153
- * @returns {Promise<ToolResult>} The executor's result, unchanged.
154
- * @throws {ToolInputError} When the arguments fail the schema.
155
- */
156
- export declare function invokeTool(tool: ToolDefinition, args: unknown, context?: ToolCallContext): Promise<ToolResult>;
157
- /**
158
- * Makes a value safe for one line of terminal or protocol text.
159
- *
160
- * Removes escape sequences, then replaces every control, format, line and
161
- * paragraph separator character with a space: a raw newline, U+2028 or a bidi
162
- * override (U+202E, a `Cf`) in an echoed value forges a line that reads as the
163
- * tool's own output. `String()` first, since hostile JSON ignores declared types.
164
- *
165
- * @param value - Value to render.
166
- * @returns {string} Single-line text.
167
- */
168
- export declare function sanitizeLine(value: unknown): string;
169
- /**
170
- * Text of a result, for hosts that carry failures as thrown errors.
171
- *
172
- * @param result - Tool result.
173
- * @returns {string} Text blocks joined by newlines.
174
- */
175
- export declare function resultText(result: ToolResult): string;
176
- export { type AddImmutable, type AddImmutableDeferred, type AddOptional, type AddOptionalDeferred, type AddReadonly, type AddReadonlyDeferred, type Any, type _Array_ as Array, type _Array_, type ArrayOptions, type BigInt, type BigIntPattern, type Boolean, type Broaden, type Call, type CallConstruct, type CanComposite, type Capitalize, type CapitalizeAction, type CapitalizeDeferred, type CapitalizeInstantiate, type Codec, type CollapseToObject, type Compare, type CompareResultDisjoint, type CompareResultEqual, type CompareResultLeftInside, type CompareResultRightInside, type Composite, type Conditional, type ConditionalAction, type ConditionalDeferred, type ConditionalInstantiate, type Constructor, type ConstructorOptions, type ConstructorParameters, type ConstructorParametersAction, type ConstructorParametersDeferred, type ConstructorParametersInstantiate, type ConvertToIntegerKey, type Cyclic, type CyclicCandidates, type CyclicCheck, type CyclicDependencies, type CyclicExtends, type CyclicOptions, type CyclicTarget, type Decode, type DecodeBuilder, type Deferred, type Dependent, type DependentOptions, type Distribute, type Encode, type EncodeBuilder, type Enum, type Evaluate, type EvaluateAction, type EvaluateDeferred, type EvaluateDependent, type EvaluateEnum, type EvaluateInstantiate, type EvaluateIntersect, type EvaluateTemplateLiteral, type EvaluateType, type EvaluateUnion, type EvaluateUnionFast, type Exclude, type ExcludeAction, type ExcludeDeferred, type ExcludeInstantiate, type Extends, type result_d_exports as ExtendsResult, type Extract, type ExtractAction, type ExtractDeferred, type ExtractInstantiate, type Flatten, type _Function_ as Function, type _Function_, type FunctionOptions, type Generic, type Identifier, type Immutable, type Index, type IndexAction, type IndexDeferred, type IndexInstantiate, type Infer, type InstanceType, type InstanceTypeAction, type InstanceTypeDeferred, type InstanceTypeInstantiate, type Instantiate, type InstantiateCyclic, type Integer, type IntegerKey, type IntegerPattern, type Interface, type InterfaceAction, type InterfaceDeferred, type InterfaceInstantiate, type Intersect, type IntersectOptions, type InvalidLiteralValue, type IsAny, type IsArray, type IsBigInt, type IsBoolean, type IsCall, type IsCodec, type IsConstructor, type IsCyclic, type IsDeferred, type IsDependent, type IsEnum, type IsEnumValue, type IsFunction, type IsGeneric, type IsIdentifier, type IsImmutable, type IsInfer, type IsInteger, type IsInterfaceDeferred, type IsIntersect, type IsKind, type IsLiteral, type IsLiteralBigInt, type IsLiteralBoolean, type IsLiteralNumber, type IsLiteralString, type IsLiteralValue, type IsNever, type IsNull, type IsNumber, type IsObject, type IsOptional, type IsParameter, type IsReadonly, type IsRecord, type IsRef, type IsRefine, type IsRefinement, type IsRest, type IsSchema, type IsString, type IsSymbol, type IsTemplateLiteral, type IsTemplateLiteralDeferred, type IsTemplateLiteralFinite, type IsTemplateLiteralPattern, type IsThis, type IsTuple, type IsTypeScriptEnumLike, type IsUndefined, type IsUnion, type IsUnknown, type IsUnsafe, type IsVoid, type KeyOf, type KeyOfAction, type KeyOfDeferred, type KeyOfInstantiate, type KeysToIndexer, type Literal, type LiteralTypeName, type Lowercase, type LowercaseAction, type LowercaseDeferred, type LowercaseInstantiate, type Mapped, type MappedAction, type MappedDeferred, type MappedInstantiate, type Module, type ModuleDeferred, type ModuleInstantiate, type Narrow, type Never, type NeverPattern, type NonNullable, type NonNullableAction, type NonNullableDeferred, type NonNullableInstantiate, type Null, type Number, type NumberKey, type NumberPattern, type _Object_ as Object, type _Object_, type ObjectOptions, type Omit, type OmitAction, type OmitDeferred, type OmitInstantiate, type Optional, type Parameter, type Parameters, type ParametersAction, type ParametersDeferred, type ParametersInstantiate, type ParsePatternIntoTypes, type ParseTemplateIntoTypes, type Partial, type PartialAction, type PartialDeferred, type PartialInstantiate, type Pick, type PickAction, type PickDeferred, type PickInstantiate, type Priority, type PropertyKeys, type PropertyValues, type Readonly, type ReadonlyObject, type ReadonlyObjectAction, type ReadonlyObjectDeferred, type ReadonlyObjectInstantiate, type ReadonlyType, type Record$1 as Record, type RecordAction, type RecordDeferred, type RecordFromPattern, type RecordInstantiate, type RecordKey, type RecordOptions, type RecordPattern, type RecordPatternToType, type RecordValue, type Ref, type RefInstantiate, type Refine, type RefineAdd, type RemoveImmutable, type RemoveImmutableDeferred, type RemoveOptional, type RemoveOptionalDeferred, type RemoveReadonly, type RemoveReadonlyDeferred, type Required, type RequiredAction, type RequiredArray, type RequiredDeferred, type RequiredInstantiate, type Rest, type ReturnType, type ReturnTypeAction, type ReturnTypeDeferred, type ReturnTypeInstantiate, type Script, type Static, type StaticAny, type StaticArray, type StaticBigInt, type StaticBoolean, type StaticCodec, type StaticConstructor, type StaticCyclic, type StaticDecode, type StaticDependent, type StaticDirection, type StaticEncode, type StaticEnum, type StaticEvaluate, type StaticFunction, type StaticInstantiatedParameters, type StaticInteger, type StaticIntersect, type StaticLiteral, type StaticNever, type StaticNull, type StaticNumber, type StaticObject, type StaticParse, type StaticProperties, type StaticRecord, type StaticRef, type StaticString, type StaticSymbol, type StaticTemplateLiteral, type StaticThis, type StaticTuple, type StaticType, type StaticUndefined, type StaticUnion, type StaticUnknown, type StaticUnsafe, type StaticVoid, type String, type StringKey, type StringPattern, type Symbol, type TAddImmutable, type TAddImmutableDeferred, type TAddOptional, type TAddOptionalDeferred, type TAddReadonly, type TAddReadonlyDeferred, type TAny, type TArray, type TArrayOptions, type TBigInt, type TBoolean, type TBroaden, type TCall, type TCallConstruct, type TCanComposite, type TCapitalize, type TCapitalizeAction, type TCapitalizeDeferred, type TCapitalizeInstantiate, type TCodec, type TCollapseToObject, type TCompare, type TCompareResult, type TComposite, type TConditional, type TConditionalAction, type TConditionalDeferred, type TConditionalInstantiate, type TConstructor, type TConstructorParameters, type TConstructorParametersAction, type TConstructorParametersDeferred, type TConstructorParametersInstantiate, type TConvertToIntegerKey, type TCyclic, type TCyclicCandidates, type TCyclicCheck, type TCyclicDependencies, type TCyclicExtends, type TCyclicTarget, type TDecodeCallback, type TDeferred, type TDependent, type TDistribute, type TEncodeCallback, type TEnum, type TEnumValue, type TEvaluate, type TEvaluateAction, type TEvaluateDeferred, type TEvaluateDependent, type TEvaluateEnum, type TEvaluateInstantiate, type TEvaluateIntersect, type TEvaluateTemplateLiteral, type TEvaluateType, type TEvaluateUnion, type TEvaluateUnionFast, type TExclude, type TExcludeAction, type TExcludeDeferred, type TExcludeInstantiate, type TExtends, type TExtract, type TExtractAction, type TExtractDeferred, type TExtractInstantiate, type TFlatten, type TFormat, type TFunction, type TGeneric, type TIdentifier, type TImmutable, type TIndex, type TIndexAction, type TIndexDeferred, type TIndexInstantiate, type TInfer, type TInstanceType, type TInstanceTypeAction, type TInstanceTypeDeferred, type TInstanceTypeInstantiate, type TInstantiate, type TInstantiateCyclic, type TInteger, type TIntegerKey, type TInterface, type TInterfaceAction, type TInterfaceDeferred, type TInterfaceInstantiate, type TIntersect, type TIntersectOptions, type TIsTemplateLiteralFinite, type TIsTemplateLiteralPattern, type TKeyOf, type TKeyOfAction, type TKeyOfDeferred, type TKeyOfInstantiate, type TKeysToIndexer, type TLiteral, type TLiteralTypeName, type TLiteralValue, type TLowercase, type TLowercaseAction, type TLowercaseDeferred, type TLowercaseInstantiate, type TMapped, type TMappedAction, type TMappedDeferred, type TMappedInstantiate, type TModule, type TModuleDeferred, type TModuleInstantiate, type TNarrow, type TNever, type TNonNullable, type TNonNullableAction, type TNonNullableDeferred, type TNonNullableInstantiate, type TNull, type TNumber, type TNumberKey, type TNumberOptions, type TObject, type TObjectOptions, type TOmit, type TOmitAction, type TOmitDeferred, type TOmitInstantiate, type TOptional, type TParameter, type TParameters, type TParametersAction, type TParametersDeferred, type TParametersInstantiate, type TParsePatternIntoTypes, type TParseTemplateIntoTypes, type TPartial, type TPartialAction, type TPartialDeferred, type TPartialInstantiate, type TPick, type TPickAction, type TPickDeferred, type TPickInstantiate, type TPriority, type TProperties, type TPropertyKeys, type TPropertyValues, type TReadonly, type TReadonlyObject, type TReadonlyObjectAction, type TReadonlyObjectDeferred, type TReadonlyObjectInstantiate, type TRecord, type TRecordAction, type TRecordDeferred, type TRecordInstantiate, type TRecordKey, type TRecordPattern, type TRecordPatternToType, type TRecordValue, type TRef, type TRefInstantiate, type TRefine, type TRefineAdd, type TRefineCheckCallback, type TRefineErrorCallback, type TRefinement, type TRemoveImmutable, type TRemoveImmutableDeferred, type TRemoveOptional, type TRemoveOptionalDeferred, type TRemoveReadonly, type TRemoveReadonlyDeferred, type TRequired, type TRequiredAction, type TRequiredArray, type TRequiredDeferred, type TRequiredInstantiate, type TRest, type TReturnType, type TReturnTypeAction, type TReturnTypeDeferred, type TReturnTypeInstantiate, type TSchema, type TSchemaOptions, type TScript, type TScriptOptions, type TStaticElements, type TString, type TStringKey, type TStringOptions, type TSymbol, type TTemplateLiteral, type TTemplateLiteralDecode, type TTemplateLiteralDecodeUnsafe, type TTemplateLiteralDeferred, type TTemplateLiteralEncode, type TTemplateLiteralFromString, type TTemplateLiteralFromTypes, type TTemplateLiteralStatic, type TThis, type TTuple, type TTupleOptions, type TTupleToIntersect, type TTupleToUnion, type TTypeScriptEnumLike, type TTypeScriptEnumToEnumValues, type TUncapitalize, type TUncapitalizeAction, type TUncapitalizeDeferred, type TUncapitalizeInstantiate, type TUndefined, type TUnion, type TUnionLast, type TUnionToIntersect, type TUnionToTuple, type TUnknown, type TUnsafe, type TUppercase, type TUppercaseAction, type TUppercaseDeferred, type TUppercaseInstantiate, type TVoid, type TWith, type TWithAction, type TWithDeferred, type TWithInstantiate, type TemplateLiteral, type TemplateLiteralCreate, type TemplateLiteralDecode, type TemplateLiteralDecodeUnsafe, type TemplateLiteralDeferred, type TemplateLiteralEncode, type TemplateLiteralFromString, type TemplateLiteralFromTypes, type This, type Tuple, type TupleOptions, index_d_exports as Type, type TypeScriptEnumToEnumValues, type Uncapitalize, type UncapitalizeAction, type UncapitalizeDeferred, type UncapitalizeInstantiate, type Undefined, type Union, type UnionOptions, type Unknown, type Unsafe, type Uppercase, type UppercaseAction, type UppercaseDeferred, type UppercaseInstantiate, type Void, type With, type WithAction, type WithDeferred, type WithInstantiate };
177
- //# sourceMappingURL=index.d.mts.map
1
+ import { AddImmutable, AddImmutableDeferred, AddOptional, AddOptionalDeferred, AddReadonly, AddReadonlyDeferred, Any, ArrayOptions, BigInt, BigIntPattern, Boolean, Broaden, Call, CallConstruct, CanComposite, Capitalize, CapitalizeAction, CapitalizeDeferred, CapitalizeInstantiate, Codec, CollapseToObject, Compare, CompareResultDisjoint, CompareResultEqual, CompareResultLeftInside, CompareResultRightInside, Composite, Conditional, ConditionalAction, ConditionalDeferred, ConditionalInstantiate, Constructor, ConstructorOptions, ConstructorParameters, ConstructorParametersAction, ConstructorParametersDeferred, ConstructorParametersInstantiate, ConvertToIntegerKey, Cyclic, CyclicCandidates, CyclicCheck, CyclicDependencies, CyclicExtends, CyclicOptions, CyclicTarget, Decode, DecodeBuilder, Deferred, Dependent, DependentOptions, Distribute, Encode, EncodeBuilder, Enum, Evaluate, EvaluateAction, EvaluateDeferred, EvaluateDependent, EvaluateEnum, EvaluateInstantiate, EvaluateIntersect, EvaluateTemplateLiteral, EvaluateType, EvaluateUnion, EvaluateUnionFast, Exclude, ExcludeAction, ExcludeDeferred, ExcludeInstantiate, Extends, Extract, ExtractAction, ExtractDeferred, ExtractInstantiate, Flatten, FunctionOptions, Generic, Identifier, Immutable, Index, IndexAction, IndexDeferred, IndexInstantiate, Infer, InstanceType, InstanceTypeAction, InstanceTypeDeferred, InstanceTypeInstantiate, Instantiate, InstantiateCyclic, Integer, IntegerKey, IntegerPattern, Interface, InterfaceAction, InterfaceDeferred, InterfaceInstantiate, Intersect, IntersectOptions, InvalidLiteralValue, IsAny, IsArray, IsBigInt, IsBoolean, IsCall, IsCodec, IsConstructor, IsCyclic, IsDeferred, IsDependent, IsEnum, IsEnumValue, IsFunction, IsGeneric, IsIdentifier, IsImmutable, IsInfer, IsInteger, IsInterfaceDeferred, IsIntersect, IsKind, IsLiteral, IsLiteralBigInt, IsLiteralBoolean, IsLiteralNumber, IsLiteralString, IsLiteralValue, IsNever, IsNull, IsNumber, IsObject, IsOptional, IsParameter, IsReadonly, IsRecord, IsRef, IsRefine, IsRefinement, IsRest, IsSchema, IsString, IsSymbol, IsTemplateLiteral, IsTemplateLiteralDeferred, IsTemplateLiteralFinite, IsTemplateLiteralPattern, IsThis, IsTuple, IsTypeScriptEnumLike, IsUndefined, IsUnion, IsUnknown, IsUnsafe, IsVoid, KeyOf, KeyOfAction, KeyOfDeferred, KeyOfInstantiate, KeysToIndexer, Literal, LiteralTypeName, Lowercase, LowercaseAction, LowercaseDeferred, LowercaseInstantiate, Mapped, MappedAction, MappedDeferred, MappedInstantiate, Module, ModuleDeferred, ModuleInstantiate, Narrow, Never, NeverPattern, NonNullable, NonNullableAction, NonNullableDeferred, NonNullableInstantiate, Null, Number, NumberKey, NumberPattern, ObjectOptions, Omit, OmitAction, OmitDeferred, OmitInstantiate, Optional, Parameter, Parameters, ParametersAction, ParametersDeferred, ParametersInstantiate, ParsePatternIntoTypes, ParseTemplateIntoTypes, Partial, PartialAction, PartialDeferred, PartialInstantiate, Pick, PickAction, PickDeferred, PickInstantiate, Priority, PropertyKeys, PropertyValues, Readonly, ReadonlyObject, ReadonlyObjectAction, ReadonlyObjectDeferred, ReadonlyObjectInstantiate, ReadonlyType, Record, RecordAction, RecordDeferred, RecordFromPattern, RecordInstantiate, RecordKey, RecordOptions, RecordPattern, RecordPatternToType, RecordValue, Ref, RefInstantiate, Refine, RefineAdd, RemoveImmutable, RemoveImmutableDeferred, RemoveOptional, RemoveOptionalDeferred, RemoveReadonly, RemoveReadonlyDeferred, Required, RequiredAction, RequiredArray, RequiredDeferred, RequiredInstantiate, Rest, ReturnType, ReturnTypeAction, ReturnTypeDeferred, ReturnTypeInstantiate, Script, Static, StaticAny, StaticArray, StaticBigInt, StaticBoolean, StaticCodec, StaticConstructor, StaticCyclic, StaticDecode, StaticDependent, StaticDirection, StaticEncode, StaticEnum, StaticEvaluate, StaticFunction, StaticInstantiatedParameters, StaticInteger, StaticIntersect, StaticLiteral, StaticNever, StaticNull, StaticNumber, StaticObject, StaticParse, StaticProperties, StaticRecord, StaticRef, StaticString, StaticSymbol, StaticTemplateLiteral, StaticThis, StaticTuple, StaticType, StaticUndefined, StaticUnion, StaticUnknown, StaticUnsafe, StaticVoid, String, StringKey, StringPattern, Symbol, TAddImmutable, TAddImmutableDeferred, TAddOptional, TAddOptionalDeferred, TAddReadonly, TAddReadonlyDeferred, TAny, TArray, TArrayOptions, TBigInt, TBoolean, TBroaden, TCall, TCallConstruct, TCanComposite, TCapitalize, TCapitalizeAction, TCapitalizeDeferred, TCapitalizeInstantiate, TCodec, TCollapseToObject, TCompare, TCompareResult, TComposite, TConditional, TConditionalAction, TConditionalDeferred, TConditionalInstantiate, TConstructor, TConstructorParameters, TConstructorParametersAction, TConstructorParametersDeferred, TConstructorParametersInstantiate, TConvertToIntegerKey, TCyclic, TCyclicCandidates, TCyclicCheck, TCyclicDependencies, TCyclicExtends, TCyclicTarget, TDecodeCallback, TDeferred, TDependent, TDistribute, TEncodeCallback, TEnum, TEnumValue, TEvaluate, TEvaluateAction, TEvaluateDeferred, TEvaluateDependent, TEvaluateEnum, TEvaluateInstantiate, TEvaluateIntersect, TEvaluateTemplateLiteral, TEvaluateType, TEvaluateUnion, TEvaluateUnionFast, TExclude, TExcludeAction, TExcludeDeferred, TExcludeInstantiate, TExtends, TExtract, TExtractAction, TExtractDeferred, TExtractInstantiate, TFlatten, TFormat, TFunction, TGeneric, TIdentifier, TImmutable, TIndex, TIndexAction, TIndexDeferred, TIndexInstantiate, TInfer, TInstanceType, TInstanceTypeAction, TInstanceTypeDeferred, TInstanceTypeInstantiate, TInstantiate, TInstantiateCyclic, TInteger, TIntegerKey, TInterface, TInterfaceAction, TInterfaceDeferred, TInterfaceInstantiate, TIntersect, TIntersectOptions, TIsTemplateLiteralFinite, TIsTemplateLiteralPattern, TKeyOf, TKeyOfAction, TKeyOfDeferred, TKeyOfInstantiate, TKeysToIndexer, TLiteral, TLiteralTypeName, TLiteralValue, TLowercase, TLowercaseAction, TLowercaseDeferred, TLowercaseInstantiate, TMapped, TMappedAction, TMappedDeferred, TMappedInstantiate, TModule, TModuleDeferred, TModuleInstantiate, TNarrow, TNever, TNonNullable, TNonNullableAction, TNonNullableDeferred, TNonNullableInstantiate, TNull, TNumber, TNumberKey, TNumberOptions, TObject, TObjectOptions, TOmit, TOmitAction, TOmitDeferred, TOmitInstantiate, TOptional, TParameter, TParameters, TParametersAction, TParametersDeferred, TParametersInstantiate, TParsePatternIntoTypes, TParseTemplateIntoTypes, TPartial, TPartialAction, TPartialDeferred, TPartialInstantiate, TPick, TPickAction, TPickDeferred, TPickInstantiate, TPriority, TProperties, TPropertyKeys, TPropertyValues, TReadonly, TReadonlyObject, TReadonlyObjectAction, TReadonlyObjectDeferred, TReadonlyObjectInstantiate, TRecord, TRecordAction, TRecordDeferred, TRecordInstantiate, TRecordKey, TRecordPattern, TRecordPatternToType, TRecordValue, TRef, TRefInstantiate, TRefine, TRefineAdd, TRefineCheckCallback, TRefineErrorCallback, TRefinement, TRemoveImmutable, TRemoveImmutableDeferred, TRemoveOptional, TRemoveOptionalDeferred, TRemoveReadonly, TRemoveReadonlyDeferred, TRequired, TRequiredAction, TRequiredArray, TRequiredDeferred, TRequiredInstantiate, TRest, TReturnType, TReturnTypeAction, TReturnTypeDeferred, TReturnTypeInstantiate, TSchema, TSchemaOptions, TScript, TScriptOptions, TStaticElements, TString, TStringKey, TStringOptions, TSymbol, TTemplateLiteral, TTemplateLiteralDecode, TTemplateLiteralDecodeUnsafe, TTemplateLiteralDeferred, TTemplateLiteralEncode, TTemplateLiteralFromString, TTemplateLiteralFromTypes, TTemplateLiteralStatic, TThis, TTuple, TTupleOptions, TTupleToIntersect, TTupleToUnion, TTypeScriptEnumLike, TTypeScriptEnumToEnumValues, TUncapitalize, TUncapitalizeAction, TUncapitalizeDeferred, TUncapitalizeInstantiate, TUndefined, TUnion, TUnionLast, TUnionToIntersect, TUnionToTuple, TUnknown, TUnsafe, TUppercase, TUppercaseAction, TUppercaseDeferred, TUppercaseInstantiate, TVoid, TWith, TWithAction, TWithDeferred, TWithInstantiate, TemplateLiteral, TemplateLiteralCreate, TemplateLiteralDecode, TemplateLiteralDecodeUnsafe, TemplateLiteralDeferred, TemplateLiteralEncode, TemplateLiteralFromString, TemplateLiteralFromTypes, This, Tuple, TupleOptions, TypeScriptEnumToEnumValues, Uncapitalize, UncapitalizeAction, UncapitalizeDeferred, UncapitalizeInstantiate, Undefined, Union, UnionOptions, Unknown, Unsafe, Uppercase, UppercaseAction, UppercaseDeferred, UppercaseInstantiate, Void, With, WithAction, WithDeferred, WithInstantiate, _Array_, _Function_, _Object_, index_d_exports, result_d_exports } from "./_chunks/libs/typebox.mjs";
2
+ import { Icon, InputCheck, ToolCallContext, ToolCliHints, ToolContent, ToolDefinition, ToolDefinitionError, ToolEffect, ToolInputError, ToolProgress, ToolResult, defineTool, indexTools, invokeTool, resultText, sanitizeLine, sanitizeText, validateInput, wireSchema } from "./_chunks/index.mjs";
3
+ export { type AddImmutable, type AddImmutableDeferred, type AddOptional, type AddOptionalDeferred, type AddReadonly, type AddReadonlyDeferred, type Any, type _Array_ as Array, type _Array_, type ArrayOptions, type BigInt, type BigIntPattern, type Boolean, type Broaden, type Call, type CallConstruct, type CanComposite, type Capitalize, type CapitalizeAction, type CapitalizeDeferred, type CapitalizeInstantiate, type Codec, type CollapseToObject, type Compare, type CompareResultDisjoint, type CompareResultEqual, type CompareResultLeftInside, type CompareResultRightInside, type Composite, type Conditional, type ConditionalAction, type ConditionalDeferred, type ConditionalInstantiate, type Constructor, type ConstructorOptions, type ConstructorParameters, type ConstructorParametersAction, type ConstructorParametersDeferred, type ConstructorParametersInstantiate, type ConvertToIntegerKey, type Cyclic, type CyclicCandidates, type CyclicCheck, type CyclicDependencies, type CyclicExtends, type CyclicOptions, type CyclicTarget, type Decode, type DecodeBuilder, type Deferred, type Dependent, type DependentOptions, type Distribute, type Encode, type EncodeBuilder, type Enum, type Evaluate, type EvaluateAction, type EvaluateDeferred, type EvaluateDependent, type EvaluateEnum, type EvaluateInstantiate, type EvaluateIntersect, type EvaluateTemplateLiteral, type EvaluateType, type EvaluateUnion, type EvaluateUnionFast, type Exclude, type ExcludeAction, type ExcludeDeferred, type ExcludeInstantiate, type Extends, type result_d_exports as ExtendsResult, type Extract, type ExtractAction, type ExtractDeferred, type ExtractInstantiate, type Flatten, type _Function_ as Function, type _Function_, type FunctionOptions, type Generic, Icon, type Identifier, type Immutable, type Index, type IndexAction, type IndexDeferred, type IndexInstantiate, type Infer, InputCheck, type InstanceType, type InstanceTypeAction, type InstanceTypeDeferred, type InstanceTypeInstantiate, type Instantiate, type InstantiateCyclic, type Integer, type IntegerKey, type IntegerPattern, type Interface, type InterfaceAction, type InterfaceDeferred, type InterfaceInstantiate, type Intersect, type IntersectOptions, type InvalidLiteralValue, type IsAny, type IsArray, type IsBigInt, type IsBoolean, type IsCall, type IsCodec, type IsConstructor, type IsCyclic, type IsDeferred, type IsDependent, type IsEnum, type IsEnumValue, type IsFunction, type IsGeneric, type IsIdentifier, type IsImmutable, type IsInfer, type IsInteger, type IsInterfaceDeferred, type IsIntersect, type IsKind, type IsLiteral, type IsLiteralBigInt, type IsLiteralBoolean, type IsLiteralNumber, type IsLiteralString, type IsLiteralValue, type IsNever, type IsNull, type IsNumber, type IsObject, type IsOptional, type IsParameter, type IsReadonly, type IsRecord, type IsRef, type IsRefine, type IsRefinement, type IsRest, type IsSchema, type IsString, type IsSymbol, type IsTemplateLiteral, type IsTemplateLiteralDeferred, type IsTemplateLiteralFinite, type IsTemplateLiteralPattern, type IsThis, type IsTuple, type IsTypeScriptEnumLike, type IsUndefined, type IsUnion, type IsUnknown, type IsUnsafe, type IsVoid, type KeyOf, type KeyOfAction, type KeyOfDeferred, type KeyOfInstantiate, type KeysToIndexer, type Literal, type LiteralTypeName, type Lowercase, type LowercaseAction, type LowercaseDeferred, type LowercaseInstantiate, type Mapped, type MappedAction, type MappedDeferred, type MappedInstantiate, type Module, type ModuleDeferred, type ModuleInstantiate, type Narrow, type Never, type NeverPattern, type NonNullable, type NonNullableAction, type NonNullableDeferred, type NonNullableInstantiate, type Null, type Number, type NumberKey, type NumberPattern, type _Object_ as Object, type _Object_, type ObjectOptions, type Omit, type OmitAction, type OmitDeferred, type OmitInstantiate, type Optional, type Parameter, type Parameters, type ParametersAction, type ParametersDeferred, type ParametersInstantiate, type ParsePatternIntoTypes, type ParseTemplateIntoTypes, type Partial, type PartialAction, type PartialDeferred, type PartialInstantiate, type Pick, type PickAction, type PickDeferred, type PickInstantiate, type Priority, type PropertyKeys, type PropertyValues, type Readonly, type ReadonlyObject, type ReadonlyObjectAction, type ReadonlyObjectDeferred, type ReadonlyObjectInstantiate, type ReadonlyType, type Record, type RecordAction, type RecordDeferred, type RecordFromPattern, type RecordInstantiate, type RecordKey, type RecordOptions, type RecordPattern, type RecordPatternToType, type RecordValue, type Ref, type RefInstantiate, type Refine, type RefineAdd, type RemoveImmutable, type RemoveImmutableDeferred, type RemoveOptional, type RemoveOptionalDeferred, type RemoveReadonly, type RemoveReadonlyDeferred, type Required, type RequiredAction, type RequiredArray, type RequiredDeferred, type RequiredInstantiate, type Rest, type ReturnType, type ReturnTypeAction, type ReturnTypeDeferred, type ReturnTypeInstantiate, type Script, type Static, type StaticAny, type StaticArray, type StaticBigInt, type StaticBoolean, type StaticCodec, type StaticConstructor, type StaticCyclic, type StaticDecode, type StaticDependent, type StaticDirection, type StaticEncode, type StaticEnum, type StaticEvaluate, type StaticFunction, type StaticInstantiatedParameters, type StaticInteger, type StaticIntersect, type StaticLiteral, type StaticNever, type StaticNull, type StaticNumber, type StaticObject, type StaticParse, type StaticProperties, type StaticRecord, type StaticRef, type StaticString, type StaticSymbol, type StaticTemplateLiteral, type StaticThis, type StaticTuple, type StaticType, type StaticUndefined, type StaticUnion, type StaticUnknown, type StaticUnsafe, type StaticVoid, type String, type StringKey, type StringPattern, type Symbol, type TAddImmutable, type TAddImmutableDeferred, type TAddOptional, type TAddOptionalDeferred, type TAddReadonly, type TAddReadonlyDeferred, type TAny, type TArray, type TArrayOptions, type TBigInt, type TBoolean, type TBroaden, type TCall, type TCallConstruct, type TCanComposite, type TCapitalize, type TCapitalizeAction, type TCapitalizeDeferred, type TCapitalizeInstantiate, type TCodec, type TCollapseToObject, type TCompare, type TCompareResult, type TComposite, type TConditional, type TConditionalAction, type TConditionalDeferred, type TConditionalInstantiate, type TConstructor, type TConstructorParameters, type TConstructorParametersAction, type TConstructorParametersDeferred, type TConstructorParametersInstantiate, type TConvertToIntegerKey, type TCyclic, type TCyclicCandidates, type TCyclicCheck, type TCyclicDependencies, type TCyclicExtends, type TCyclicTarget, type TDecodeCallback, type TDeferred, type TDependent, type TDistribute, type TEncodeCallback, type TEnum, type TEnumValue, type TEvaluate, type TEvaluateAction, type TEvaluateDeferred, type TEvaluateDependent, type TEvaluateEnum, type TEvaluateInstantiate, type TEvaluateIntersect, type TEvaluateTemplateLiteral, type TEvaluateType, type TEvaluateUnion, type TEvaluateUnionFast, type TExclude, type TExcludeAction, type TExcludeDeferred, type TExcludeInstantiate, type TExtends, type TExtract, type TExtractAction, type TExtractDeferred, type TExtractInstantiate, type TFlatten, type TFormat, type TFunction, type TGeneric, type TIdentifier, type TImmutable, type TIndex, type TIndexAction, type TIndexDeferred, type TIndexInstantiate, type TInfer, type TInstanceType, type TInstanceTypeAction, type TInstanceTypeDeferred, type TInstanceTypeInstantiate, type TInstantiate, type TInstantiateCyclic, type TInteger, type TIntegerKey, type TInterface, type TInterfaceAction, type TInterfaceDeferred, type TInterfaceInstantiate, type TIntersect, type TIntersectOptions, type TIsTemplateLiteralFinite, type TIsTemplateLiteralPattern, type TKeyOf, type TKeyOfAction, type TKeyOfDeferred, type TKeyOfInstantiate, type TKeysToIndexer, type TLiteral, type TLiteralTypeName, type TLiteralValue, type TLowercase, type TLowercaseAction, type TLowercaseDeferred, type TLowercaseInstantiate, type TMapped, type TMappedAction, type TMappedDeferred, type TMappedInstantiate, type TModule, type TModuleDeferred, type TModuleInstantiate, type TNarrow, type TNever, type TNonNullable, type TNonNullableAction, type TNonNullableDeferred, type TNonNullableInstantiate, type TNull, type TNumber, type TNumberKey, type TNumberOptions, type TObject, type TObjectOptions, type TOmit, type TOmitAction, type TOmitDeferred, type TOmitInstantiate, type TOptional, type TParameter, type TParameters, type TParametersAction, type TParametersDeferred, type TParametersInstantiate, type TParsePatternIntoTypes, type TParseTemplateIntoTypes, type TPartial, type TPartialAction, type TPartialDeferred, type TPartialInstantiate, type TPick, type TPickAction, type TPickDeferred, type TPickInstantiate, type TPriority, type TProperties, type TPropertyKeys, type TPropertyValues, type TReadonly, type TReadonlyObject, type TReadonlyObjectAction, type TReadonlyObjectDeferred, type TReadonlyObjectInstantiate, type TRecord, type TRecordAction, type TRecordDeferred, type TRecordInstantiate, type TRecordKey, type TRecordPattern, type TRecordPatternToType, type TRecordValue, type TRef, type TRefInstantiate, type TRefine, type TRefineAdd, type TRefineCheckCallback, type TRefineErrorCallback, type TRefinement, type TRemoveImmutable, type TRemoveImmutableDeferred, type TRemoveOptional, type TRemoveOptionalDeferred, type TRemoveReadonly, type TRemoveReadonlyDeferred, type TRequired, type TRequiredAction, type TRequiredArray, type TRequiredDeferred, type TRequiredInstantiate, type TRest, type TReturnType, type TReturnTypeAction, type TReturnTypeDeferred, type TReturnTypeInstantiate, type TSchema, type TSchemaOptions, type TScript, type TScriptOptions, type TStaticElements, type TString, type TStringKey, type TStringOptions, type TSymbol, type TTemplateLiteral, type TTemplateLiteralDecode, type TTemplateLiteralDecodeUnsafe, type TTemplateLiteralDeferred, type TTemplateLiteralEncode, type TTemplateLiteralFromString, type TTemplateLiteralFromTypes, type TTemplateLiteralStatic, type TThis, type TTuple, type TTupleOptions, type TTupleToIntersect, type TTupleToUnion, type TTypeScriptEnumLike, type TTypeScriptEnumToEnumValues, type TUncapitalize, type TUncapitalizeAction, type TUncapitalizeDeferred, type TUncapitalizeInstantiate, type TUndefined, type TUnion, type TUnionLast, type TUnionToIntersect, type TUnionToTuple, type TUnknown, type TUnsafe, type TUppercase, type TUppercaseAction, type TUppercaseDeferred, type TUppercaseInstantiate, type TVoid, type TWith, type TWithAction, type TWithDeferred, type TWithInstantiate, type TemplateLiteral, type TemplateLiteralCreate, type TemplateLiteralDecode, type TemplateLiteralDecodeUnsafe, type TemplateLiteralDeferred, type TemplateLiteralEncode, type TemplateLiteralFromString, type TemplateLiteralFromTypes, type This, ToolCallContext, ToolCliHints, ToolContent, ToolDefinition, ToolDefinitionError, ToolEffect, ToolInputError, ToolProgress, ToolResult, type Tuple, type TupleOptions, index_d_exports as Type, type TypeScriptEnumToEnumValues, type Uncapitalize, type UncapitalizeAction, type UncapitalizeDeferred, type UncapitalizeInstantiate, type Undefined, type Union, type UnionOptions, type Unknown, type Unsafe, type Uppercase, type UppercaseAction, type UppercaseDeferred, type UppercaseInstantiate, type Void, type With, type WithAction, type WithDeferred, type WithInstantiate, defineTool, indexTools, invokeTool, resultText, sanitizeLine, sanitizeText, validateInput, wireSchema };
package/dist/index.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  import { type_exports } from "./_chunks/libs/typebox.mjs";
2
- import { ToolDefinitionError, ToolInputError, defineTool, indexTools, invokeTool, resultText, sanitizeLine, validateInput, wireSchema } from "./_chunks/src.mjs";
3
- export { ToolDefinitionError, ToolInputError, type_exports as Type, defineTool, indexTools, invokeTool, resultText, sanitizeLine, validateInput, wireSchema };
2
+ import { ToolDefinitionError, ToolInputError, defineTool, indexTools, invokeTool, resultText, sanitizeLine, sanitizeText, validateInput, wireSchema } from "./_chunks/src.mjs";
3
+ export { ToolDefinitionError, ToolInputError, type_exports as Type, defineTool, indexTools, invokeTool, resultText, sanitizeLine, sanitizeText, validateInput, wireSchema };
package/dist/mcp.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { ToolCallContext, ToolDefinition } from "./index.mjs";
1
+ import { Icon, ToolCallContext, ToolDefinition } from "./_chunks/index.mjs";
2
2
  import { CallToolResult, Server, Tool, ToolAnnotations } from "@modelcontextprotocol/server";
3
3
  interface McpServerInfo {
4
4
  /** Server name, also used in the unknown-tool message. */
@@ -6,6 +6,9 @@ interface McpServerInfo {
6
6
  readonly version: string;
7
7
  /** Display name for clients that show one, such as `Forges`. */
8
8
  readonly title?: string;
9
+ /** One line under the name on a connector card or in a registry. */
10
+ readonly description?: string;
11
+ readonly icons?: readonly Icon[];
9
12
  /** Project home a client can link to. */
10
13
  readonly websiteUrl?: string;
11
14
  }
@@ -32,7 +35,7 @@ export declare function errorResult(...lines: readonly string[]): CallToolResult
32
35
  * The entries `tools/list` answers with, in the order given.
33
36
  *
34
37
  * @param tools - Tools to list.
35
- * @returns {Tool[]} Name, title, description, schema and annotations of each tool.
38
+ * @returns {Tool[]} Name, title, description, icons, schema and annotations of each tool.
36
39
  * @throws {ToolDefinitionError} When two tools share a name.
37
40
  */
38
41
  export declare function listTools(tools: readonly ToolDefinition[]): Tool[];
@@ -63,7 +66,7 @@ export declare function callTool(info: Pick<McpServerInfo, "name">, tools: reado
63
66
  *
64
67
  * A progress notification that fails to send goes to `onerror`, never to the tool.
65
68
  *
66
- * @param info - Server name, version and optional title and website, sent to the client as given.
69
+ * @param info - Name, version and optional title, description, icons and website, sent as given.
67
70
  * @param tools - Tools to serve.
68
71
  * @returns {Server} Unconnected MCP server.
69
72
  * @throws {ToolDefinitionError} When two tools share a name.
@@ -1 +1 @@
1
- {"version":3,"file":"mcp.d.mts","names":[],"sources":["../src/mcp-answers.ts","../src/mcp.ts"],"mappings":";;UAmBiB;;WAEN;WACA;;WAEA;;WAEA;;;;;;;;wBASK,gBAAgB,MAAM,iBAAiB;;;;;;;;;;;;wBAqBvC,eAAe,2BAA2B;;;;;;;;wBAW1C,UAAU,gBAAgB,mBAAmB;;;;;;;;;;;wBAqBvC,SACpB,MAAM,KAAK,wBACX,gBAAgB,kBAChB,cACA,gBACA,UAAS,kBACR,QAAQ;;;;;;;;;;;;;;;;;;;;;;wBClDK,gBAAgB,MAAM,eAAe,gBAAgB,mBAAmB"}
1
+ {"version":3,"file":"mcp.d.mts","names":[],"sources":["../src/mcp-answers.ts","../src/mcp.ts"],"mappings":";;UAoBiB;;WAEN;WACA;;WAEA;;WAEA;WACA,iBAAiB;;WAEjB;;;;;;;;wBASK,gBAAgB,MAAM,iBAAiB;;;;;;;;;;;;wBAqBvC,eAAe,2BAA2B;;;;;;;;wBAW1C,UAAU,gBAAgB,mBAAmB;;;;;;;;;;;wBAkCvC,SACpB,MAAM,KAAK,wBACX,gBAAgB,kBAChB,cACA,gBACA,UAAS,kBACR,QAAQ;;;;;;;;;;;;;;;;;;;;;;wBClEK,gBAAgB,MAAM,eAAe,gBAAgB,mBAAmB"}
package/dist/mcp.mjs CHANGED
@@ -1,13 +1,15 @@
1
1
  import { indexTools } from "./_chunks/src.mjs";
2
- import { callTool, errorResult, listTools, progressSteps, toolAnnotations } from "./_chunks/mcp-answers.mjs";
2
+ import { callTool, copyIcons, errorResult, listTools, progressSteps, toolAnnotations } from "./_chunks/mcp-answers.mjs";
3
3
  import { Server } from "@modelcontextprotocol/server";
4
4
  function createMcpServer(info, tools) {
5
5
  indexTools(tools);
6
- const { name, version, title, websiteUrl } = info;
6
+ const { name, version, title, description, icons, websiteUrl } = info;
7
7
  const server = new Server({
8
8
  name,
9
9
  version,
10
10
  title,
11
+ description,
12
+ ...icons === void 0 ? {} : { icons: copyIcons(icons) },
11
13
  websiteUrl
12
14
  }, { capabilities: { tools: {} } });
13
15
  server.setRequestHandler("tools/list", () => ({ tools: listTools(tools) }));