//! Verifies that MCP user-verification ceremonies are never honored for a user-configured //! server: the capability is stripped and any request is refused without prompting. use std::sync::Arc; use std::time::Duration; use anyhow::Result; use axum::Router; use codex_config::Constrained; use codex_core::StartThreadOptions; use codex_protocol::mcp::ClientMcpExtensions; use codex_protocol::mcp::OPENAI_ELICITATION_EXTENSION_ID; use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; use core_test_support::mcp_test_server::MCP_TEST_SERVER_NAME; use core_test_support::mcp_test_server::MCP_TEST_SERVER_PATH; use core_test_support::mcp_test_server::mcp_server_builder; use core_test_support::responses::start_mock_server; use pretty_assertions::assert_eq; use rmcp::ServerHandler; use rmcp::model::CallToolRequestParams; use rmcp::model::CallToolResponse; use rmcp::model::CallToolResult; use rmcp::model::ContentBlock; use rmcp::model::CustomRequest; use rmcp::model::ServerCapabilities; use rmcp::model::ServerConfig; use rmcp::model::ServerRequest; use rmcp::service::RequestContext; use rmcp::service::RoleServer; use rmcp::transport::StreamableHttpServerConfig; use rmcp::transport::StreamableHttpService; use rmcp::transport::streamable_http_server::session::local::LocalSessionManager; use serde_json::Value; use serde_json::json; use tokio::net::TcpListener; use tokio::sync::Mutex; use tokio::time::timeout; use tokio_util::task::AbortOnDropHandle; #[derive(Clone)] struct VerificationServer { response: Arc>>, elicitation_extension: Arc>>>, } impl ServerHandler for VerificationServer { fn get_info(&self) -> ServerConfig { ServerConfig::new(ServerCapabilities::builder().enable_tools().build()) } async fn call_tool( &self, _request: CallToolRequestParams, context: RequestContext, ) -> Result { *self.elicitation_extension.lock().await = Some( context .client_capabilities() .and_then(|capabilities| capabilities.extensions) .and_then(|extensions| extensions.get(OPENAI_ELICITATION_EXTENSION_ID).cloned()) .map(Value::Object), ); let result = context .peer .send_request(ServerRequest::CustomRequest(CustomRequest::new( "openai/elicitation/create", Some(json!({ "mode": "openai/userVerification", "title": "Approve purchase", "description": "Pay $200 to Example Store", "challenge": "AAECA_7_", "_meta": {"example/display": {"label": "Operation"}}, })), ))) .await; let outcome = match result { Ok(result) => serde_json::to_value(result).map_err(|error| { rmcp::ErrorData::internal_error(error.to_string(), /*data*/ None) })?, Err(error) => json!({ "error": error.to_string() }), }; *self.response.lock().await = Some(outcome); Ok(CallToolResult::success(vec![ContentBlock::text("unverified")]).into()) } } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn user_verification_mcp_request_is_cancelled_without_prompt_in_full_access() -> Result<()> { let received = Arc::new(Mutex::new(None)); let elicitation_extension = Arc::new(Mutex::new(None)); let server = VerificationServer { response: Arc::clone(&received), elicitation_extension: Arc::clone(&elicitation_extension), }; let service = StreamableHttpService::new( move || Ok(server.clone()), Arc::new(LocalSessionManager::default()), StreamableHttpServerConfig::default(), ); let listener = TcpListener::bind("127.0.0.1:0").await?; let base_url = format!("http://{}", listener.local_addr()?); let router = Router::new().nest_service(MCP_TEST_SERVER_PATH, service); let _server = AbortOnDropHandle::new(tokio::spawn(async move { axum::serve(listener, router).await.unwrap(); })); let model_server = start_mock_server().await; let test = mcp_server_builder(base_url) .with_config(|config| { config.permissions.approval_policy = Constrained::allow_any(AskForApproval::Never); config .permissions .set_permission_profile(PermissionProfile::Disabled) .unwrap(); }) .build_with_auto_env(&model_server) .await?; // Even a host that declares the user-verification capability must not grant it to an // ordinary user-configured MCP server. let thread = test .thread_manager .start_thread(StartThreadOptions { client_mcp_extensions: ClientMcpExtensions::new([( OPENAI_ELICITATION_EXTENSION_ID.to_string(), json!({"userVerification": {}}), )]), environments: Some(vec![test.executor_environment().request()]), ..StartThreadOptions::new(test.config.clone()) }) .await? .thread; let caller = Arc::clone(&thread); let call = AbortOnDropHandle::new(tokio::spawn(async move { caller .call_mcp_tool( MCP_TEST_SERVER_NAME, "verify_action", /*arguments*/ None, /*meta*/ None, ) .await })); // The ceremony is refused without surfacing a prompt, so the call completes unattended. assert_eq!( timeout(Duration::from_secs(/*secs*/ 10), call).await???, codex_protocol::mcp::CallToolResult { content: vec![json!({"type": "text", "text": "unverified"})], structured_content: None, is_error: Some(false), meta: None, }, ); // Without the capability the client rejects the request outright; it never returns a // proof or an acceptance. let outcome = received .lock() .await .clone() .expect("server recorded the verification outcome"); let error = outcome["error"] .as_str() .unwrap_or_else(|| panic!("user verification must not succeed: {outcome}")); assert!(error.contains("-32601"), "{error}"); let advertised = elicitation_extension .lock() .await .clone() .expect("tool call recorded the client capabilities"); assert!( advertised .as_ref() .and_then(|settings| settings.get("userVerification")) .is_none(), "user verification capability leaked to the server: {advertised:?}" ); while let Ok(Ok(event)) = timeout(Duration::from_millis(/*millis*/ 200), thread.next_event()).await { assert!( !matches!(event.msg, EventMsg::ElicitationRequest(_)), "user verification must not prompt: {event:?}" ); } thread.shutdown_and_wait().await?; test.codex.shutdown_and_wait().await?; Ok(()) }