diff --git a/codex-rs/codex-mcp/src/connection_manager/tool_catalog.rs b/codex-rs/codex-mcp/src/connection_manager/tool_catalog.rs index a2f57bfc99..ad82d36ade 100644 --- a/codex-rs/codex-mcp/src/connection_manager/tool_catalog.rs +++ b/codex-rs/codex-mcp/src/connection_manager/tool_catalog.rs @@ -620,6 +620,45 @@ impl McpConnectionSet { .ok_or_else(unavailable) } + #[instrument(level = "trace", skip_all)] + pub(crate) async fn prepare_app_hook_call( + self: &Arc, + config: Arc, + tool: &str, + ) -> Result { + let server = McpServerKey::unscoped(CODEX_APPS_MCP_SERVER_NAME); + self.validate_tool_call(&server, tool)?; + let view = self + .servers + .get(&server) + .context("Apps runtime is unavailable")?; + let mut client = view + .connection + .client() + .await + .context("Could not start Apps server")?; + view.refresh_notified_catalog(CODEX_APPS_MCP_SERVER_NAME, &client) + .await; + client.tool_timeout = view.tool_timeout; + let snapshot = client.tool_catalog.read(Arc::new).await; + let mut matches = snapshot.tools.iter().filter(|info| info.tool.name == tool); + let info = matches.next().context("App hook tool is unavailable")?; + anyhow::ensure!(matches.next().is_none(), "App hook tool name is ambiguous"); + let exposure = config.mcp_server_catalog.exposure(); + let tools = + view.prepare_tools_for_model(vec![info.clone()], &self.tool_plugin_context, exposure); + let info = normalize_tools_for_model_with_prefix( + tools, + self.prefix_mcp_tool_names, + &self.non_prefixed_mcp_tool_servers, + exposure, + ) + .pop() + .context("App hook tool is unavailable")?; + self.prepare_call(info, Arc::new(client), config, snapshot) + .context("App hook tool is unavailable") + } + fn prepare_call( self: &Arc, tool_info: impl Into, diff --git a/codex-rs/codex-mcp/src/connection_manager_tests.rs b/codex-rs/codex-mcp/src/connection_manager_tests.rs index f52a285718..bc67f8a7a7 100644 --- a/codex-rs/codex-mcp/src/connection_manager_tests.rs +++ b/codex-rs/codex-mcp/src/connection_manager_tests.rs @@ -2671,11 +2671,16 @@ async fn capture_binding_preserves_ready_client_catalog_and_shares_prepared_meta .expect("metadata object") .clone(), )); + let mut app_only = create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "calendar.read_context"); + app_only.callable_namespace = "calendar".to_string(); + app_only.connector_id = Some("calendar".to_string()); + app_only.tool.meta = hidden_collision.tool.meta.clone(); let mut ready_client = create_test_managed_client(vec![ create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "client_local_tool"), create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "client_local_blocked"), visible_collision, hidden_collision, + app_only, ]) .await; let tool_filter = ToolFilter { @@ -2723,7 +2728,7 @@ async fn capture_binding_preserves_ready_client_catalog_and_shares_prepared_meta tool_approval_modes: HashMap::new(), }, ); - let manager = Arc::new(manager); + let mut manager = Arc::new(manager); assert_eq!( manager @@ -2783,6 +2788,39 @@ async fn capture_binding_preserves_ready_client_catalog_and_shares_prepared_meta ) .is_none() ); + + let config = Arc::clone(step.config()); + let expected = step + .tool_info( + &McpServerKey::unscoped(CODEX_APPS_MCP_SERVER_NAME), + "calendar.read_context", + ) + .expect("app-only tool metadata") + .clone(); + drop(prepared); + drop(step); + let (unrelated, mut started, _release) = + create_gated_async_managed_client(create_test_managed_client(Vec::new()).await); + let connections = Arc::get_mut(&mut manager).expect("no retained calls or bindings"); + connections.insert_test_client("unrelated", unrelated); + connections.required_servers = vec![McpServerKey::unscoped("unrelated")]; + + // A host hook prepares its hidden tool without starting an unrelated required server. + let prepared = tokio::select! { + result = manager.prepare_app_hook_call(Arc::clone(&config), "calendar.read_context") => { + result.expect("prepare the current Apps call") + } + _ = &mut started => panic!("App hook preparation started an unrelated server"), + }; + assert_eq!(prepared.tool_info(), &expected); + for tool in ["shared_cached_tool", "client_local_blocked", "collision"] { + assert!( + manager + .prepare_app_hook_call(Arc::clone(&config), tool) + .await + .is_err() + ); + } } #[tokio::test] diff --git a/codex-rs/codex-mcp/src/runtime.rs b/codex-rs/codex-mcp/src/runtime.rs index 5c40b67cbf..75def52531 100644 --- a/codex-rs/codex-mcp/src/runtime.rs +++ b/codex-rs/codex-mcp/src/runtime.rs @@ -28,6 +28,7 @@ use std::sync::atomic::AtomicU64; use std::sync::atomic::Ordering; use std::time::Duration; +use anyhow::Context; use arc_swap::ArcSwap; use async_channel::Sender; use codex_config::types::McpServerDisabledReason; @@ -722,6 +723,22 @@ impl McpRuntime { .await } + /// Prepares one host-owned App hook from its client's current catalog, including hidden tools. + /// Callable names are normalized for this call without capturing the model's global binding. + /// Callers must validate connector identity and current approval policy before dispatch. + pub async fn prepare_app_hook_call(&self, tool: &str) -> anyhow::Result { + let current = self.current.load_full(); + ensure_host_owned_apps_registration(¤t, CODEX_APPS_MCP_SERVER_NAME)?; + let config = current + .config + .as_ref() + .context("Apps runtime is unavailable")?; + current + .connections + .prepare_app_hook_call(Arc::clone(config), tool) + .await + } + /// Captures the current runtime after its selected server has finished startup. pub async fn current_binding_for_call(&self, server: &McpServerKey) -> Option> { let current = self.current.load_full(); @@ -780,6 +797,43 @@ impl McpRuntime { .await } + /// Capture before refreshing Core's MCP projection; retry preparation if refresh invalidates it. + /// Check again at dispatch so an old binding cannot bypass newer App policy. + pub fn capture_app_hook_admission(&self) -> impl Fn() -> anyhow::Result<()> + Send + Sync { + let (generation, current) = { + let generation = self + .catalog_publication + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + (*generation, self.current.load_full()) + }; + let auth_changes = current.auth_manager.as_ref().map(|manager| { + let mut changes = manager.auth_change_state_receiver(); + if !current.auth_matches(manager.auth_cached().as_ref()) { + changes.mark_changed(); + } + changes + }); + move || { + let publication = self + .catalog_publication + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let _auth = auth_changes + .as_ref() + .map(tokio::sync::watch::Receiver::borrow); + anyhow::ensure!( + *publication == generation + && Arc::ptr_eq(&self.current.load(), ¤t) + && auth_changes + .as_ref() + .is_none_or(|changes| matches!(changes.has_changed(), Ok(false))), + "App hook policy changed before dispatch" + ); + Ok(()) + } + } + /// Captures the current Apps client under Core's session permit. /// Await the returned fetch after releasing the permit. A stale result is skipped. pub fn capture_apps_tool_refresh( diff --git a/codex-rs/codex-mcp/src/runtime/apps_tool_refresh_tests.rs b/codex-rs/codex-mcp/src/runtime/apps_tool_refresh_tests.rs index 0009faaecd..4a79aab0f2 100644 --- a/codex-rs/codex-mcp/src/runtime/apps_tool_refresh_tests.rs +++ b/codex-rs/codex-mcp/src/runtime/apps_tool_refresh_tests.rs @@ -58,7 +58,13 @@ async fn stale_apps_refresh_does_not_publish() -> anyhow::Result<()> { _ = started.notified() => {} _ = &mut refresh => panic!("refresh completed before tools/list was released"), } + let admit_hook = runtime.capture_app_hook_admission(); + admit_hook()?; runtime.invalidate_apps_tool_refresh(); + assert!( + admit_hook().is_err(), + "pending config refresh revokes hook admission before publication" + ); release.notify_one(); assert!( refresh.await?.is_none(), @@ -71,7 +77,10 @@ async fn stale_apps_refresh_does_not_publish() -> anyhow::Result<()> { _ = started.notified() => {} _ = &mut refresh => panic!("refresh completed before tools/list was released"), } + let admit_hook = runtime.capture_app_hook_admission(); + admit_hook()?; auth_manager.logout().await?; + assert!(admit_hook().is_err(), "logout revokes hook admission"); release.notify_one(); assert!(refresh.await?.is_none(), "logout supersedes the fetch"); diff --git a/codex-rs/core/src/hook_mcp_executor.rs b/codex-rs/core/src/hook_mcp_executor.rs index 1ed54b8992..c44aa8a51d 100644 --- a/codex-rs/core/src/hook_mcp_executor.rs +++ b/codex-rs/core/src/hook_mcp_executor.rs @@ -1,18 +1,32 @@ +//! Executes hook MCP calls; bundled Apps require current connector and approval authority. + use std::sync::Arc; +use std::sync::OnceLock; +use std::sync::Weak; use anyhow::Context; use anyhow::bail; use codex_hooks::HookMcpCall; use codex_hooks::HookMcpExecutor; use codex_hooks::HookMcpOutput; +use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; use codex_mcp::McpRuntime; +use codex_mcp::McpToolCallResult; use codex_mcp::McpToolStartup; use codex_protocol::ThreadId; use futures::FutureExt; use futures::future::BoxFuture; use serde_json::Value; +use crate::mcp_tool_call::bundled_app_hook_connector; +use crate::session::session::Session; + +#[cfg(test)] +#[path = "hook_mcp_executor_tests.rs"] +mod tests; + pub(crate) struct CoreHookMcpExecutor { + pub(crate) session: OnceLock>, pub(crate) runtime: Arc, // Session-scoped MCP tools require the owning thread ID in request metadata. pub(crate) thread_id: ThreadId, @@ -29,19 +43,70 @@ impl HookMcpExecutor for CoreHookMcpExecutor { let call_result = tokio::time::timeout( call.timeout, - self.runtime.latest_call_tool( - &call.server, - &call.tool, - call.environment_id.as_deref(), - Some(Value::Object(call.input)), - Some(Value::Object(metadata)), - Some(call.timeout), - if call.skip_dormant_repl_cleanup { - McpToolStartup::SkipDormantReplCleanup + async { + if let Some(expected_connector) = call.expected_app_connector_id { + anyhow::ensure!( + call.server == CODEX_APPS_MCP_SERVER_NAME && call.environment_id.is_none(), + "bundled App hook must use the host Apps server" + ); + let session = self + .session + .get() + .and_then(Weak::upgrade) + .context("App hook session is unavailable")?; + loop { + // Invalidation happens before asynchronous publication. Capture first + // so refresh cannot pair new authority with an old runtime. + let admit = self.runtime.capture_app_hook_admission(); + session.refresh_mcp_if_dirty().await; + session.wait_for_apps_tool_refresh().await; + if admit().is_err() { + continue; + } + let prepared = self + .runtime + .prepare_app_hook_call(&call.tool) + .await; + if admit().is_err() { + continue; + } + let prepared = prepared?; + let result = prepared.call_with_admission( + Some(call.timeout), + || { + admit()?; + anyhow::ensure!( + bundled_app_hook_connector(&prepared) == Some(expected_connector), + "App hook connector or approval policy does not permit automatic execution" + ); + Ok(()) + }, + || async { + Ok((Some(Value::Object(call.input)), Some(Value::Object(metadata)))) + }, + ).await?; + // Never retry a dispatched call: it may already have had side effects. + break Ok(McpToolCallResult { + result, + source_tool_namespace: Some(prepared.tool_info().callable_namespace.clone()), + }); + } } else { - McpToolStartup::Wait - }, - ), + self.runtime.latest_call_tool( + &call.server, + &call.tool, + call.environment_id.as_deref(), + Some(Value::Object(call.input)), + Some(Value::Object(metadata)), + Some(call.timeout), + if call.skip_dormant_repl_cleanup { + McpToolStartup::SkipDormantReplCleanup + } else { + McpToolStartup::Wait + }, + ).await + } + }, ) .await .context("MCP hook timed out")??; diff --git a/codex-rs/core/src/hook_mcp_executor_tests.rs b/codex-rs/core/src/hook_mcp_executor_tests.rs new file mode 100644 index 0000000000..0dfc3738b3 --- /dev/null +++ b/codex-rs/core/src/hook_mcp_executor_tests.rs @@ -0,0 +1,116 @@ +#![cfg(test)] +//! App hook dispatch follows refreshed connector policy without exposing app-only tools. + +use super::*; +use crate::ConfigRefreshOutcome; +use crate::session::tests::make_session_and_context_with_auth_config_home_and_rx; +use codex_features::Feature; +use codex_login::CodexAuth; +use codex_mcp::McpServerKey; +use core_test_support::PathExt; +use core_test_support::apps_test_server::AppsTestServer; +use core_test_support::apps_test_server::recorded_apps_tool_calls; +use core_test_support::responses::start_mock_server; +use core_test_support::skip_if_no_network; +use pretty_assertions::assert_eq; +use serde_json::json; +use std::sync::Mutex; +use std::time::Duration; + +#[tokio::test] +async fn app_hook_dispatch_follows_current_policy() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + let server = start_mock_server().await; + let apps = AppsTestServer::mount_with_tools( + &server, + Arc::new(Mutex::new(vec![json!({ + "name": "calendar.read_context", + "description": "Read calendar context.", + "inputSchema": { "type": "object", "properties": {} }, + "annotations": { "readOnlyHint": true }, + "_meta": { + "connector_id": "calendar", "connector_name": "Calendar", + "ui": { "visibility": ["app"] }, + "_codex_apps": { + "resource_uri": "connector://calendar/tools/calendar.read_context", + "contains_mcp_source": true, "connector_id": "calendar", + }, + }, + })])), + ) + .await?; + let home = tempfile::tempdir()?; + let (session, _turn, _events) = make_session_and_context_with_auth_config_home_and_rx( + CodexAuth::create_dummy_chatgpt_auth_for_testing(), + Vec::new(), + home.path(), + |config| { + config.chatgpt_base_url = apps.chatgpt_base_url; + config.features.enable(Feature::Apps).unwrap(); + }, + ) + .await; + let executor = CoreHookMcpExecutor { + session: OnceLock::from(Arc::downgrade(&session)), + runtime: Arc::clone(&session.services.mcp_runtime), + thread_id: session.thread_id, + }; + for (policy, connector, allowed, calls) in [ + ("", "calendar", true, 1), + ( + "default_tools_approval_mode = 'prompt'", + "calendar", + false, + 1, + ), + ("enabled = false", "calendar", false, 1), + ("", "different_connector", false, 1), + ("", "calendar", true, 2), + ] { + let current = session.get_config().await; + let mut next = (*current).clone(); + next.config_layer_stack = next.config_layer_stack.with_user_config( + &next.codex_home.join("config.toml").abs(), + toml::from_str(&format!( + "[features]\napps = true\n[apps.calendar]\n{policy}" + ))?, + )?; + assert_eq!( + session.refresh_runtime_config(current, next).await, + ConfigRefreshOutcome::Published + ); + let result = executor + .execute(HookMcpCall { + expected_app_connector_id: Some(connector), + skip_dormant_repl_cleanup: false, + server: CODEX_APPS_MCP_SERVER_NAME.into(), + tool: "calendar.read_context".into(), + environment_id: None, + metadata: None, + input: Default::default(), + timeout: Duration::from_secs(30), + }) + .await; + assert_eq!( + ( + result.is_ok(), + recorded_apps_tool_calls(&server).await.len() + ), + (allowed, calls), + "{policy}: {:?}", + result.err() + ); + } + let binding = executor + .runtime + .current_binding_for_call(&McpServerKey::unscoped(CODEX_APPS_MCP_SERVER_NAME)) + .await + .unwrap(); + assert!( + binding + .tools() + .iter() + .all(|info| info.tool.name != "calendar.read_context") + ); + Ok(()) +} diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index 7496e7c894..c5a10b88df 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -2117,6 +2117,22 @@ pub(crate) fn build_guardian_mcp_tool_review_request( } } +/// Connector identity only when this exact App call is enabled and needs no user approval. +pub(crate) fn bundled_app_hook_connector(call: &PreparedMcpCall) -> Option<&str> { + let info = call.tool_info(); + if !call.is_host_owned_apps() { + return None; + } + let metadata = mcp_tool_metadata(info, call.plugin_id(), /*arguments*/ None).ok()?; + let policy = app_tool_policy(call.config(), &metadata, &info.tool.name); + if !policy.enabled + || requires_mcp_tool_approval_for_mode(metadata.annotations.as_ref(), policy.approval) + { + return None; + } + info.connector_id.as_deref() +} + fn mcp_tool_approval_policy( call: &PreparedMcpCall, metadata: &McpToolApprovalMetadata, diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index a02877afa7..c8d6395de3 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -1690,13 +1690,15 @@ impl Session { &session_configuration.disabled_plugin_ids, ) .await; + let hook_mcp_executor = Arc::new(CoreHookMcpExecutor { + runtime: Arc::clone(&mcp_runtime), + thread_id, + session: OnceLock::new(), + }); let (hooks, async_hook_results) = Hooks::new( hooks_config, thread_id, - Arc::new(CoreHookMcpExecutor { - runtime: Arc::clone(&mcp_runtime), - thread_id, - }), + hook_mcp_executor.clone(), )?; for warning in hooks.startup_warnings() { post_session_configured_events.push(Event { @@ -2033,6 +2035,7 @@ impl Session { forked_from_ordinal_exclusive, next_internal_sub_id: AtomicU64::new(0), }); + let _ = hook_mcp_executor.session.set(Arc::downgrade(&sess)); if let Some(startup) = &startup { startup.set_session(Arc::clone(&sess)); } diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index a6dd9d837e..c1c61c21dc 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -1014,6 +1014,7 @@ async fn preview_session_start_hooks( }, thread_id, Arc::new(CoreHookMcpExecutor { + session: Default::default(), runtime: Arc::new(McpRuntime::empty(config.prefix_mcp_tool_names())), thread_id, }), @@ -6950,6 +6951,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { }, thread_id, Arc::new(CoreHookMcpExecutor { + session: Default::default(), runtime: Arc::clone(&mcp_runtime), thread_id, }), @@ -9305,6 +9307,7 @@ where }, thread_id, Arc::new(CoreHookMcpExecutor { + session: Default::default(), runtime: Arc::clone(&mcp_runtime), thread_id, }), diff --git a/codex-rs/hooks/src/engine/discovery.rs b/codex-rs/hooks/src/engine/discovery.rs index 3dd05e7fe6..5d4c495d65 100644 --- a/codex-rs/hooks/src/engine/discovery.rs +++ b/codex-rs/hooks/src/engine/discovery.rs @@ -770,6 +770,7 @@ fn append_matcher_groups( NormalizedHandler { config, kind: ConfiguredHandlerKind::McpTool { + expected_app_connector_id: None, server, tool, input, diff --git a/codex-rs/hooks/src/engine/dispatcher.rs b/codex-rs/hooks/src/engine/dispatcher.rs index 73b1d9dd1b..2dc70c78ae 100644 --- a/codex-rs/hooks/src/engine/dispatcher.rs +++ b/codex-rs/hooks/src/engine/dispatcher.rs @@ -254,6 +254,7 @@ pub(super) async fn execute_handler( server, tool, input, + .. } => { run_mcp_tool( engine.mcp_executor.as_ref(), diff --git a/codex-rs/hooks/src/engine/mcp_runner.rs b/codex-rs/hooks/src/engine/mcp_runner.rs index dae2db346f..91d7a60fea 100644 --- a/codex-rs/hooks/src/engine/mcp_runner.rs +++ b/codex-rs/hooks/src/engine/mcp_runner.rs @@ -11,6 +11,7 @@ use serde_json::Map; use serde_json::Value; use super::ConfiguredHandler; +use super::ConfiguredHandlerKind; use super::HandlerRunResult; use super::HandlerSourcePath; use crate::mcp::HookMcpCall; @@ -77,6 +78,13 @@ pub(crate) async fn run_mcp_tool( skip_dormant_repl_cleanup: handler.builtin && is_node_repl_backed_server(server) && tool == "turn_ended", + expected_app_connector_id: match &handler.kind { + ConfiguredHandlerKind::McpTool { + expected_app_connector_id, + .. + } => *expected_app_connector_id, + ConfiguredHandlerKind::Command { .. } => None, + }, server: server.to_string(), tool: tool.to_string(), environment_id, diff --git a/codex-rs/hooks/src/engine/mcp_runner_tests.rs b/codex-rs/hooks/src/engine/mcp_runner_tests.rs index a1fe3ab723..1830ab6ac4 100644 --- a/codex-rs/hooks/src/engine/mcp_runner_tests.rs +++ b/codex-rs/hooks/src/engine/mcp_runner_tests.rs @@ -107,6 +107,7 @@ async fn mcp_tool_results_use_command_hook_output_contract() { source: HookSource::User, display_order: 0, kind: ConfiguredHandlerKind::McpTool { + expected_app_connector_id: None, server: "security".to_string(), tool: "scan".to_string(), input: configured_input.clone(), @@ -135,6 +136,7 @@ async fn mcp_tool_results_use_command_hook_output_contract() { assert_eq!( *calls.lock().expect("lock calls"), vec![HookMcpCall { + expected_app_connector_id: None, skip_dormant_repl_cleanup: false, server: "security".to_string(), tool: "scan".to_string(), diff --git a/codex-rs/hooks/src/engine/mod.rs b/codex-rs/hooks/src/engine/mod.rs index bfec9a847a..73f2b4df64 100644 --- a/codex-rs/hooks/src/engine/mod.rs +++ b/codex-rs/hooks/src/engine/mod.rs @@ -63,7 +63,7 @@ pub(crate) struct CommandShell { #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct ConfiguredHandler { - /// Internally admitted cleanup hook, enabled independently of per-hook state. + /// Internally admitted bundled hook, enabled independently of per-hook state. pub builtin: bool, pub plugin_trust: Option, pub event_name: codex_protocol::protocol::HookEventName, @@ -153,6 +153,7 @@ pub(crate) enum ConfiguredHandlerKind { r#async: bool, }, McpTool { + expected_app_connector_id: Option<&'static str>, server: String, tool: String, input: serde_json::Map, @@ -415,6 +416,7 @@ impl ClaudeHooksEngine { source: HookSource::Plugin, display_order, kind: ConfiguredHandlerKind::McpTool { + expected_app_connector_id: None, server, tool, input, diff --git a/codex-rs/hooks/src/engine/mod_tests.rs b/codex-rs/hooks/src/engine/mod_tests.rs index cdc9f626f6..c3ad7a9e80 100644 --- a/codex-rs/hooks/src/engine/mod_tests.rs +++ b/codex-rs/hooks/src/engine/mod_tests.rs @@ -1815,6 +1815,13 @@ fn bundled_cleanup_hooks_are_trusted_without_saved_hashes() { "{plugin_id} {event}" ); assert!(discovered.handlers[0].builtin, "{plugin_id} {event}"); + assert!(matches!( + discovered.handlers[0].kind, + ConfiguredHandlerKind::McpTool { + expected_app_connector_id: None, + .. + } + )); } } } @@ -2394,6 +2401,7 @@ fn executor_stop_hook_fixture() -> ( source: HookSource::Plugin, display_order: 0, kind: ConfiguredHandlerKind::McpTool { + expected_app_connector_id: None, server: "node_repl".to_string(), tool: "turn_ended".to_string(), input: serde_json::from_value(serde_json::json!({ @@ -2426,6 +2434,7 @@ fn executor_stop_hook_fixture() -> ( }; let expected_executor_call = HookMcpCall { + expected_app_connector_id: None, skip_dormant_repl_cleanup: true, server: "node_repl".to_string(), tool: "turn_ended".to_string(), @@ -2468,6 +2477,7 @@ async fn subagent_stop_paths_are_scoped_to_each_hook() { source_path: source_path.clone().into(), source: HookSource::User, kind: ConfiguredHandlerKind::McpTool { + expected_app_connector_id: None, server: "recorder".to_string(), tool: "capture".to_string(), input: serde_json::from_value(serde_json::json!({ @@ -2548,6 +2558,7 @@ async fn executor_stop_hooks_run_unless_regular_hooks_block_without_stopping() { source: HookSource::User, display_order: 0, kind: ConfiguredHandlerKind::McpTool { + expected_app_connector_id: None, server: "security".to_string(), tool: "check".to_string(), input: Default::default(), @@ -2562,6 +2573,7 @@ async fn executor_stop_hooks_run_unless_regular_hooks_block_without_stopping() { vec![ expected_executor_call.clone(), HookMcpCall { + expected_app_connector_id: None, skip_dormant_repl_cleanup: false, server: "security".to_string(), tool: "check".to_string(), @@ -2585,6 +2597,7 @@ async fn executor_stop_hooks_run_unless_regular_hooks_block_without_stopping() { source: HookSource::User, display_order: 1, kind: ConfiguredHandlerKind::McpTool { + expected_app_connector_id: None, server: "security".to_string(), tool: "terminate".to_string(), input: Default::default(), @@ -2601,6 +2614,7 @@ async fn executor_stop_hooks_run_unless_regular_hooks_block_without_stopping() { vec![ expected_executor_call.clone(), HookMcpCall { + expected_app_connector_id: None, skip_dormant_repl_cleanup: false, server: "security".to_string(), tool: "check".to_string(), @@ -2610,6 +2624,7 @@ async fn executor_stop_hooks_run_unless_regular_hooks_block_without_stopping() { timeout: Duration::from_secs(30), }, HookMcpCall { + expected_app_connector_id: None, skip_dormant_repl_cleanup: false, server: "security".to_string(), tool: "check".to_string(), @@ -2619,6 +2634,7 @@ async fn executor_stop_hooks_run_unless_regular_hooks_block_without_stopping() { timeout: Duration::from_secs(30), }, HookMcpCall { + expected_app_connector_id: None, skip_dormant_repl_cleanup: false, server: "security".to_string(), tool: "terminate".to_string(), @@ -2753,6 +2769,7 @@ async fn memory_consolidation_stop_preserves_policy_and_executor_cleanup() { executor_stop_hook_fixture(); request.target = StopHookTarget::MemoryConsolidation; let policy_call = HookMcpCall { + expected_app_connector_id: None, skip_dormant_repl_cleanup: false, server: "security".to_string(), tool: "check".to_string(), @@ -2765,6 +2782,7 @@ async fn memory_consolidation_stop_preserves_policy_and_executor_cleanup() { handler.source_path = cwd().join("hooks.json").into(); handler.source = source; handler.kind = ConfiguredHandlerKind::McpTool { + expected_app_connector_id: None, server: policy_call.server.clone(), tool: policy_call.tool.clone(), input: policy_call.input.clone(), @@ -2921,6 +2939,7 @@ async fn mcp_tool_hooks_expand_event_input_and_apply_pre_tool_decisions() { assert_eq!( *calls.lock().expect("lock MCP calls"), vec![HookMcpCall { + expected_app_connector_id: None, skip_dormant_repl_cleanup: false, server: "security".to_string(), tool: "scan".to_string(), @@ -3024,6 +3043,7 @@ async fn mcp_interrupt_hooks_expand_event_input_and_bound_timeout() { assert_eq!( *calls.lock().expect("lock MCP calls"), vec![HookMcpCall { + expected_app_connector_id: None, skip_dormant_repl_cleanup: false, server: "security".to_string(), tool: "notify".to_string(), diff --git a/codex-rs/hooks/src/mcp.rs b/codex-rs/hooks/src/mcp.rs index 9ac93b172a..b85b26e839 100644 --- a/codex-rs/hooks/src/mcp.rs +++ b/codex-rs/hooks/src/mcp.rs @@ -9,6 +9,8 @@ use serde_json::Value; pub struct HookMcpCall { /// A bundled REPL cleanup may skip a private local transport whose startup was never requested. pub skip_dormant_repl_cleanup: bool, + /// Exact bundled App identity; executors must enforce live connector and approval policy. + pub expected_app_connector_id: Option<&'static str>, pub server: String, pub tool: String, pub environment_id: Option, @@ -24,7 +26,7 @@ pub struct HookMcpOutput { pub source_tool_namespace: Option, } -/// Executes already-connected MCP tools on behalf of hooks without coupling this crate to core. +/// Executes MCP tools on behalf of hooks without coupling this crate to core. /// /// Implementations own server readiness, policy enforcement, timeout handling, and elicitation. pub trait HookMcpExecutor: Send + Sync {