9. The Tool System
Codex rebuilds the list of tools for every sampling request, sends
their specs to the model, and turns each tool call the model returns
into one typed ToolCall. A registry dispatches that call
through hooks and a handler, a single read/write lock decides which
calls may overlap, and every result goes back to the model as an output
item with the same call_id.
A tool is the only way the model can act: it can only emit an item that names a tool and carries arguments. Everything between that item and the output the model reads next is the tool system. It decides which tools exist, how each is described, which Rust code serves a call, what may run at once, and what the model sees when a call fails.
This chapter follows that path, traces one exec_command
call, and lists every handler. Chapter 10 then opens up
exec_command itself.
The picture
The turn loop sees a finished function_call item and
hands it to ToolRouter::build_tool_call, which produces a
ToolCall. ToolCallRuntime spawns a task that
waits for the read side of a shared lock, or the write side if the tool
must run alone. The registry checks the call, and
PreToolUse hooks may block it or rewrite its input. A shell
handler goes through the ToolOrchestrator for approval,
sandbox choice, and retry. PostToolUse hooks see the
result, which becomes an output item for the next sampling request.
Every red box can end the call early, and an early end still produces an
output item.
What the model is offered
A new plan for every sampling request
Before each sampling request, which the code calls a step,
Session::capture_step_context_inner reaches
build_tool_router in
codex-rs/core/src/tools/spec_plan.rs. The doc comment on
StepContext describes it as “Request-scoped state that may
change between model sampling requests.” The tool list is part of that
state, because its inputs can change mid-turn: the model, Model Context
Protocol (MCP) servers that finish starting, the attached environments,
and client tools.
build_tool_router fills a fresh
ToolRegistry in a fixed order: core tools through
add_core_tool_sources, then MCP tools, extension tools,
client-supplied dynamic tools, and finally hosted specs that only the
provider executes. finalize_tool_router then removes tools
that clash with reserved names, adds tool_search when the
model supports search and some tool is deferred, registers the code-mode
tools when that mode is on, and returns a ToolRouter.
Caches such as ToolSearchHandlerCache reduce the repeated
work.
The conditions that add a core tool
Each core tool has its own condition. add_shell_tools in
spec_plan.rs reads two feature flags and one model
field:
if !features.enabled(Feature::ShellTool)
|| matches!(context.model_info.shell_type, ConfigShellToolType::Disabled)
{
return;
}
if context.tool_policy.require_unified_exec && !features.enabled(Feature::UnifiedExec) {
return;
}
// ...
if features.enabled(Feature::UnifiedExec) {
registry.add(ExecCommandHandler::new(options));
registry.add(WriteStdinHandler);
} else {
// Managed requirements are the only configuration path that can keep
// unified exec disabled. ...
registry.add(ExecCommandHandler::one_shot(options));
}A stricter gate sits above all core tools. When the tool policy sets
require_managed_sandbox and the thread or any selected
environment lacks a PermissionProfile::Managed profile,
add_core_tool_sources returns before registering anything.
The model then gets no core tools, not even a shell.
The table lists the main core tools, with each tool’s wire kind and
the condition in spec_plan.rs that adds it. Registered does
not mean listed: under code mode, described next, most of them sit
behind one script tool.
| Tool | Wire kind | Offered when | Purpose |
|---|---|---|---|
exec_command |
function | shell_tool on, model shell type not disabled |
Run a shell command |
write_stdin |
function | as above, plus unified_exec on |
Write to or poll a running command |
apply_patch |
custom (grammar) | model sets apply_patch_tool_type |
Edit files (Chapter 11) |
update_plan |
function | [tools.update_plan] enabled = true; off by default |
Publish a step checklist |
view_image |
function | view_image on |
Load a local image |
request_user_input |
function | [tools.experimental_request_user_input]; on by
default |
Ask the user structured questions |
| MCP resource tools | function | an MCP server is configured, or the mode is
CodeModeOnly |
List and read MCP resources |
tool_search |
tool_search | model supports search, a tool is deferred | Find deferred tools by query |
web_search |
hosted web_search | provider supports it, mode not disabled | Search the web on the server |
Model catalog entries matter too. All 14 models in the bundled
models-manager/models.json set
"shell_type": "shell_command" and
"apply_patch_tool_type": "freeform" (counted for this
book).
Code mode is the default for most models
The catalog also sets the tool mode. In the bundled
models.json, 13 of the 14 models set
"tool_mode": "code_mode_only" and
"use_responses_lite": true; only gpt-5.5 sets
no tool mode and runs in Direct mode.
requested_tool_mode in core/src/tools/mod.rs
reads the catalog’s tool_mode first, then the
code_mode_only flag, then code_mode, else
Direct, so the catalog wins over your flags.
effective_tool_mode falls back to Direct only
for plain CodeMode when the code-mode host is unavailable
and disable_in_process_fallback is not set.
In CodeModeOnly,
is_hidden_by_code_mode_only drops every tool that code mode
can call from the direct list. The model sees the free-form
exec tool, which takes JavaScript, its wait
partner, and tools code mode cannot call, such as the
DirectModelOnly tool request_user_input.
Inside a script, each hidden tool is a function such as
await tools.exec_command({...}). A nested call comes back
to core as an ordinary ToolCall tagged
ToolCallSource::CodeMode, through the same registry, hooks,
orchestrator, and sandbox. Chapter 12 covers code mode in
depth.
Exposure: direct, deferred, hidden
Each registered tool carries a ToolExposure, defined in
codex-rs/tools/src/tool_executor.rs with six variants.
Direct tools go into the initial tool list.
Deferred tools stay out of the list but can be found
through tool_search. DirectModelOnly and
DeferredModelOnly keep a tool away from code mode.
CodeModeOnly exposes a tool only to code-mode scripts, and
Hidden keeps a tool dispatchable without showing it.
apply_mcp_tool_exposure_policy defers MCP tools when the
model supports search, which keeps a large MCP catalog out of the prompt
(see Chapter 17).
Three kinds of tool spec
Tool specs are ToolSpec values from
codex-rs/tools/src/tool_spec.rs. The enum is internally
tagged by type, and at this commit it has five variants:
function, namespace, tool_search,
web_search, and custom. There is no
local-shell variant. These five fall into three kinds.
Where the specs travel depends on the API. For a full Responses model
they go in the request’s tools array. For a Responses Lite
model, which is most of the bundled catalog,
build_responses_request in core/src/client.rs
sends no tools array; it prepends a developer-role
AdditionalTools input item instead, and
create_tools_json_for_responses_lite folds the function and
free-form tools into one functions namespace.
Function tools with a JSON schema
A function tool is a ResponsesApiTool: a name, a
description, a strict flag, an optional
defer_loading, and a JSON Schema for
parameters. Its output_schema is
#[serde(skip)]: it never reaches the API and serves only
code mode. This is the exec_command spec as the request
carries it, abridged from create_exec_command_tool in
core/src/tools/handlers/shell_spec.rs:
{
"type": "function",
"name": "exec_command",
"description": "Runs a command in a PTY, returning output or a session ID for ongoing interaction.",
"strict": false,
"parameters": {
"type": "object",
"properties": {
"cmd": {"type": "string", "description": "Shell command to execute."},
"tty": {"type": "boolean", "description": "True allocates a PTY for the command; false or omitted uses plain pipes."},
"workdir": {"type": "string", "description": "Working directory for the command. Defaults to the turn cwd."},
"yield_time_ms": {"type": "number", "description": "Wait before yielding output. Defaults to 10000 ms; effective range is 250-30000 ms."}
},
"required": ["cmd"],
"additionalProperties": false
}
}The full schema also has max_output_tokens,
shell, login,
sandbox_permissions, justification, and
prefix_rule. A namespace spec groups functions
under one name, such as clock for curr_time
and sleep; plain names fall into the default namespace
functions.
Free-form tools with a grammar
A custom tool is a FreeformTool. Instead of
a JSON schema it carries a format with a type,
a syntax, and a definition. For
apply_patch, the format is "type": "grammar"
and "syntax": "lark", and the definition is the Lark
grammar in core/assets/tools/apply_patch.lark. The model
then writes the raw patch text, not a JSON string with escaped newlines.
A call arrives as a custom_tool_call item with an
input string, and its result goes back as a
custom_tool_call_output. Code mode’s exec is a
free-form tool of the same kind.
Hosted tools
A hosted tool runs on the provider’s side, so Codex sends only
configuration. At this commit the only hosted spec is
web_search. create_web_search_tool in
core/src/tools/hosted_spec.rs maps the configured
WebSearchMode: Cached sends
external_web_access: false, Live sends
true, Indexed adds
indexed_web_access: true, and Disabled sends
nothing. hosted_model_tool_specs returns no hosted tools
when the model uses Responses Lite, because, as its comment says, that
API “accepts schemas for client-executed tools, not hosted Responses
tools.” Those models get web search from the client-executed
web.run extension tool instead, when the provider supports
search.
The router: from item to call
ToolRouter::build_tool_call in
core/src/tools/router.rs is the single translation point
between wire items and tool calls. It matches on the
ResponseItem and returns Ok(Some(ToolCall))
for three shapes and Ok(None) for everything else. The
function call arm, trimmed:
ResponseItem::FunctionCall { ref name, ref namespace, ref mut arguments, ref mut call_id, .. } => {
let tool_name =
ToolName::new(namespace.clone(), name.clone()).with_default_namespace();
// ...
Ok(Some(ToolCall {
tool_name,
call_id: call_id.into(),
payload: ToolPayload::Function { arguments },
encrypted_function_args,
native_call: retain_native_call.then(|| Arc::new(item)),
}))
}A ToolSearchCall becomes
ToolPayload::ToolSearch only when its
execution is "client"; a hosted search call
returns Ok(None). A CustomToolCall becomes
ToolPayload::Custom { input }. Everything else, including
the local_shell_call item that the protocol still defines,
is not a tool call.
handle_output_item_done in
core/src/stream_events_utils.rs acts on the result. For a
tool call it records the call item in history, queues
ToolCallRuntime::handle_tool_call as the step’s tool
future, and marks that the turn needs a follow-up request. Chapter 5 describes how the loop drains
those futures in call order.
The registry and the handler contract
There is no
ToolHandler trait
No trait named ToolHandler exists in
core/src/tools at this commit. The handler contract has two
layers instead. The shared one is ToolExecutor in
codex-rs/tools/src/tool_executor.rs, which extensions also
implement:
pub trait ToolExecutor<Input: ToolInput = BorrowedToolCall>: Send + Sync {
fn tool_name(&self) -> ToolName;
fn spec(&self) -> ToolSpec;
fn exposure(&self) -> ToolExposure { ToolExposure::Direct }
fn search_info(&self) -> Option<ToolSearchInfo> { /* ... */ }
fn supports_parallel_tool_calls(&self) -> bool { false }
// ...
fn handle<'a>(&'a self, invocation: Input::Call<'a>) -> ToolExecutorFuture<'a>;
}The core layer is
CoreToolRuntime: ToolExecutor<ToolInvocation> in
core/src/tools/registry.rs. Its doc comment calls it the
“Typed runtime contract for locally executed tools.” It adds defaults
for hooks, telemetry, environments, and cancellation, such as
matches_kind, which accepts function and tool-search
payloads. Each handler struct, such as ExecCommandHandler,
implements both traits, and the book’s term “tool handler” means this
pair.
ToolInvocation, the input every core handler receives,
bundles the session, turn, StepContext, cancellation token,
diff tracker, call_id, tool name, payload, environments,
and source, which says whether the call came from the model
or a code-mode script.
Dispatch, step by step
ToolRegistry stores an
IndexMap<ToolName, RegisteredTool>. Each entry holds
the runtime, its exposure for this step, a review policy, and an
optional per-step spec. dispatch_any_with_state runs every
call through the same sequence:
- Count the call in the turn state, then look up the tool. An unknown
name returns
unsupported call: {name}to the model. - Check
matches_kind. A payload of the wrong kind is aFatalerror. - Resolve the environments the call targets.
- Run
PreToolUsehooks, which can block the call or rewrite its input (Chapter 18). - Run a Guardian review if the tool requires one (multi-agent tools, under a Guardian setting).
- Notify lifecycle observers that the tool started, then run
handle. - Run
PostToolUsehooks, which can replace an accepted result with a message to the model.
Errors follow one rule: the model sees almost all of them. Of the
four FunctionCallError variants,
RespondToModel, FailedBeforeExecution, and
Blocked become an output item carrying the message, through
ToolCallRuntime::failure_response. Only Fatal
escapes as CodexErr::Fatal and ends the turn.
The orchestrator: approve, sandbox, run, retry
Handlers that start processes or write files hand a typed request and
a ToolRuntime to ToolOrchestrator::run in
core/src/tools/orchestrator.rs, which runs a fixed
sequence.
- Approval. It gets an
ExecApprovalRequirementfrom the runtime or the approval policy.Skipruns at once,Forbiddenrejects, andNeedsApprovalasks a reviewer or the user. - First attempt. It selects the platform sandbox unless the request or policy bypasses it, and runs the command.
- Retry on denial. If the sandbox denied the command, it may ask again
and rerun without the sandbox. Under the
NeverandOnRequestpolicies it returns the denial with the output instead, except thatOnRequestcan still prompt for a blocked network host.
This is a template method with typed strategies:
exec_command and apply_patch share one flow
and supply only their own request type and run step. Chapter 13 covers the approval decisions
and Chapter 14 the sandboxes.
Parallel calls through one lock
A Direct-mode model may return several tool calls in one response,
because the turn’s requests set parallel_tool_calls to
true; Responses Lite requests send false. In code mode, overlap comes
instead from a script that starts several nested calls, which a per-turn
code-mode worker admits through its own ToolCallRuntime
under the same rule. The rule lives in
core/src/tools/parallel.rs and uses one
tokio::sync::RwLock<()> per
ToolCallRuntime. Each call runs in its own spawned task,
and the task takes a guard before dispatch:
let guard = if supports_parallel {
Either::Left(lock.read().instrument(trace_span!("tool_dispatch.parallel_lock")).await)
} else {
Either::Right(lock.write().instrument(trace_span!("tool_dispatch.exclusive_lock")).await)
};The lock guards no data; it is a readers-writer admission gate for
work. supports_parallel comes from the handler’s
supports_parallel_tool_calls, except that
ToolRegistry forces it false for a Hidden
tool. The table shows which side each tool takes at this commit.
| Lock side | Tools |
|---|---|
| Read (overlap) | exec_command, write_stdin,
view_image, tool_search, MCP resource tools,
curr_time, get_context_remaining,
list_available_plugins_to_install, dynamic tools, V2
list_agents |
| Read if flagged | MCP tools whose tool_info.supports_parallel_tool_calls
is set or that carry a read_only_hint annotation |
| Write (alone) | apply_patch, update_plan,
request_user_input, spawn_agent, all others
with the default |
Why this split? The code states a reason only for MCP: a comment says
correctly implemented servers “should tolerate parallel calls to tools
that advertise themselves as read-only.” For the rest, the split follows
what each tool changes; this is inferred, not stated. Two patches racing
on one file would corrupt the turn diff, and update_plan
replaces shared state. The trade-off is that one slow exclusive call
blocks every other call behind it.
Two more rules sit around the lock. A call that arrives after the
work budget is exhausted returns ToolAbort::BeforeDispatch
without waiting. When the turn is cancelled, the task is aborted and the
output reports an abort, unless the handler
finishes_on_cancellation, as client-side dynamic tools
do.
Lifecycle events
Clients learn about tool progress through events.
ToolEmitter in core/src/tools/events.rs emits
a TurnItem::CommandExecution item when a command starts and
completes it with status, exit code, and output when it ends; a watcher
streams ExecCommandOutputDelta events between. Patches get
patch events and a TurnDiff event. The app server maps
these to item notifications (Chapter 21). Separately,
notify_tool_start and notify_tool_finish in
core/src/tools/lifecycle.rs inform extensions registered as
tool lifecycle contributors (Chapter 19).
Tracing one
exec_command call
Take the call from Chapter 3, made
by a Direct-mode model such as gpt-5.5. The model’s stream
finishes this item:
{"type": "function_call", "name": "exec_command", "call_id": "call_1",
"arguments": "{\"cmd\":\"cargo test -p parser\",\"yield_time_ms\":10000}"}handle_output_item_donecallsbuild_tool_call, which returns aToolCallnamedfunctions.exec_commandwith aFunctionpayload. The call item enters history.ToolCallRuntime::handle_tool_callspawns a task.exec_commandsupports parallel calls, so the task takes the read guard.dispatch_any_with_statefindsExecCommandHandler, checks the payload kind, and resolves the target environment.PreToolUsehooks run. They see the tool asBash, the nameHookToolName::bashreturns, with input{"command": ...}.ExecCommandHandler::handle_callparses the arguments, builds the shell argument vector, and checks whether the command is anapply_patchinvocation (Chapter 11).- The handler allocates a process ID and calls
UnifiedExecProcessManager::exec_command, which runs the orchestrator, spawns the process, and collects output until the yield time passes or the process exits (Chapter 10). - The handler returns an
ExecCommandToolOutput.PostToolUsehooks run on it. to_response_itemrenders a header and the output and wraps them throughfunction_tool_response.
The result is a function_call_output item. On the wire
its output is a plain string, because
FunctionCallOutputPayload serializes a text body as a
string:
{"type": "function_call_output", "call_id": "call_1",
"output": "Chunk ID: 3fa2c1\nWall time: 4.1027 seconds\nProcess exited with code 101\nOriginal token count: 812\nOutput:\n..."}The header format comes from
ExecCommandToolOutput::response_header; the values here are
illustrative. Chapter 10
explains each line.
A code-mode model makes the same call differently. It emits a
custom_tool_call to exec whose input is
JavaScript, such as
const r = await tools.exec_command({cmd: "cargo test -p parser"}); text(r.output);.
The nested call enters at step 2 with source
ToolCallSource::CodeMode and runs steps 2 to 7 unchanged.
Its result returns to the script as JSON from
code_mode_result, and the model reads only what the script
emits, in a custom_tool_call_output (Chapter 12).
The handler catalog
The table lists every handler in
core/src/tools/handlers/, one line each. The directory
holds 35 implementations of
ToolExecutor<ToolInvocation> (counted for this book);
the multi-agent handlers are grouped by version. Code mode’s
exec and wait handlers live in
core/src/tools/code_mode/ instead.
| Handler | Tool name | What it does |
|---|---|---|
ExecCommandHandler |
exec_command |
Starts a shell command (Chapter 10) |
WriteStdinHandler |
write_stdin |
Writes to or polls a running command |
ApplyPatchHandler |
apply_patch |
Verifies, approves, and applies a patch |
PlanHandler |
update_plan |
Emits the model’s checklist as PlanUpdate |
ViewImageHandler |
view_image |
Loads a local image into the conversation |
RequestUserInputHandler |
request_user_input |
Asks the user multiple-choice questions |
RequestUserInputAsyncHandler |
request_user_input_async |
Asks without blocking the turn |
SendMessageToUserAsyncHandler |
send_message_to_user_async |
Messages the user mid-turn |
RequestPermissionsHandler |
request_permissions |
Asks for extra file or network access |
ListMcpResourcesHandler |
list_mcp_resources |
Lists MCP resources |
ListMcpResourceTemplatesHandler |
list_mcp_resource_templates |
Lists MCP resource templates |
ReadMcpResourceHandler |
read_mcp_resource |
Reads one MCP resource |
McpHandler |
one per MCP tool | Calls a tool on an MCP server |
DynamicToolHandler |
client-defined | Forwards a call to the client and waits |
ExtensionToolAdapter |
extension-defined | Wraps an extension’s ToolExecutor |
ToolSearchHandler |
tool_search |
Searches deferred tools with BM25 ranking |
CurrentTimeHandler |
clock.curr_time |
Returns the current UTC time |
SleepHandler |
clock.sleep |
Waits, ending early on new input |
GetContextRemainingHandler |
get_context_remaining |
Reports tokens left in the window |
NewContextWindowHandler |
new_context |
Starts a new context window |
WaitForEnvironmentHandler |
wait_for_environment |
Waits for a deferred environment |
ListAvailablePluginsToInstallHandler |
list_available_plugins_to_install |
Lists installable plugins |
RequestPluginInstallHandler |
request_plugin_install |
Asks the user to install a plugin |
TestSyncHandler |
test_sync_tool |
Synchronizes tests; test only |
multi_agents handlers (V1) |
spawn_agent, send_input,
wait_agent, resume_agent,
close_agent |
Control sub-agents (Chapter 20) |
multi_agents_v2 handlers |
spawn_agent, send_message,
followup_task, wait_agent,
list_agents, interrupt_agent,
stop_agent |
Control sub-agents, newer runtime |
Status at commit 081295be9d. Bundled
catalog: 13 of 14 models use code_mode_only and Responses
Lite, overriding the code_mode flags.
shell_tool, unified_exec, and
view_image: STABLE, on by default. code_mode,
standalone_web_search,
request_permissions_tool, token_budget,
current_time_reminder, and deferred_executor:
UNDER DEVELOPMENT, off by default. Per-step tool plan, read/write
admission lock, and hook dispatch: IMPLEMENTED. The legacy
shell function tool and the Responses
local_shell tool: removed; ConfigShellToolType
keeps default, local, and
shell_command only as aliases for UnifiedExec.
Read in code, not run.
What breaks
| Symptom | Cause | Check |
|---|---|---|
Model gets unsupported call: shell |
Replayed history or an old prompt calls a removed tool | unsupported_tool_call_message in
registry.rs |
| No shell or patch tools at all | require_managed_sandbox set without a managed
profile |
add_core_tool_sources in spec_plan.rs |
| Turn fails with a tool collision error | Two tools share a name and error_on_tool_collisions is
on |
tool_registry.error_on_tool_collisions |
| An MCP tool is missing from the prompt | It was deferred behind tool_search |
apply_mcp_tool_exposure_policy |
| No web search in requests | Responses Lite, provider lacks it, or mode
disabled |
hosted_model_tool_specs |
| Calls run one at a time | One call holds the write guard, such as
apply_patch |
supports_parallel_tool_calls of each handler |
| Turn ends with a fatal tool error | Payload kind did not match the registered tool | matches_kind in CoreToolRuntime |
Code map
| What it is | Where it lives | Identifier |
|---|---|---|
| Per-step tool plan | codex:codex-rs/core/src/tools/spec_plan.rs |
build_tool_router |
| Shell tool conditions | codex:codex-rs/core/src/tools/spec_plan.rs |
add_shell_tools |
| Wire spec enum | codex:codex-rs/tools/src/tool_spec.rs |
ToolSpec |
| Shared tool contract and exposure | codex:codex-rs/tools/src/tool_executor.rs |
ToolExposure |
| Model item to tool call | codex:codex-rs/core/src/tools/router.rs |
build_tool_call |
| Core contract and dispatch | codex:codex-rs/core/src/tools/registry.rs |
dispatch_any_with_state |
| Parallel admission lock | codex:codex-rs/core/src/tools/parallel.rs |
parallel_execution |
| Approval, sandbox, retry | codex:codex-rs/core/src/tools/orchestrator.rs |
ToolOrchestrator |
Recall check
When does Codex decide which tools the model
sees?
Before every sampling request, when build_tool_router
builds a fresh registry from features, model fields, policy, MCP,
extensions, and client tools.
What are the three kinds of tool spec the Responses API
receives?
Function tools with a JSON schema, custom tools with a Lark grammar such
as apply_patch, and hosted tools such as
web_search.
Which trait does a core tool handler
implement?
ToolExecutor<ToolInvocation> plus
CoreToolRuntime; no ToolHandler trait exists
at this commit.
Why can exec_command calls overlap while
apply_patch calls cannot?
exec_command takes the read side of the admission lock;
apply_patch keeps the default and takes the write side, so
it runs alone.
What does the model see when a hook blocks a
call?
An ordinary output item carrying the block message; only a
Fatal error ends the turn instead.