17. MCP: Tools from Other Processes
Codex is an MCP client. It starts each configured server over stdio or streamable HTTP, lists its tools, renames them so the model sees short, unique names, and passes every call through an approval gate that reads the server’s own hints about what the tool does. The server runs in another process; Codex owns the names, the timeouts, the approval, and the truncation.
The Model Context Protocol (MCP) is an open protocol for giving a model tools that live outside the agent. A server announces tools with names, descriptions, and JSON schemas; a client lists and calls them over JSON-RPC. It is the main way to add a capability to Codex without changing Rust code, and the risk comes with it: the server is someone else’s code, its names can be anything, and its tools can delete data.
This chapter follows one MCP tool from configuration to result: the
[mcp_servers] table, the rmcp-client crate,
the codex-mcp connection manager, the naming rule, the call
path, approval, elicitation, and the codex mcp command-line
interface (CLI). The tool system that hosts MCP tools is in Chapter 9, and approvals in general are
in Chapter 13.
The picture
The model calls mcp__docs and search.
Core’s McpHandler binds the call to the connection that is
live now, so a catalog refresh cannot change which server answers. It
then raises an ApprovalAction::McpToolCall carrying the
tool’s annotations and approval mode, and hooks, a reviewer, or the user
answer. Only an approved call reaches
PreparedMcpCall::call_with_admission, which sends
tools/call with the raw tool name over the bound
connection. The server may send elicitation/create to ask
the user something, and Codex pauses tool-result delivery until the
answer comes. The result is truncated to a token budget before the model
sees it.
Configuring a server
The [mcp_servers] table
Each server is one table in config.toml, keyed by a name
you choose. It deserializes into McpServerConfig in
codex-rs/config/src/mcp_types.rs, which flattens a
transport and adds policy fields. The example below is composed from
those fields; it is illustrative, not a repository fixture.
[mcp_servers.docs] # stdio: "command" is present
command = "npx"
args = ["-y", "@example/docs-mcp"]
env_vars = ["GITHUB_TOKEN", { name = "API_KEY", source = "local" }]
startup_timeout_sec = 20 # default 30
tool_timeout_sec = 120 # default 300
required = true
enabled_tools = ["search", "fetch"]
default_tools_approval_mode = "writes" # auto | prompt | writes | approve
[mcp_servers.docs.tools.fetch]
approval_mode = "approve"
output_token_limit = 4000
[mcp_servers.linear] # streamable HTTP: "url" is present
url = "https://mcp.example.com/mcp"
bearer_token_env_var = "LINEAR_TOKEN"
startup_readiness = "catalog"The present key chooses the transport. The deserializer builds
McpServerTransportConfig::Stdio when command
is set, StreamableHttp when url is set, and
fails with “invalid transport” otherwise. A field from the other
transport fails with “{field} is not supported for {transport}”. An
inline bearer_token is rejected for both, so a token
arrives only through bearer_token_env_var, which names an
environment variable. The smallest valid table is the test fixture
command = "echo".
Filters, timeouts, and per-tool settings
ToolFilter in
codex-rs/codex-mcp/src/tools.rs allows a tool when there is
no enabled_tools list or the tool is on it, and when it is
not on disabled_tools. Two timeouts bound a server, both
defined in codex-rs/codex-mcp/src/rmcp_client.rs.
startup_timeout_sec covers the handshake and first listing,
with DEFAULT_STARTUP_TIMEOUT at 30 seconds.
tool_timeout_sec bounds each call, with
DEFAULT_TOOL_TIMEOUT at 300 seconds. Per-tool tables hold
approval_mode and output_token_limit; the
second replaces the model’s default truncation policy for that tool’s
result.
The client:
rmcp-client
Two transports
RmcpClient in
codex-rs/rmcp-client/src/rmcp_client.rs wraps the
rmcp library; configured servers use its stdio and
streamable HTTP constructors.
For stdio, a launcher decides where the process runs. The module
comment in
codex-rs/rmcp-client/src/stdio_server_launcher.rs names
two: LocalStdioServerLauncher starts the command as a child
of the orchestrator, and ExecutorStdioServerLauncher starts
it through the executor process API. Both return the same
StdioServerTransport, so the client never knows where the
process lives. This strategy pattern lets a remote executor host a
server without a second client. One JSON-RPC line is capped at 8 MiB
(MAX_MCP_STDIO_LINE_BYTES), and a stopping server’s process
group gets 2 seconds of grace after SIGTERM.
Streamable HTTP retries the initialization handshake, not tool calls.
STREAMABLE_HTTP_RETRY_DELAYS_MS is
[250, 1_000], so a retryable initialize error gets at most
three attempts inside the startup timeout.
McpProtocolMode::Legacy, the default, prefers MCP
2025-06-18, and Config::mcp_protocol_mode selects the
2026-07-28 revision only when the mcp_2026_07_28 feature is
on.
OAuth login and token storage
The auth key selects one of three flows for an HTTP
server. The default, oauth, uses stored OAuth credentials.
chatgpt uses the ChatGPT session for servers on the trusted
first-party origin. ema_auth exchanges an enterprise
identity provider token and, per its doc comment, permits no
fallback.
codex-rs/rmcp-client/src/oauth.rs stores MCP OAuth
tokens in the operating system keyring under “Codex MCP Credentials”
(KEYRING_SERVICE): the macOS Keychain, the Windows
Credential Manager, or the Secret Service and keyutils on Linux. When
the keyring is absent or fails, tokens go to
CODEX_HOME/.credentials.json. The
mcp_oauth_credentials_store setting picks auto
(default), file, or keyring; under
auto a client keeps the store it first resolved, so a
refresh cannot switch to a stale copy. Tokens refresh 30 seconds before
expiry (REFRESH_SKEW_MILLIS), and an interactive login
waits up to 300 seconds.
The connection manager:
codex-mcp
Startup and readiness
At session start, Session::install_initial_mcp_runtime
in codex-rs/core/src/session/mcp_runtime.rs publishes an
MCP runtime and calls validate_required_servers.
McpConnectionSet::new creates one managed client per
enabled server. Each client’s startup is a shared future, so the first
caller waits and later callers reuse the result.
A server with required = true blocks session start.
validate_required_servers in
codex-rs/codex-mcp/src/connection_manager/required.rs waits
for each one and fails the session with “required MCP servers failed to
initialize: …”. The exception is
startup_readiness = "catalog", where a valid cached catalog
satisfies readiness while the live connection starts; tool calls still
need the connection.
An optional server never blocks a turn for long.
wait_for_binding_startup in
codex-rs/codex-mcp/src/connection_manager/tool_catalog.rs
gives pending optional servers a shared grace of 1 second
(DEFAULT_OPTIONAL_MCP_STARTUP_GRACE). A server not ready by
then is left out of that step’s tools, or represented by its cached
catalog. When a startup timeout fires,
mcp_init_error_display tells the user to set
startup_timeout_sec under
[mcp_servers.<name>].
Listing and caching
Listing pages through tools/list within fixed limits in
codex-rs/codex-mcp/src/pagination.rs: 100 pages, 2,048
items (8,192 for the host-owned Apps server), a 64 KiB cursor, and 30
seconds. Each listed tool becomes a ToolInfo, with the
server’s instructions as its namespace description.
A process-wide least recently used (LRU) cache,
McpToolCatalogCache, keeps reusable catalogs: 32 entries,
valid for 30 minutes each. The stable feature
mcp_lazy_stdio_startup uses a warm catalog to defer
optional stdio servers in regular chats. Then
append_mcp_tools in
codex-rs/core/src/mcp_tool_exposure.rs registers the tools
as ToolExposure::Deferred when the model supports tool
search (model_info.supports_search_tool) and as
Direct otherwise. Deferred tools stay out of the prompt
until the model finds them through tool search (see Chapter 9). Tools from agent plugins
get a byte budget, 8,000 bytes per spec and 64,000 in total, and
overflow is registered Hidden.
Naming tools for the model
Raw MCP names cannot go to the model as they are. Two servers can
both export search, names can hold characters the Responses
API rejects, and long names can exceed its limit. ToolInfo
therefore keeps two names: tool.name, sent back to the
server in tools/call, and the model-facing pair
callable_namespace and callable_name.
normalize_tools_for_model_with_prefix in
codex-rs/codex-mcp/src/tools.rs computes the pair:
where
[A-Za-z0-9_] with
_ (sanitize_responses_api_tool_name),
mcp__
prefix is skipped when
non_prefixed_mcp_tool_names is on (for every server, or
only for the servers its server_names list names).
Collisions get a suffix
unique_callable_parts checks that
where
__, and 13 is the
length of
A worked example: raw tool search on server
docs becomes namespace mcp__docs and name
search, and a hook matcher sees
mcp__docs__search. Servers named my.docs and
my-docs both sanitize to mcp__my_docs, so each
namespace gains its own 12-digit suffix. Keeping the raw name for the
protocol and an alias for the model is the two-names pattern; its cost
is log names such as mcp__my_docs_1a2b3c4d5e6f that you map
back by hand.
Calling a tool
McpHandler::handle_call in
codex-rs/core/src/tools/handlers/mcp.rs serves every MCP
tool, and handle_mcp_tool_call in
codex-rs/core/src/mcp_tool_call.rs does the work:
Session::prepare_mcp_callbinds the call to the current connection; a comment says “a later catalog refresh must not change eligibility.”- The handler picks the truncation policy: the tool’s
output_token_limitasTruncationPolicy::Tokens, or the model default. parse_mcp_tool_argumentsparses the arguments. Malformed JSON returns a result startingerr:to the model instead of failing the turn.mcp_tool_approval_policyresolves the approval mode. An Apps tool that app configuration disables is skipped with “MCP tool call blocked by app configuration”.maybe_request_mcp_tool_approvaldecides whether to ask. A denial, timeout, or cancel returns an error result to the model.- Core adds its own
SandboxStateto_metawhen the server advertisescodex/sandbox-state-meta. ThenPreparedMcpCall::call_with_admissionincodex-rs/codex-mcp/src/binding.rssendstools/callon the bound connection. The host’s direct path,McpConnectionSet::call_tool, also strips host-owned keys (entitlement context and sandbox state) from caller-supplied_meta. - Core emits begin and end events and returns
McpToolOutput, truncated to its budget.
The timeout in step 6 is:
where
/*requested_timeout*/ None, so
in practice the server value governs. The output budget is
output_token_limit or the model default and
1.2 is the 20 percent allowance in
with_serialization_allowance.
Approving MCP tool calls
Hints and modes
Codex reads three MCP tool annotations: read_only_hint,
destructive_hint, and open_world_hint. The
approval mode decides how far to trust them. It comes from the tool’s
approval_mode, then the server’s
default_tools_approval_mode, then auto. The
decision is short, in
codex-rs/core/src/mcp_tool_call.rs:
fn requires_mcp_tool_approval_for_mode(
annotations: Option<&ToolAnnotations>,
approval_mode: AppToolApproval,
) -> bool {
match approval_mode {
AppToolApproval::Auto => requires_mcp_tool_approval(annotations),
AppToolApproval::Prompt => true,
AppToolApproval::Writes => !annotations
.and_then(|annotations| annotations.read_only_hint)
.unwrap_or(false),
AppToolApproval::Approve => false,
}
}Under auto, requires_mcp_tool_approval
skips the prompt when read_only_hint is true, and otherwise
asks when destructive_hint or open_world_hint
is true or absent. The table shows whether Codex asks, by mode and by
what the hints say.
| Mode | Read-only hint true | Destructive or open-world true or absent | Both false, not read-only |
|---|---|---|---|
auto (default) |
No | Ask | No |
writes |
No | Ask | Ask |
prompt |
Ask | Ask | Ask |
approve |
No | No | No |
Two shortcuts run first.
mcp_permission_prompt_is_auto_approved in
codex-rs/codex-mcp/src/mcp/mod.rs skips the prompt when the
mode is approve, or when approval_policy is
never and the permission profile is disabled, external, or
has full disk write access. Strict auto review disables both shortcuts.
A call that needs approval under policy never is denied
with “MCP tool call requires approval, but approval policy is
never”.
The hints come from the server, so a destructive tool marked
read_only_hint: true passes silently under
auto and writes. Use prompt for a
server you do not control.
Combining policies
When configuration layers and requirements each set a mode,
AppToolApproval::restrict_to in
codex-rs/config/src/mcp_types.rs keeps the stricter one.
prompt beats everything, and approve yields to
the other mode. Its doc comment explains the one surprise:
auto and writes “are incomparable: each can
require approval for a tool the other would approve. Their conservative
intersection is Prompt.”
Remembering a decision
The prompt offers “Allow”, “Allow for this session”, “Allow and don’t
ask me again”, and “Cancel”. It runs only after
PermissionRequest hooks and the reviewer policy (see Chapter 13). Grants are keyed by
McpToolApprovalKey: server key, plugin id, connector id,
account link id, and tool name. Remembered grants exist only in
auto mode.
“Allow for this session” stores the key in the session’s in-memory
approval store. “Allow and don’t ask me again” writes
approval_mode = "approve" into the project config layer
that defines the server, or else into user config, under
[mcp_servers.<server>.tools.<tool>], or the
matching apps or plugins path, then reloads
the user layer. That option needs the
tool_call_mcp_elicitation feature (STABLE, on by default)
and never appears for servers from a selected plugin or scoped to one
environment, because saved config, keyed by a bare server name, cannot
name that exact owner.
A third lifetime belongs to the host. A host that keeps threads across processes can attach a store that Core checks before it prompts:
pub trait McpToolApprovalStore: Send + Sync {
/// Check the current principal and exact key without blocking, including at handoff.
fn contains(&self, thread_id: ThreadId, key: &McpToolApprovalKey) -> bool;
/// Atomically add a single grant. Publish it to `contains` only after durable acknowledgement.
fn save<'a>(
&'a self,
thread_id: ThreadId,
key: &'a McpToolApprovalKey,
) -> BoxFuture<'a, anyhow::Result<()>>;
}The doc comment tells the host to bind each instance to one
authenticated workspace member and to check that member on every lookup
and save. Core consults the store only for host-owned Apps tools in
auto mode with both a connector id and a link id, and saves
only when the user answered. Core does not persist these grants itself;
the trait keeps them tied to a principal that only the host knows. No
implementation exists in the open-source tree.
Elicitation
Elicitation is the server asking the user a question mid-call, as a
form with a JSON schema or as a URL. The callback built in
codex-rs/codex-mcp/src/elicitation.rs applies policy before
any prompt:
- A request whose approval kind is a tool suggestion is declined.
- A request with no authority or permission profile for the server is declined.
- A form with an empty schema, a pure confirmation, is accepted when permission prompts would be auto-approved.
elicitation_is_rejected_by_policydeclines whenapproval_policyisnever, orgranularwithout MCP elicitations.- Otherwise a reviewer may answer, or Codex emits an event and waits for the client.
While an elicitation is outstanding, Core’s
ElicitationService in
codex-rs/core/src/elicitation.rs holds two
reference-counted pauses, on tool-result delivery and on command
timeouts. A slow answer cannot make an unrelated command time out, but a
leaked guard stalls the turn.
The codex mcp CLI
McpSubcommand in
codex-rs/cli/src/mcp_cmd.rs has six subcommands:
list, get, add,
remove, login, and logout.
add takes --url or a trailing
-- <COMMAND>..., and clap requires exactly one.
codex mcp add docs -- npx -y @example/docs-mcp
codex mcp add linear --url https://mcp.example.com/mcp --oauth-client-registration dcr
codex mcp login linear --scopes read,write --no-browser
codex mcp list --jsonadd writes a global server entry and, for an HTTP server
that supports OAuth, prints “Detected OAuth support. Starting OAuth
flow…” and logs in at once. login --no-browser accepts a
pasted callback URL, which suits a remote shell.
Codex as a server: a short history
Codex used to be an MCP server too. Commit 531f3836a1e
(2026-09-05) is “Remove the deprecated codex mcp-server
command (#42993)”, and at the pinned commit the CLI’s
Mcp(McpCli) variant reads “Manage external MCP servers for
Codex”.
The one standalone MCP server crate left is
message-board-mcp. Its README describes
MessageBoardMcpServer as an
rmcp::ServerHandler over the agent message-board tools. Its
HTTP binary listens on 127.0.0.1:7777 by default and reads
a bearer token from CODEX_MESSAGE_BOARD_TOKEN; it ships as
a plugin (see Chapter 18
and Chapter 20). Two smaller servers
exist outside that crate: the terminal UI (TUI) runs a private loopback
server, DynamicToolMcpServer, for its own client-owned
tools, and codex-rs/rmcp-client/src/bin holds test
servers.
Status at commit 081295be9d. MCP client
over stdio and streamable HTTP: IMPLEMENTED.
tool_call_mcp_elicitation,
mcp_lazy_stdio_startup,
mcp_connection_sharing: STABLE, on by default.
mcp_2026_07_28, mcp_tool_list_changed,
non_prefixed_mcp_tool_names: UNDER DEVELOPMENT, off.
codex mcp-server: removed on 2026-09-05. OAuth token
storage: PLATFORM-SPECIFIC keyring with a file fallback. Read in code,
not run.
What breaks
| Symptom | Cause | Check |
|---|---|---|
“MCP client for x timed out after 30 seconds” |
Slow first start, such as an npx download |
Raise startup_timeout_sec under
[mcp_servers.x] |
| “required MCP servers failed to initialize” | A required = true server did not start |
validate_required_servers; consider
startup_readiness = "catalog" |
| “bearer_token is not supported for streamable_http” | Inline token in TOML | Use bearer_token_env_var |
Tool name ends in _ and 12 hex digits |
Names collided, or the joined name exceeded 128 | normalize_tools_for_model_with_prefix |
| MCP tool never prompts | Mode approve, or never with full
access |
mcp_permission_prompt_is_auto_approved |
| “interactive approval is unavailable in exec mode” | A headless run needed a prompt | Set the tool’s approval_mode |
| Elicitation silently declined | Policy never, or granular without MCP elicitations |
elicitation_is_rejected_by_policy |
codex mcp-server not found |
Removed on 2026-09-05 | git show 531f3836a1e |
Code map
| What it is | Where it lives | Identifier |
|---|---|---|
| Server config and transports | codex:codex-rs/config/src/mcp_types.rs |
McpServerConfig |
| Protocol client | codex:codex-rs/rmcp-client/src/rmcp_client.rs |
RmcpClient |
| OAuth token storage | codex:codex-rs/rmcp-client/src/oauth.rs |
KEYRING_SERVICE |
| Connection set and calls | codex:codex-rs/codex-mcp/src/connection_manager.rs |
McpConnectionSet |
| Model-facing names | codex:codex-rs/codex-mcp/src/tools.rs |
normalize_tools_for_model_with_prefix |
| Call path and approval | codex:codex-rs/core/src/mcp_tool_call.rs |
requires_mcp_tool_approval_for_mode |
| Elicitation policy | codex:codex-rs/codex-mcp/src/elicitation.rs |
elicitation_is_rejected_by_policy |
| CLI subcommands | codex:codex-rs/cli/src/mcp_cmd.rs |
McpSubcommand |
Recall check
Which config key decides whether a server uses stdio or
streamable HTTP?
command selects stdio and url selects
streamable HTTP; neither is “invalid transport”.
What does the model see for raw tool search on
server docs, and what does a hook see?
Namespace mcp__docs with name search; hooks
and logs see mcp__docs__search.
Under auto, does a tool with no annotations need
approval?
Yes: absent destructive and open-world hints count as true, so Codex
asks.
Why do auto and writes combine to
prompt?
Each can approve a tool the other would ask about, so the only safe
common policy is to always ask.
What does an outstanding elicitation pause?
Tool-result delivery and command timeouts, through the reference-counted
ElicitationService.