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

+3
View File
@@ -14,6 +14,7 @@ use crate::environment_selection::ThreadEnvironments;
use crate::exec_policy::ExecPolicyManager;
use crate::guardian::GuardianRejectionCircuitBreaker;
use crate::mcp::McpManager;
use crate::mcp_tool_exposure::McpHandlerCache;
use crate::tools::ExecutedToolCallRecorder;
use crate::tools::code_mode::CodeModeService;
use crate::tools::handlers::ToolSearchHandlerCache;
@@ -45,6 +46,8 @@ use tokio::sync::Mutex;
pub(crate) struct SessionServices {
/// The single owner of live MCP connections for this thread.
pub(crate) mcp_runtime: Arc<McpRuntime>,
/// Immutable MCP handlers scoped to this thread's current binding.
pub(crate) mcp_handler_cache: McpHandlerCache,
pub(crate) unified_exec_manager: UnifiedExecProcessManager,
pub(crate) elicitations: ElicitationService,
#[cfg_attr(not(unix), allow(dead_code))]