Skip to main content
Tools extend what agents can do—letting them fetch real-time data, execute code, query external databases, and take actions in the world. Under the hood, tools are callable functions with well-defined inputs and outputs that get passed to a chat model. The model decides when to invoke a tool based on the conversation context, and what input arguments to provide.
For details on how models handle tool calls, see Tool calling. Trace tool calls and debug errors with LangSmith. Follow the tracing quickstart to get set up.We recommend you also set up LangSmith Engine which monitors your traces, detects issues, and proposes fixes.

Create tools

Basic tool definition

The simplest way to create a tool is with the @tool decorator. By default, the function’s docstring becomes the tool’s description that helps the model understand when to use it:
Type hints are required as they define the tool’s input schema. The docstring should be informative and concise to help the model understand the tool’s purpose.
Server-side tool use: Some chat models feature built-in tools (web search, code interpreters) that are executed server-side. See Server-side tool use for details.
Prefer snake_case for tool names (e.g., web_search instead of Web Search). Some model providers have issues with or reject names containing spaces or special characters with errors. Sticking to alphanumeric characters, underscores, and hyphens helps to improve compatibility across providers.

Customize tool properties

Custom tool name

By default, the tool name comes from the function name. Override it when you need something more descriptive:

Custom tool description

Override the auto-generated tool description for clearer model guidance:

Advanced schema definition

Define complex inputs with Pydantic models or JSON schemas:

Reserved argument names

The following parameter names are reserved and cannot be used as tool arguments. Using these names will cause runtime errors. To access runtime information, use the ToolRuntime parameter instead of naming your own arguments config or runtime. If you use InjectedState, InjectedStore, get_runtime(), or InjectedToolCallId, see Migrate from older injection patterns.

Access context

Tools are most powerful when they can access runtime information like conversation history, user data, and persistent memory. This section covers how to access and update this information from within your tools. Tools can access runtime information through the ToolRuntime parameter, which provides:

Short-term memory (State)

State represents short-term memory that exists for the duration of a conversation. It includes the message history and any custom fields you define in your graph state.
Add runtime: ToolRuntime to your tool signature to access state. This parameter is automatically injected and hidden from the LLM - it won’t appear in the tool’s schema.

Access state

Tools can access the current conversation state using runtime.state:
The runtime parameter is hidden from the model. For the example above, the model only sees pref_name in the tool schema.

Update state

Use Command to update the agent’s state. This is useful for tools that need to update custom state fields. Include a ToolMessage in the update so the model can see the result of the tool call:
When tools update state variables, consider defining a reducer for those fields. Since LLMs can call multiple tools in parallel, a reducer determines how to resolve conflicts when the same state field is updated by concurrent tool calls.

Context

Context provides immutable configuration data that is passed at invocation time. Use it for user IDs, session details, or application-specific settings that shouldn’t change during a conversation.
While thread_id (passed via config={"configurable": {"thread_id": ...}}) scopes the conversation: message history and checkpoints, context carries per-run data your tools and middleware read at invocation time. In production you typically pass both together: a stable thread_id per conversation, and a context object on every invoke.
Access context through runtime.context. Pass it alongside a thread_id so the conversation is persisted across turns:

Long-term memory (Store)

The BaseStore provides persistent storage that survives across conversations. Unlike state (short-term memory), data saved to the store remains available in future sessions. Access the store through runtime.store. The store uses a namespace/key pattern to organize data:
For production deployments, use a persistent store implementation like PostgresStore instead of InMemoryStore. See the memory documentation for setup details.

Stream writer

Stream real-time updates from tools during execution. This is useful for providing progress feedback to users during long-running operations. Use runtime.stream_writer to emit custom updates:
If you use runtime.stream_writer inside your tool, the tool must be invoked within a LangGraph execution context. See Streaming for more details.

Execution info

Access thread ID, run ID, and retry state from within a tool via runtime.execution_info:
Requires deepagents>=0.5.0 (or langgraph>=1.1.5).

Server info

When your tool runs on LangGraph Server, access the assistant ID, graph ID, and authenticated user via runtime.server_info:
server_info is None when the tool is not running on LangGraph Server (e.g., during local development or testing).
Requires deepagents>=0.5.0 (or langgraph>=1.1.5).
Older examples used InjectedState, InjectedStore, get_runtime(), or InjectedToolCallId. Use ToolRuntime instead for one explicit interface to state, context, store, and execution metadata.

Previous pattern

For agent-level migrations (for example create_react_agent and custom state), see the LangChain v1 migration guide.

Tool execution

In LangChain, tools are used by agents (for example via create_agent) and tool error handling is configured through middleware. For LangGraph workflows, tool execution is handled by ToolNode. See ToolNode for Graph API usage, including how tools can access the current graph state and run-scoped context.

Tool return values

You can choose different return values for your tools:
  • Return a string for human-readable results.
  • Return an object for structured results the model should parse.
  • Return a Command with optional message when you need to write to state.

Return a string

Return a string when the tool should provide plain text for the model to read and use in its next response.
Behavior:
  • The return value is converted to a ToolMessage.
  • The model sees that text and decides what to do next.
  • No agent state fields are changed unless the model or another tool does so later.
Use this when the result is naturally human-readable text.

Return an object

Return an object (for example, a dict) when your tool produces structured data that the model should inspect.
Behavior:
  • The object is serialized and sent back as tool output.
  • The model can read specific fields and reason over them.
  • Like string returns, this does not directly update graph state.
Use this when downstream reasoning benefits from explicit fields instead of free-form text.

Return multimodal content

Tools are not limited to plain text. When the model supports multimodal tool results, the tool can return standard content blocks so the model receives text, images, and other media in one tool result.
Behavior:
  • The return value is converted to a ToolMessage with multimodal content.
  • Use message.content_blocks to read the normalized block list after the tool runs.
  • The model must support the modalities you return. Check your model’s capabilities before returning images, audio, or video.
For block types and provider-specific requirements, see Multimodal messages. MCP tools that return images or mixed content are converted the same way; see Multimodal tool content.

Return a Command

Return a Command when the tool needs to update graph state (for example, setting user preferences or app state). You can return a Command with or without including a ToolMessage. If the model needs to see that the tool succeeded (for example, to confirm a preference change), include a ToolMessage in the update, using runtime.tool_call_id for the tool_call_id parameter.
Behavior:
  • The command updates state using update.
  • Updated state is available to subsequent steps in the same run.
  • Use reducers for fields that may be updated by parallel tool calls.
Use this when the tool is not just returning data, but also mutating agent state.

Return directly from a tool

Set return direct on a tool to short-circuit the agent loop: the agent returns the tool’s output to the caller immediately, without sending it back through the model for further processing.
Behavior:
  • The tool executes normally and its output is wrapped in a ToolMessage.
  • The agent stops looping and returns the tool’s output as the final response, bypassing any additional model call.
  • If the model calls multiple tools in a single turn, return_direct takes effect only when all called tools have return_direct=True.
Use this when:
  • The tool’s output is the complete, user-ready answer (for example, a lookup that returns a ready-to-display result).
  • You want to avoid an extra model call when no additional reasoning is needed.
  • You need deterministic, unmodified output — the model cannot rephrase, summarize, or act on the tool result.
Because the model does not process the tool’s output, return_direct=True is not suitable for tools whose results require further reasoning, summarization, or chaining with other tool calls.

Error handling

Handle tool errors using LangChain agent middleware to retry failed tool calls or return custom error messages:

State injection

Tools access graph state through ToolRuntime. See Access context for state, context, store, and streaming APIs.
For more details on accessing state, context, and long-term memory from tools, see Access context.

Dynamic tool selection

With dynamic tools, the set of tools available to the agent is modified at runtime rather than defined all upfront. Not every tool is appropriate for every situation. Too many tools may overwhelm the model (overload context) and increase errors; too few limit capabilities. Dynamic tool selection enables adapting the available toolset based on authentication state, user permissions, feature flags, or conversation stage. There are two approaches depending on whether tools are known ahead of time:
When all possible tools are known at agent creation time, you can pre-register them and dynamically filter which ones are exposed to the model based on state, permissions, or context.
Enable advanced tools only after certain conversation milestones:
This approach is best when:
  • All possible tools are known at compile/startup time
  • You want to filter based on permissions, feature flags, or conversation state
  • Tools are static but their availability is dynamic
See Dynamically selecting tools for more examples.

Headless tools

Some tools should run where your user’s app runs (typically the browser), not inside the process. Headless tools are tool definitions, which include the name, description, and argument schema, that you register on the server with your agent. The implementation is registered only on the client and executed after a short interrupt/resume handshake. This is different from ordinary tools whose function body runs on the server, and from server-side tool use where the model provider executes built-in tools remotely.

When to use headless tools

Use them when the work depends on the environment, device, or UI that only exists on the client. For example:
  • Browser APIs: Geolocation, IndexedDB, Clipboard, Canvas 2D, file pickers, Battery API, etc.
  • Privacy and locality: Data stays on the device (for example, local “memory” in IndexedDB).
  • Latency: No extra server round trip for purely local operations.
  • Structured, safe effects: Prefer many small, typed tools (for example one tool per canvas primitive) instead of sending arbitrary code to eval.

How the pattern works

In both runtimes, the model sees a normal tool it can call, but the actual execution happens outside the server process.
  1. Define a headless tool with tool(name=..., description=..., args_schema=...) from langchain.tools. A headless tool is schema-only, with no in-process implementation.
  2. Register that tool with create_agent or your LangGraph graph so the model can call it normally.
  3. Handle the interrupt payload when the tool is invoked. Instead of running locally, the graph pauses with a payload shaped like {"type": "tool", "tool_call": {"id", "name", "args"}}.
  4. Resume the graph after your app, another service, or a human step performs the action. For browser-based flows, you can mirror the schema in the frontend and attach .implement(...) there.
If you call tool(...) in Python with only name, description, and args_schema, LangChain returns a HeadlessTool. There is no .implement() API on the Python side.
When the model issues a tool call for one of these tools, the run interrupts instead of executing the tool locally. Your app can inspect the payload, perform the action in the right environment (for example a browser, another service, or a human review step), then resume the graph with the tool result. When you use the supported JS SDK hooks, they can detect headless-tool interrupts, run the matching client implementation, and submit the resume command for you. Use the optional onTool callback to observe lifecycle events (start, success, error) for UI feedback such as spinners or toasts.

Headless tools frontend pattern

See an end-to-end example of schema-only tools executed in the client with useStream.

Prebuilt tools

LangChain provides a large collection of prebuilt tools and toolkits for common tasks like web search, code interpretation, database access, and more. These ready-to-use tools can be directly integrated into your agents without writing custom code. See the tools and toolkits integration page for a complete list of available tools organized by category.

Server-side tool use

Some chat models feature built-in tools that are executed server-side by the model provider. These include capabilities like web search and code interpreters that don’t require you to define or host the tool logic. Refer to the individual chat model integration pages and the tool calling documentation for details on enabling and using these built-in tools.