Reuse MCP handlers across sampling steps (#37273)

## Why

MCP tool handlers and their Code Mode definitions are immutable for the lifetime
of a stable MCP binding, so rebuilding them for every sampling step repeats schema
construction unnecessarily.

## What changed

- Cache MCP handlers per session and reuse them while the same binding remains
  active, invalidating the cache when the binding changes.
- Lazily cache schema-free Code Mode definitions on MCP handlers while continuing
  to rebuild definitions for step-local tools whose specifications may change.
- Reapply current app enablement, tool policy, exposure, and plugin schema budgets
  whenever cached handlers are registered for a step.

## Testing

- Cover handler and Code Mode definition reuse, binding invalidation, changing app
  policy, stable continuation schemas, and step-local custom tool updates.

GitOrigin-RevId: 69c5011fb97c08580ac476e7fb2286b1e92e0359
This commit is contained in:
jif authored and copyberry committed 2026-08-06 13:37:07 +00:00
1 parent bfb6a6ea22
commit e1831db7c3
13 files changed
+439 -85

No files matched your search

+21 -4
View File
@@ -51,6 +51,16 @@ pub use codex_tools::ToolExposure;
/// Implementers provide the shared `ToolExecutor` behavior plus optional
/// core-owned metadata for hooks, telemetry, tool search, and argument diffs.
pub(crate) trait CoreToolRuntime: ToolExecutor<ToolInvocation> {
/// Returns a shared spec when both the spec and search metadata are immutable.
fn immutable_spec(&self) -> Option<&Arc<ToolSpec>> {
None
}
/// Returns lazily cached Code Mode definitions owned by this runtime.
fn cached_code_mode_definitions(&self) -> Option<&[codex_code_mode::ToolDefinition]> {
None
}
/// Returns a readiness wait for this exact tool before taking the execution gate.
fn wait_until_ready<'a>(&'a self, _session: &'a Arc<Session>) -> Option<BoxFuture<'a, ()>> {
None
@@ -385,15 +395,22 @@ impl ToolRegistry {
if !existing_description.trim().is_empty() {
continue;
}
let description = match tool.runtime.spec() {
ToolSpec::Namespace(namespace) => namespace.description,
let owned_spec;
let spec = if let Some(spec) = tool.runtime.immutable_spec() {
spec.as_ref()
} else {
owned_spec = tool.runtime.spec();
&owned_spec
};
let description = match spec {
ToolSpec::Namespace(namespace) => namespace.description.as_str(),
ToolSpec::Function(_)
| ToolSpec::Freeform(_)
| ToolSpec::ToolSearch { .. }
| ToolSpec::WebSearch { .. } => String::new(),
| ToolSpec::WebSearch { .. } => "",
};
if !description.trim().is_empty() {
*existing_description = description;
*existing_description = description.to_string();
}
}
namespaces