Core API
Every export of @miragon/mcp-toolkit-tool-codegen-core, the runtime of the generated tools.ts: what it takes, what it returns and how it fails.
- Package
@miragon/mcp-toolkit-tool-codegen-core- Install
pnpm add @miragon/mcp-toolkit-tool-codegen-core@4- Imported by
- the generated
tools.tsand@miragon/mcp-toolkit-tool-codegen-react - Runs in
- Node, browsers and MCP Apps widgets: no React, no Node APIs, no dependencies
- Module
- ESM only. The declarations name the global
AbortSignal: compile with the DOM library or@types/node.
Exports
| Export | Kind | What it is |
|---|---|---|
createTypedCallTool | function | types a ToolCaller by a tool map |
toolCallerFromClient | function | a ToolCaller over an MCP SDK client |
parseToolResult | function | decodes a tool result into the tool's output |
isToolCallError | function | true for a ToolCallError, also one from another copy |
ToolCallError | class | the tool ran and answered isError: true |
ToolCaller | type | calls a tool by name and resolves with its raw result |
ToolCallResult | type | the part of an MCP CallToolResult the runtime reads |
ToolCallOptions | type | the options of one call: signal, timeouts, progress |
ToolCallProgress | type | one progress notification of a running call |
McpClientLike | type | the client shape toolCallerFromClient takes |
TypedCallTool | type | a tool call typed by a tool map |
ToolShape | type | one entry of a tool map: { input; output } |
ToolMapOf | type | the constraint every tool map meets |
ToolName | type | the tool names of a map |
ToolInput | type | the input of one tool of a map |
ToolOutput | type | the output of one tool of a map |
ParseToolResultOptions | type | the options of parseToolResult: text |
Functions
Each function lists its parameters, then what it returns, how it fails and what it leaves to you.
createTypedCallTool
function createTypedCallTool<TMap extends ToolMapOf<TMap>>(
callTool: ToolCaller,
): TypedCallTool<TMap>| Parameter | Type | Meaning |
|---|---|---|
TMap | type parameter | the tool map, such as the generated <Name>ToolMap; see ToolMapOf |
callTool | ToolCaller | the function every call goes through |
- Returns a
TypedCallTool<TMap>. Each call passes its name, args and options tocallToolas given and decodes the result withparseToolResult. The generatedcreate<Name>Clientis built on it: the client'scallis this function. - Rejects with a
ToolCallErrorwhen the result hasisError: true, and with whatevercallToolthrew or rejected with, unchanged, for anything else (transport, protocol, abort). AcallToolthat throws synchronously rejects the call too. - Leaves the output unchecked at run time: its type is what the map claims.
import { createTypedCallTool } from "@miragon/mcp-toolkit-tool-codegen-core"
interface Task {
id: string
title: string
done: boolean
}
interface TasksToolMap {
"list-tasks": { input: { done?: boolean }; output: { tasks: Task[] } }
"add-task": { input: { title: string }; output: Task }
}
const call = createTypedCallTool<TasksToolMap>(callTool)
await call("list-tasks", {}) // Promise<{ tasks: Task[] }>
await call("list_tasks", {}) // compile error: no tool of the map
await call("add-task", {}) // compile error: title is missingtoolCallerFromClient
function toolCallerFromClient(client: McpClientLike): ToolCaller| Parameter | Type | Meaning |
|---|---|---|
client | McpClientLike | a connected MCP client, such as Client from @modelcontextprotocol/client |
- Returns a
ToolCallerthat maps each call ontoclient.callTool({ name, arguments: args }, options), theToolCallOptionshanded on as given. They carry the SDK's own names, so the SDK implements the signal, the timeouts and the progress callback. - Rejects with whatever
client.callToolrejects with. - Leaves connecting and closing the client to you. The package does not depend on the MCP SDK: any object of the shape fits.
import { toolCallerFromClient } from "@miragon/mcp-toolkit-tool-codegen-core"
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"
import { createTasksClient } from "./generated/tools.js"
const client = new Client({ name: "tasks-script", version: "1.0.0" })
await client.connect(new StreamableHTTPClientTransport(new URL("http://localhost:4000/mcp")))
const tasks = createTasksClient(toolCallerFromClient(client))The v1 SDK's Client (@modelcontextprotocol/sdk) takes a result schema before the options and does not fit McpClientLike; Call tools from Node and the browser shows the one-line adapter.
parseToolResult
function parseToolResult<T = unknown>(
toolName: string,
result: ToolCallResult,
options?: ParseToolResultOptions,
): T| Parameter | Type | Meaning |
|---|---|---|
T | type parameter | the output the caller claims; not checked at run time |
toolName | string | the tool's name, for the ToolCallError |
result | ToolCallResult | the raw result |
options | ParseToolResultOptions | how to read a text block; default { text: "json" } |
Returns the output by the first rule that applies:
# The result has The output 1 isError: truenone: throws a ToolCallError2 structuredContentnotundefinedstructuredContentas it is, alsonull,0,falseor""3 a text block ( { type: "text", text })the first one, other blocks skipped: its JSON value, or the string when it is not JSON; with text: "raw"always the string4 no text block undefinedThrows a
ToolCallErrorby rule 1, and nothing else.Leaves plain text that happens to be JSON changed by rule 3. Every typed call applies it with the default
"json", and the generator has no option to change that; see Guarantees and limits.
const text = (value: string) => ({ content: [{ type: "text", text: value }] })
parseToolResult("get-version", text("2.10")) // 2.1, a number
parseToolResult("get-version", text("2.10"), { text: "raw" }) // "2.10"
parseToolResult("get-version", text("Hello")) // "Hello": not JSON, so the string
parseToolResult("get-version", { content: [] }) // undefinedTo keep a plain-text answer as it is, decode it yourself: parseToolResult<string>(name, await callTool(name, args), { text: "raw" }).
isToolCallError
function isToolCallError(error: unknown): error is ToolCallError| Parameter | Type | Meaning |
|---|---|---|
error | unknown | what a call rejected with |
- Returns
truefor aToolCallError, also one thrown by another copy of this package in the same bundle or realm, whereinstanceoffails. It reads a brand underSymbol.for("@miragon/mcp-toolkit-tool-codegen-core/ToolCallError"). - Never throws.
- Leaves every other error to you: it returns
falsefor transport, protocol and abort errors.
Classes
ToolCallError
class ToolCallError extends Error {
constructor(toolName: string, result: ToolCallResult)
readonly name: "ToolCallError"
readonly toolName: string
readonly result: ToolCallResult
}| Property | Value |
|---|---|
name | "ToolCallError" |
toolName | the tool that answered |
result | the raw result, isError: true included |
message | the texts of the result's text blocks, joined by line breaks and trimmed; without any text, Tool "<toolName>" reported an error |
parseToolResult throws it, so every typed call and every hook rejects with it when the tool ran and answered isError: true. A transport or protocol failure is never a ToolCallError. Recognise one with isToolCallError rather than instanceof:
import { isToolCallError } from "@miragon/mcp-toolkit-tool-codegen-core"
try {
await tasks.getTask({ id: "task-404" })
} catch (error) {
if (!isToolCallError(error)) throw error
console.log(error.toolName) // "get-task"
console.log(error.message) // 'No task with id "task-404".'
}Types
Each type shows its definition, then what it promises and where it is used.
ToolCaller
type ToolCaller = (
name: string,
args: Record<string, unknown>,
options?: ToolCallOptions,
) => Promise<ToolCallResult>Calls the tool name with args and resolves with its raw result. A tool that reports a failure resolves with isError: true; only a transport or protocol failure rejects. It hands options to the transport, so an aborted signal cancels the request and a timeout fails it. A caller other than toolCallerFromClient honours the options it supports. toolCallerFromClient makes one from an MCP client; a widget host bridge or a test fake can be one too. createTypedCallTool, the generated create<Name>Client and the React package's ToolCallerProvider take it.
ToolCallResult
interface ToolCallResult {
content?: readonly unknown[]
structuredContent?: unknown
isError?: boolean
}Structural, so the MCP SDK's CallToolResult and a widget host's tool result fit as they are. parseToolResult reads only these three fields.
ToolCallOptions
interface ToolCallOptions {
signal?: AbortSignal
timeout?: number
onprogress?: (progress: ToolCallProgress) => void
resetTimeoutOnProgress?: boolean
maxTotalTimeout?: number
}The per-request options of the MCP SDK client (RequestOptions in @modelcontextprotocol/client), by name and meaning. The runtime hands them to the caller untouched and reads none of them; toolCallerFromClient passes them to the SDK, which implements them.
| Option | Meaning | SDK default |
|---|---|---|
signal | Cancels the call. | none |
timeout | Milliseconds to wait for the result; then the call rejects with Request timed out. | 60000 |
onprogress | Receives each progress notification the server sends for this call. Setting it asks the server for them. | none |
resetTimeoutOnProgress | Starts timeout again with every progress notification. Needs onprogress: without it the server sends none. | false |
maxTotalTimeout | Milliseconds the call may take in all, however often progress starts timeout again; see below. | no limit |
A tool that runs longer than a minute needs a timeout, or progress notifications with resetTimeoutOnProgress; see Give a long call more time.
The SDK checks maxTotalTimeout only when a progress notification starts timeout again, and before each further round of a call that asks the client for input. The first check past it rejects the call with Maximum total timeout exceeded, so a call can run up to one timeout past it. Without resetTimeoutOnProgress, an ordinary call never reaches such a check: timeout alone limits it.
ToolCallProgress
interface ToolCallProgress {
progress: number
total?: number
message?: string
}One notifications/progress of a running call, as onprogress receives it: the progress so far, which grows with every notification, the total when the server knows it, and a message when it sends one.
McpClientLike
interface McpClientLike {
callTool(
params: { name: string; arguments?: Record<string, unknown> },
options?: ToolCallOptions,
): Promise<ToolCallResult>
}The part of an MCP client toolCallerFromClient uses. Client from @modelcontextprotocol/client, the v2 SDK, fits as it is.
TypedCallTool
type TypedCallTool<TMap extends ToolMapOf<TMap>> = <TName extends ToolName<TMap>>(
name: TName,
args: ToolInput<TMap, TName>,
options?: ToolCallOptions,
) => Promise<ToolOutput<TMap, TName>>The name picks the input the call takes and the output it resolves with. The generated <Name>CallTool is TypedCallTool<<Name>ToolMap>. Pass a literal name: with a union of names (which: "a" | "b") the args are typed as the union of both inputs, so args that fit only one tool compile for either (TypeScript's correlated-union limit). The generated client's methods always pass a literal.
ToolShape
interface ToolShape {
input: unknown
output: unknown
}One entry of a tool map. Every entry of a map that meets ToolMapOf is a ToolShape.
ToolMapOf
type ToolMapOf<TMap> = string extends keyof TMap
? never
: number extends keyof TMap
? never
: { [K in keyof TMap]: ToolShape }The constraint TMap extends ToolMapOf<TMap>: every entry a ToolShape, and no index signature. A map with a string or number index signature fails it, such as Record<string, ToolShape> or an interface extending it, as 2.x generated: its key type would be string, so a misspelled tool name would compile.
ToolName
type ToolName<TMap> = keyof TMap & stringThe tool names of a map. The generated <Name>ToolName is keyof <Name>ToolMap.
ToolInput
type ToolInput<TMap extends ToolMapOf<TMap>, TName extends ToolName<TMap>> = TMap[TName]["input"]The input of the tool TName.
ToolOutput
type ToolOutput<TMap extends ToolMapOf<TMap>, TName extends ToolName<TMap>> = TMap[TName]["output"]The output of the tool TName.
ParseToolResultOptions
interface ParseToolResultOptions {
text?: "json" | "raw"
}text | A text block becomes |
|---|---|
"json" (default) | its JSON value, or the string when it is not JSON |
"raw" | always the string |
Applies only to rule 3 of parseToolResult; rules 1, 2 and 4 hold either way. Under "json", "2.10" becomes the number 2.1, "true" the boolean true, and digits beyond a double's precision are lost.
Next steps
- React API: the provider and the hooks built on this package.
- Call tools from Node and the browser: a
ToolCallerfor an MCP client, a widget host or a test. - Generated code: what
create<Name>Clientand the tool map look like.