Generated code
What tools.ts and hooks.tsx contain, and how each tool name becomes a type, a client method, a hook and a query key.
Files
| File | Written | Imports | Contains |
|---|---|---|---|
tools.ts | always | @miragon/mcp-toolkit-tool-codegen-core | The input and output types, the tool map, the typed client |
hooks.tsx | with react: true | @miragon/mcp-toolkit-tool-codegen-react and ./tools.js | The query key helper and one React hook per tool |
Both files:
- Start with three comment lines. The first,
// AUTO-GENERATED by @miragon/mcp-toolkit-tool-codegen. Do not edit by hand., marks the file as the generator's. The second is// Regenerate with: mcp-tool-codegen generate. The third,// Source: <origin>, names the origin ofurl, never its path, query or credentials. - List the tools sorted by name, in code-unit order rather than by locale. The same
tools/listgives byte-identical files in whatever order the server lists the tools, and the files hold no date or version. The generator's Prettier and json-schema-to-typescript are ranges your lockfile resolves, so updating them there can change the files. - Come out formatted like Prettier with a print width of 100, double quotes, no semicolons and trailing commas. If your formatter's style differs, exclude
outfrom it. - Are meant to be committed.
generate --checktells you when they no longer match the server.
Names
The names for examples/tasks, whose config has name: "tasks":
| Name | Pattern | Example |
|---|---|---|
| Prefix | <Name>: PascalCase of the config's name | Tasks |
| Tool part | <Tool>: PascalCase of the tool name, or of overrides.<tool>.identifier | ListTasks for list-tasks |
| Input type | <Name><Tool>Input | TasksListTasksInput |
| Output type | <Name><Tool>Output | TasksListTasksOutput |
| Referenced schema | The input or output type, then the PascalCase words of the target's path | TasksMoveInputPoint for #/$defs/point in a tool move |
| Tool map | <Name>ToolMap | TasksToolMap |
| Tool name union | <Name>ToolName | TasksToolName |
| Typed call | <Name>CallTool | TasksCallTool |
| Client factory | create<Name>Client | createTasksClient |
| Client type | <Name>Client | TasksClient |
| Client method | camelCase of <Tool>, with _ before a leading digit | listTasks |
| Query hook | use<Name><Tool>Query | useTasksListTasksQuery |
| Mutation hook | use<Name><Tool>Mutation | useTasksAddTaskMutation for add-task |
| Query key helper | <name>QueryKey, where <name> is <Name> with a lower-case first letter | tasksQueryKey |
| Query key namespace | The config's name as written | "tasks" |
| Tool map key | The tool name as listed: bare when it is a plain identifier, else quoted | "list-tasks" |
The tool map key and the string every call passes stay the tool's own name; only identifiers go through PascalCase.
PascalCase
- Take the runs of
A-Z,a-zand0-9. Every other character (-,_,., a space, a letter beyond ASCII) separates runs and is dropped. - Capitalise the first character of each run and keep the rest as it is.
- Upper-case a letter that follows a digit, as json-schema-to-typescript does for the names it declares.
| Tool name | <Tool> | Client method | Tool map key |
|---|---|---|---|
list-tasks | ListTasks | listTasks | "list-tasks" |
list_tasks | ListTasks | listTasks | list_tasks |
tasks.search | TasksSearch | tasksSearch | "tasks.search" |
getHTTPStatus | GetHTTPStatus | getHTTPStatus | getHTTPStatus |
get_v2beta | GetV2Beta | getV2Beta | get_v2beta |
oauth2token | Oauth2Token | oauth2Token | oauth2token |
2fa-check | 2FaCheck | _2FaCheck | "2fa-check" |
über-liste | BerListe | berListe | "über-liste" |
タスク | none | none | none |
The config's name follows the same rule: my-app gives MyApp, my_tasks2go gives MyTasks2Go. For a name like über-liste or タスク, set overrides.<tool>.identifier (Configuration).
Collisions
The generator keeps a list of every name a file declares. A second claim on a name fails the run, names both owners and says what resolves it:
| Case | Message |
|---|---|
Two tools give the same <Tool> (list-tasks and list_tasks) | cannot generate tools.ts: the tool "list-tasks" and the tool "list_tasks" both produce the identifier "TasksListTasksInput". Rename one of the tools on the server, or give one another identifier with overrides.<tool>.identifier. |
A client method JavaScript looks up on any object (then) | cannot generate the client of tools.ts: JavaScript's object member then and the tool "then" both produce the identifier "then". Rename the tool on the server, or give it another identifier with overrides.<tool>.identifier. |
A tool name without an ASCII letter or digit (タスク) | cannot generate code for the tool "タスク": its name has no ASCII letter or digit to build an identifier from. Rename it on the server, or give it one with overrides.<tool>.identifier. |
The config's name: "typed" | cannot generate tools.ts: the import TypedCallTool and the config name "typed" both produce the identifier "TypedCallTool". Change the config name. |
The config's name: "tool" with react: true and a query hook | cannot generate hooks.tsx: the import toolQueryKey and the config name "tool" both produce the identifier "toolQueryKey". Change the config name. |
What the generator checks the names against:
- In
tools.ts: the importscreateTypedCallTool,ToolCallOptions,ToolCallerandTypedCallTool, the config's names<Name>ToolMap,<Name>ToolName,<Name>CallTool,create<Name>Clientand<Name>Client, and any type another tool declares. - On the client:
call,then,constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf,toJSON, and any method of another tool.thenwould make the client a thenable thatawaitcalls. - In
hooks.tsx: the imports from the React package. Only the config's<name>QueryKeycan clash with one, and the message then asks you to change the config'sname.
tools.ts
In this order:
- The three header lines.
- One import from
@miragon/mcp-toolkit-tool-codegen-core:createTypedCallTooland the typesToolCallOptions,ToolCallerandTypedCallTool.ToolCallOptionsonly when the server lists a tool. - Per tool: the input type, then the output type, each followed by the types of the schemas it references.
export interface <Name>ToolMap: one entry{ input; output }per tool, keyed by the tool name, without an index signature, so an unknown tool name does not compile. Empty ({}) when the server lists no tool.export type <Name>ToolName = keyof <Name>ToolMap.export type <Name>CallTool = TypedCallTool<<Name>ToolMap>.export function create<Name>Client(callTool: ToolCaller), which returns the client.export type <Name>Client = ReturnType<typeof create<Name>Client>.
The second half of the committed examples/tasks/src/generated/tools.ts:
export interface TasksToolMap {
"add-task": {
input: TasksAddTaskInput
output: TasksAddTaskOutput
}
"complete-task": {
input: TasksCompleteTaskInput
output: TasksCompleteTaskOutput
}
"get-task": {
input: TasksGetTaskInput
output: TasksGetTaskOutput
}
"list-tasks": {
input: TasksListTasksInput
output: TasksListTasksOutput
}
}
export type TasksToolName = keyof TasksToolMap
export type TasksCallTool = TypedCallTool<TasksToolMap>
export function createTasksClient(callTool: ToolCaller) {
const call = createTypedCallTool<TasksToolMap>(callTool)
return {
call,
/** Adds an open task and returns it. */
addTask: (args: TasksAddTaskInput, options?: ToolCallOptions) =>
call("add-task", args, options),
/** Marks a task as done and returns it. Completing a done task changes nothing. */
completeTask: (args: TasksCompleteTaskInput, options?: ToolCallOptions) =>
call("complete-task", args, options),
/** Returns one task. */
getTask: (args: TasksGetTaskInput, options?: ToolCallOptions) =>
call("get-task", args, options),
/** Lists the tasks in the order they were added. */
listTasks: (args: TasksListTasksInput = {}, options?: ToolCallOptions) =>
call("list-tasks", args, options),
}
}
export type TasksClient = ReturnType<typeof createTasksClient>The client
| Member | Signature | What it does |
|---|---|---|
call | <Name>CallTool: (name, args, options?) => Promise<output> | Calls any tool of the map by its name. |
| One method per tool | (args: <Name><Tool>Input, options?: ToolCallOptions) => Promise<<Name><Tool>Output> | Calls call("<tool>", args, options). Its JSDoc is the tool description. |
argsdefaults to{}when{}is a valid input, see Whenargsis optional.optionsis aToolCallOptions:signalcancels the call,timeout,onprogress,resetTimeoutOnProgressandmaxTotalTimeoutgo to the MCP SDK as its own request options.createTypedCallTooldecodes each result:structuredContentwhen present, else the first text block, read as JSON when it parses as JSON. A result withisError: truerejects with aToolCallError(Core API).- The output type is what the server's schema promises. Nothing checks the result against it at run time.
Types from schemas
| Schema | Generated type |
|---|---|
An input or output override | export type <T> = <expression>, the expression trimmed and pasted unchecked |
No outputSchema | export type <T> = unknown |
An input { type: "object" } with no properties, nothing required and additionalProperties absent or false | export type <T> = Record<string, never> |
An output { type: "object" } with no properties, nothing required and additionalProperties absent or false | Record<string, unknown> with additionalProperties absent, Record<string, never> with false |
An input or output { type: "object" } with no properties and additionalProperties: true or a schema | An interface with an index signature: [k: string]: unknown for true, the schema's type for a schema |
A tuple: prefixItems (draft 2020-12, zod 4's z.tuple) or items as a list (draft-07) | A TypeScript tuple, its elements past minItems optional and further elements allowed unless the schema closes it: [A, B?], [A, B?, ...C[]], see Tuples |
No type, items or prefixItems, and object keywords that give the object a member | Object or array, as JSON Schema applies each keyword to its own type only: { a?: string } | [string?, ...unknown[]] |
A type that names no object, next to properties, patternProperties or additionalProperties | The type alone: JSON Schema applies those keywords to objects only, so they are dropped |
| Any other schema | json-schema-to-typescript's interface or type alias; a property the schema does not declare is a type error unless additionalProperties allows it, descriptions become JSDoc |
The target of a $ref | Declared once as its own type, named after the input or output type and the target's path |
<T> is <Name><Tool>Input or <Name><Tool>Output. The generator rebuilds every schema from a list of allowed keywords before json-schema-to-typescript sees it; what it drops and why: Guarantees and limits.
An input schema with a $defs entry, for a tool move and the config name my-app:
{
"type": "object",
"properties": {
"from": { "$ref": "#/$defs/point" },
"to": { "$ref": "#/$defs/point" }
},
"required": ["from", "to"],
"$defs": {
"point": {
"type": "object",
"properties": { "x": { "type": "number" }, "y": { "type": "number" } },
"required": ["x", "y"]
}
}
}export interface MyAppMoveInput {
from: MyAppMoveInputPoint
to: MyAppMoveInputPoint
}
export interface MyAppMoveInputPoint {
x: number
y: number
}Tuples
A tuple lists a schema per position: prefixItems in draft 2020-12, items as a list in draft-07. The generated type reads it as JSON Schema does. An element past minItems may be missing, so it is optional; without minItems, every element is. Further elements are allowed unless the schema says otherwise, and typed by the schema for them: items beside prefixItems, or additionalItems beside an items list. For minItems: 1:
| Elements after the listed ones | Generated type |
|---|---|
false, or a maxItems no larger than the number of listed elements | [A, B?] |
A schema C | [A, B?, ...C[]] |
true, or no schema for them | [A, B?, ...unknown[]] |
A maxItems smaller than the number of listed elements also drops the elements past it. A minItems or maxItems that is not a non-negative integer up to Number.MAX_SAFE_INTEGER counts as absent, -1, 1.5, "2" and 1e300 alike. A bound past the listed elements is not typed: { prefixItems: [A], items: C, minItems: 3 } is [A, ...C[]], just as z.array(z.string()).min(3) is string[]; see Guarantees and limits. A $ref may point into a tuple (#/properties/at/prefixItems/0); its target is declared once, as for any other path.
zod 4 writes minItems for the required elements of a z.tuple and closes it with items: false unless it has a rest, so its tuples come out as declared. Parameters z.tuple([z.string(), z.number()]), z.tuple([z.string(), z.number().optional()]) and z.tuple([z.string()], z.boolean()) reach tools/list as:
{
"pair": {
"type": "array",
"prefixItems": [{ "type": "string" }, { "type": "number" }],
"items": false,
"minItems": 2,
"maxItems": 2
},
"last": {
"type": "array",
"prefixItems": [{ "type": "string" }, { "type": "number" }],
"items": false,
"minItems": 1,
"maxItems": 2
},
"flags": {
"type": "array",
"prefixItems": [{ "type": "string" }],
"items": { "type": "boolean" },
"minItems": 1
}
}export interface MyAppMarkInput {
pair: [string, number]
last: [string, number?]
flags: [string, ...boolean[]]
}pydantic closes a tuple with maxItems instead: tuple[int, str] is { "prefixItems": [...], "minItems": 2, "maxItems": 2 }, typed [number, string]. A tuple that says nothing about further elements, such as { "prefixItems": [{ "type": "string" }] } written by hand, is open: [string?, ...unknown[]].
When args is optional
args defaults to {}, in the client method and in the query hook, when all of these hold:
- The tool has no
inputoverride. - The input schema has
type: "object"and noallOf,anyOforoneOfat its root. requiredlists nothing, and no property carries the draft 3 flagrequired: true.- No property is named like a member every object has:
constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toStringorvalueOf.
hooks.tsx
In this order:
- The three header lines.
- One import from
@miragon/mcp-toolkit-tool-codegen-react, of what the hooks use:toolQueryKey,useToolQuery,ToolCallQueryKeyandUseToolQueryOptionswith a query hook,useToolMutationandUseToolMutationOptionswith a mutation hook. - One
import typefrom./tools.js:<Name>ToolMap, and with a query hook also<Name>ToolNameand the input and output types of each tool with a query hook. <name>QueryKey(name, args), when at least one tool has a query hook.- One hook per tool, its JSDoc the tool description.
When the server lists no tool, the file holds only the header and export {}.
Query or mutation
The first row that applies decides:
| Condition | Hook |
|---|---|
overrides.<tool>.hook is set | That one |
The tool is annotated readOnlyHint: true | Query |
| Any other tool | Mutation |
MCP's readOnlyHint defaults to false, and a query runs its tool again on every refetch, so a tool that does not declare itself read-only never gets a query hook on its own.
Hook signatures
<Name>, <Tool> and toolName are placeholders:
use<Name><Tool>Query<TSelected = <Name><Tool>Output>(
args: <Name><Tool>Input,
options?: UseToolQueryOptions<<Name><Tool>Output, TSelected>,
)
use<Name><Tool>Mutation<TOnMutateResult = unknown>(
options?: UseToolMutationOptions<<Name>ToolMap, toolName, TOnMutateResult>,
)| Hook | Calls |
|---|---|
| Query | useToolQuery(namespace, toolName, args, options) |
| Mutation | useToolMutation(namespace, toolName, options) |
namespace is the config's name as written and toolName the tool name, both as string literals. What the options take and what the hooks return: React API.
The start of the committed examples/tasks/src/generated/hooks.tsx, after its imports:
/** The key a query of this server caches a tool call under, for the QueryClient. */
export function tasksQueryKey<TName extends TasksToolName>(
name: TName,
args: TasksToolMap[TName]["input"],
): ToolCallQueryKey<TasksToolMap, TName> {
return toolQueryKey<TasksToolMap, TName>("tasks", name, args)
}
/** Adds an open task and returns it. */
export function useTasksAddTaskMutation<TOnMutateResult = unknown>(
options?: UseToolMutationOptions<TasksToolMap, "add-task", TOnMutateResult>,
) {
return useToolMutation<TasksToolMap, "add-task", TOnMutateResult>("tasks", "add-task", options)
}and its last hook:
/** Lists the tasks in the order they were added. */
export function useTasksListTasksQuery<TSelected = TasksListTasksOutput>(
args: TasksListTasksInput = {},
options?: UseToolQueryOptions<TasksListTasksOutput, TSelected>,
) {
return useToolQuery<TasksToolMap, "list-tasks", TSelected>("tasks", "list-tasks", args, options)
}Query keys
<name>QueryKey(tool, args) returns the key a query hook caches its call under: tasksQueryKey("list-tasks", { done: false }) is ["tasks", "list-tasks", { done: false }].
| Key | Matches |
|---|---|
[namespace] | Every query of the server; what a mutation invalidates by default |
[namespace, toolName] | Every call of one tool |
[namespace, toolName, args] | One call; equal args give the same key, whatever their object identity |
The helper is typed by the tool map, so an unknown tool name or wrong args do not compile, and its key carries the tool's output type for the QueryClient's getQueryData and setQueryData.
Next steps
- Configuration: the keys that set
name,reactand the overrides. - Call tools from Node and the browser: the client of
tools.tsat work. - Use the React hooks: the hooks of
hooks.tsxin a React app.