Skip to content

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 ​

FileWrittenImportsContains
tools.tsalways@miragon/mcp-toolkit-tool-codegen-coreThe input and output types, the tool map, the typed client
hooks.tsxwith react: true@miragon/mcp-toolkit-tool-codegen-react and ./tools.jsThe 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 of url, never its path, query or credentials.
  • List the tools sorted by name, in code-unit order rather than by locale. The same tools/list gives 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 out from it.
  • Are meant to be committed. generate --check tells you when they no longer match the server.

Names ​

The names for examples/tasks, whose config has name: "tasks":

NamePatternExample
Prefix<Name>: PascalCase of the config's nameTasks
Tool part<Tool>: PascalCase of the tool name, or of overrides.<tool>.identifierListTasks for list-tasks
Input type<Name><Tool>InputTasksListTasksInput
Output type<Name><Tool>OutputTasksListTasksOutput
Referenced schemaThe input or output type, then the PascalCase words of the target's pathTasksMoveInputPoint for #/$defs/point in a tool move
Tool map<Name>ToolMapTasksToolMap
Tool name union<Name>ToolNameTasksToolName
Typed call<Name>CallToolTasksCallTool
Client factorycreate<Name>ClientcreateTasksClient
Client type<Name>ClientTasksClient
Client methodcamelCase of <Tool>, with _ before a leading digitlistTasks
Query hookuse<Name><Tool>QueryuseTasksListTasksQuery
Mutation hookuse<Name><Tool>MutationuseTasksAddTaskMutation for add-task
Query key helper<name>QueryKey, where <name> is <Name> with a lower-case first lettertasksQueryKey
Query key namespaceThe config's name as written"tasks"
Tool map keyThe 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 ​

  1. Take the runs of A-Z, a-z and 0-9. Every other character (-, _, ., a space, a letter beyond ASCII) separates runs and is dropped.
  2. Capitalise the first character of each run and keep the rest as it is.
  3. Upper-case a letter that follows a digit, as json-schema-to-typescript does for the names it declares.
Tool name<Tool>Client methodTool map key
list-tasksListTaskslistTasks"list-tasks"
list_tasksListTaskslistTaskslist_tasks
tasks.searchTasksSearchtasksSearch"tasks.search"
getHTTPStatusGetHTTPStatusgetHTTPStatusgetHTTPStatus
get_v2betaGetV2BetagetV2Betaget_v2beta
oauth2tokenOauth2Tokenoauth2Tokenoauth2token
2fa-check2FaCheck_2FaCheck"2fa-check"
über-listeBerListeberListe"über-liste"
タスクnonenonenone

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:

CaseMessage
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 hookcannot 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 imports createTypedCallTool, ToolCallOptions, ToolCaller and TypedCallTool, the config's names <Name>ToolMap, <Name>ToolName, <Name>CallTool, create<Name>Client and <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. then would make the client a thenable that await calls.
  • In hooks.tsx: the imports from the React package. Only the config's <name>QueryKey can clash with one, and the message then asks you to change the config's name.

tools.ts ​

In this order:

  1. The three header lines.
  2. One import from @miragon/mcp-toolkit-tool-codegen-core: createTypedCallTool and the types ToolCallOptions, ToolCaller and TypedCallTool. ToolCallOptions only when the server lists a tool.
  3. Per tool: the input type, then the output type, each followed by the types of the schemas it references.
  4. 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.
  5. export type <Name>ToolName = keyof <Name>ToolMap.
  6. export type <Name>CallTool = TypedCallTool<<Name>ToolMap>.
  7. export function create<Name>Client(callTool: ToolCaller), which returns the client.
  8. export type <Name>Client = ReturnType<typeof create<Name>Client>.

The second half of the committed examples/tasks/src/generated/tools.ts:

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 ​

MemberSignatureWhat 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.
  • args defaults to {} when {} is a valid input, see When args is optional.
  • options is a ToolCallOptions: signal cancels the call, timeout, onprogress, resetTimeoutOnProgress and maxTotalTimeout go to the MCP SDK as its own request options.
  • createTypedCallTool decodes each result: structuredContent when present, else the first text block, read as JSON when it parses as JSON. A result with isError: true rejects with a ToolCallError (Core API).
  • The output type is what the server's schema promises. Nothing checks the result against it at run time.

Types from schemas ​

SchemaGenerated type
An input or output overrideexport type <T> = <expression>, the expression trimmed and pasted unchecked
No outputSchemaexport type <T> = unknown
An input { type: "object" } with no properties, nothing required and additionalProperties absent or falseexport type <T> = Record<string, never>
An output { type: "object" } with no properties, nothing required and additionalProperties absent or falseRecord<string, unknown> with additionalProperties absent, Record<string, never> with false
An input or output { type: "object" } with no properties and additionalProperties: true or a schemaAn 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 memberObject 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 additionalPropertiesThe type alone: JSON Schema applies those keywords to objects only, so they are dropped
Any other schemajson-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 $refDeclared 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:

json
{
  "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"]
    }
  }
}
ts
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 onesGenerated 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:

json
{
  "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
  }
}
ts
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 input override.
  • The input schema has type: "object" and no allOf, anyOf or oneOf at its root.
  • required lists nothing, and no property carries the draft 3 flag required: true.
  • No property is named like a member every object has: constructor, hasOwnProperty, isPrototypeOf, propertyIsEnumerable, toLocaleString, toString or valueOf.

hooks.tsx ​

In this order:

  1. The three header lines.
  2. One import from @miragon/mcp-toolkit-tool-codegen-react, of what the hooks use: toolQueryKey, useToolQuery, ToolCallQueryKey and UseToolQueryOptions with a query hook, useToolMutation and UseToolMutationOptions with a mutation hook.
  3. One import type from ./tools.js: <Name>ToolMap, and with a query hook also <Name>ToolName and the input and output types of each tool with a query hook.
  4. <name>QueryKey(name, args), when at least one tool has a query hook.
  5. 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:

ConditionHook
overrides.<tool>.hook is setThat one
The tool is annotated readOnlyHint: trueQuery
Any other toolMutation

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:

txt
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>,
)
HookCalls
QueryuseToolQuery(namespace, toolName, args, options)
MutationuseToolMutation(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:

tsx
/** 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:

tsx
/** 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 }].

KeyMatches
[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 ​