View the source code for this module on GitHub: https://github.com/mcp-use/mcp-use/blob/main/libraries/typescript/packages/mcp-use/src/react/useCallTool.ts
useCallTool is a React hook for calling MCP tools from inside a widget. It manages the call with a discriminated union state machine (idle, pending, success, error) similar to TanStack Query, and exposes two ways to invoke the tool: callTool (fire-and-forget with optional side effect callbacks) and callToolAsync (returns a Promise).
Types are inferred from the ToolRef values exported by your server entry. The project’s mcp-env.d.ts registers that module with mcp-use/react; it does not generate tool-specific types or require the server to be running.
Declare static tools as exported constants:
mcp-env.d.ts is present, calling useCallTool("search-flights") is a TypeScript error if the matching tool ref is not exported. Use useDynamicTool<Args, Result>("name") only when the tool is genuinely registered at runtime and cannot have an exported ref.
useCallTool runs only in a browser environment. Calling it outside the browser (for example, during server-side rendering) throws Error("useCallTool can only be used in browser environment").useCallTool
Call an MCP tool and track its lifecycle with idle, pending, success, and error states.RegisteredTools or a ToolRef value. Both forms infer the tool input and output types. The runtime detects the protocol automatically: in MCP Apps clients it uses JSON-RPC over postMessage, and in the ChatGPT Apps SDK it uses window.openai.callTool(). Your code is identical in both cases.
When name is a key of RegisteredTools, input arguments and the response structuredContent are fully typed from your server’s tool definition. The hook tracks the latest call with an internal counter, so if you fire a new call before a previous one resolves, only the most recent call updates state (responses from stale calls are ignored).
Type Parameters (ref overload)keyof RegisteredToolsrequiredThe tool name, constrained to exported tool refs from the registered server entry.
ParametersToolRef<string, unknown, unknown>requiredA tool ref value carrying its name, input, and output types.
Returnskeyof RegisteredTools | ToolRefrequiredThe exported name or tool ref to call.
SignatureCallToolHandle<Args, Result>The call function and its latest data, error, and pending state.
Returns
The hook returns the currentCallToolState spread together with two methods. Every field below is present on the returned object.
status
The current lifecycle state of the tool call. Returns"idle" | "pending" | "success" | "error""idle"before any call,"pending"while a call is in flight,"success"after the latest call resolves, and"error"after the latest call rejects.
isIdle
Convenience boolean flag for the idle state. Returnsbooleantruewhenstatus === "idle"(no call has been made yet).
isPending
Convenience boolean flag for the pending state. Returnsbooleantruewhenstatus === "pending"(a call is currently executing).
isSuccess
Convenience boolean flag for the success state. Returnsbooleantruewhenstatus === "success". Whentrue,datais defined anderrorisundefined.
isError
Convenience boolean flag for the error state. Returnsbooleantruewhenstatus === "error". Whentrue,erroris defined anddataisundefined.
data
The tool result, available only after a successful call. ReturnsTResponse | undefinedThe normalized response.undefinedin every state exceptsuccess. For registry-typed tools this isCallToolResponsewith a typedstructuredContent. SeeCallToolResponse.
error
The error thrown by the tool call, available only after a failed call. Returnsunknown | undefinedThe thrown error.undefinedin every state excepterror. Typed asunknownbecause any value can be thrown.
callTool
Fire-and-forget invocation with optional side effect callbacks.callTool starts the tool call and returns void immediately. State (isPending, data, error, and so on) updates as the call progresses. You can pass a SideEffects object to react to the result. When the tool input is optional (for example null input or all-optional fields), you may omit args entirely or pass only the side effects object as the first argument; the hook detects a side effects object by the presence of an onSuccess, onError, or onSettled key.
Type
CallToolFn for the full set of call signatures.
callToolAsync
Promise-based invocation for sequential ortry/catch flows.
callToolAsync starts the tool call and returns a Promise that resolves with the response or rejects with the thrown error. State flags update the same way as callTool. When the tool input is optional, you may call it with no arguments. Use this method to chain tool calls or to handle the result with await inside a try/catch block.
Type
CallToolAsyncFn for the full set of call signatures.
generateHelpers
Generate fully-typed hook helpers from an explicit tool map. This is an alternative to the automaticToolRegistry approach. When using mcp-use dev, types are auto-generated in .mcp-use/tool-registry.d.ts and useCallTool is typed without this factory. Use generateHelpers for advanced cases: running without mcp-use dev (for example a custom build setup), scoping types to a subset of tools, or using different tool maps in different parts of your app. It returns an object containing a typed useCallTool and a typed useToolInfo hook, both bound to the supplied TMap.
Returns
SignatureTypedUseCallTool<TMap>AuseCallToolhook whosenameargument is constrained to the keys ofTMap, with input and output inferred from the map. SeeTypedUseCallTool.TypedUseToolInfo<TMap>
Types
CallToolState
The discriminated union that models the four lifecycle states of a tool call. Each variant fixes the boolean flags and the presence ofdata and error, so narrowing on status (or on any flag) gives type-safe access to data and error. The success variant is the only one where data is present, and the error variant is the only one where error is present.
SignatureanyrequiredThe type ofdatain thesuccessvariant.
SideEffects
Optional callbacks passed tocallTool, modeled after TanStack Query mutation callbacks.
All three callbacks are optional. onSuccess runs when the call resolves, onError runs when it rejects, and onSettled runs after either outcome. Each callback receives the original args that were passed to the call. In onSettled, exactly one of data or error is defined depending on the outcome.
SignatureTArgsrequiredThe type of the tool input arguments passed back to each callback.TResponserequiredThe type of the successful response.
CallToolFn
The call signature ofcallTool, the fire-and-forget method. Returns void.
The signature adapts to whether the tool input is optional. When the input type is optional (it is null, or all of its keys are optional), you can call with no arguments, with only a SideEffects object, with only args, or with both. When the input is required, you must pass args, optionally followed by a SideEffects object.
SignatureTArgsrequiredThe tool input type. Whether it is optional determines which overloads are available.TResponserequiredThe successful response type passed to the callbacks.
CallToolAsyncFn
The call signature ofcallToolAsync, the Promise-based method.
Like CallToolFn, it adapts to whether the input is optional. When the input is optional, you can call with no arguments or with args; both return Promise<TResponse>. When the input is required, you must pass args.
SignatureTArgsrequiredThe tool input type. Whether it is optional determines which overloads are available.TResponserequiredThe type the returnedPromiseresolves with.
UseCallToolReturn
The full return type ofuseCallTool. Intersects the current CallToolState with the two call methods.
SignatureTArgsrequiredThe tool input type.TResponserequiredThe successful response type.
ToolMap
The structure of a tool map passed togenerateHelpers. Maps each tool name to its input and optional output types.
Each entry has a required input (an object type, or null when the tool takes no arguments) and an optional output object type. When output is omitted, the tool’s response is the bare CallToolResponse without typed structuredContent.
ToolInput
Extracts the input type for a given tool name from aToolMap.
SignatureToolMaprequiredThe tool map to read from.keyof TMaprequiredThe tool name whose input type to extract.
ToolOutput
Extracts the output type for a given tool name from aToolMap, combined with CallToolResponse.
When the map entry declares an output object, the result is CallToolResponse intersected with { structuredContent: <output> }. When output is absent, it intersects with Record<string, never>, leaving structuredContent untyped.
SignatureToolMaprequiredThe tool map to read from.keyof TMaprequiredThe tool name whose output type to extract.
TypedUseCallTool
The type of theuseCallTool hook returned by generateHelpers. A useCallTool bound to a specific ToolMap, so name is constrained to that map’s keys and input/output are inferred from it.
SignatureToolMaprequiredThe tool map the hook is bound to.
TypedUseToolInfo
The type of theuseToolInfo hook returned by generateHelpers. A useToolInfo bound to a specific ToolMap that returns the current widget state (a UseWidgetResult) typed against the map.
null input types are widened to UnknownObject for compatibility with useWidget.
SignatureToolMaprequiredThe tool map the hook is bound to.
InferToolMapFromSchemas
Helper type that builds aToolMap from Zod schemas, so you do not have to hand-write input and output object types.
Pass a record mapping tool names to objects with an optional schema and outputSchema. The helper reads the inferred input from the schema (_input, falling back to _type) and the inferred output from the output schema (_output, falling back to _type). When a schema is missing, input resolves to null; when an output schema is missing, output resolves to undefined.
SignatureRecord<string, { schema?: any; outputSchema?: any }>requiredA record mapping tool names to their Zod input and output schemas.
Response Structure
Successful calls resolve with a normalizedCallToolResponse. The hook’s data field (and the data argument of the success callbacks) has this shape. For registry-typed or tool-map-typed tools, structuredContent is narrowed to your tool’s output type.
CallToolResponse
The normalized response returned by a tool call.result is a convenience field containing the text content blocks joined into a single string. structuredContent holds the tool’s structured output when it returned any. isError is set by the protocol when the tool reported an error result.
Signature
Examples
Basic usage
The tool name is type-checked, and input and output are typed from the registry when runningmcp-use dev.
Fire-and-forget with callbacks
UsecallTool for non-blocking calls. The callbacks receive the original args, so you can read them back in any of the three handlers.
Async/await
UsecallToolAsync to chain calls or handle results in a try/catch block. The Promise resolves with the response or rejects with the thrown error.
Dynamic tools (escape hatch)
When a tool is registered from runtime data, a loop, or an OpenAPI document, supply its input and result types explicitly withuseDynamicTool. Do not use this to hide a missing export on a statically declared tool.
How registration works
The rootmcp-env.d.ts points at the server entry in type space. Exported ToolRef values become the useCallTool name union automatically, including refs re-exported from split tool modules.
Server tool definition
The exported tool refs and their schemas drive the inferred types. Define tools withnew MCPServer({ ... }) and a Zod schema.
See Also
- useWidget() - Accessing widget props, state, and host context
- Building UI Widgets - Complete widget development guide