aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -0,0 +1,67 @@
use std::ffi::OsString;
use std::sync::Arc;
use std::sync::Mutex;
use akode_exec_server::ExecBackend;
use akode_exec_server::ExecBackendFuture;
use akode_exec_server::ExecParams;
use akode_exec_server::ExecServerError;
use akode_rmcp_client::ExecutorStdioServerLauncher;
use akode_rmcp_client::RmcpClient;
use akode_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
#[derive(Default)]
struct RecordingExecBackend {
params: Mutex<Option<ExecParams>>,
}
impl ExecBackend for RecordingExecBackend {
fn start(&self, params: ExecParams) -> ExecBackendFuture<'_> {
let mut recorded_params = match self.params.lock() {
Ok(recorded_params) => recorded_params,
Err(poisoned) => poisoned.into_inner(),
};
*recorded_params = Some(params);
Box::pin(async {
Err(ExecServerError::Protocol(
"stop after recording executor request".to_string(),
))
})
}
}
#[tokio::test]
async fn executor_stdio_forwards_foreign_absolute_cwd_as_path_uri() {
#[cfg(not(windows))]
let cwd = r"C:\Users\openai\share";
#[cfg(windows)]
let cwd = "/home/openai/share";
#[cfg(not(windows))]
let expected_cwd: PathUri = "file:///C:/Users/openai/share"
.parse()
.expect("expected cwd should be a path URI");
#[cfg(windows)]
let expected_cwd: PathUri = "file:///home/openai/share"
.parse()
.expect("expected cwd should be a path URI");
let backend = Arc::new(RecordingExecBackend::default());
let launcher = Arc::new(ExecutorStdioServerLauncher::new(backend.clone()));
let _ = RmcpClient::new_stdio_client(
OsString::from("echo"),
Vec::new(),
/*env*/ None,
&[],
Some(cwd.to_string()),
launcher,
)
.await;
let params = backend
.params
.lock()
.expect("recorded params lock should not be poisoned")
.take()
.expect("executor start request should be recorded");
assert_eq!(params.cwd, expected_cwd);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,140 @@
//! Verifies metadata on the actual HTTP session-expiry retry and subsequent tool calls.
use super::*;
use pretty_assertions::assert_eq;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
#[tokio::test]
async fn recovered_tool_calls_use_current_session_capabilities() -> anyhow::Result<()> {
for (initial_support, recovered_support, fail_policy) in [
(false, true, false),
(true, false, false),
(true, true, false),
(false, false, false),
(false, true, true),
] {
let server = MockServer::start().await;
let handshakes = Arc::new(AtomicUsize::new(0));
let calls = Arc::new(AtomicUsize::new(0));
let observed_handshakes = Arc::clone(&handshakes);
let observed_calls = Arc::clone(&calls);
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(move |request: &Request| {
let body: Value = request.body_json().expect("JSON-RPC request");
match body["method"].as_str() {
Some("server/discover" | "initialize") => {
let initial = observed_handshakes.fetch_add(1, Ordering::SeqCst) == 0;
let supports_policy = if initial {
initial_support
} else {
recovered_support
};
let mut capabilities = json!({"tools": {}});
if supports_policy {
capabilities["experimental"] = json!({"codex/network-policy-meta": {}});
}
let mut result = if body["method"] == "server/discover" {
modern_discover_result(&body)
} else {
json!({"jsonrpc": "2.0", "id": body["id"], "result": {
"protocolVersion": LEGACY_VERSION,
"serverInfo": {"name": "recovery-test", "version": "1.0"},
}})
};
result["result"]["capabilities"] = capabilities;
ResponseTemplate::new(200)
.insert_header(
"mcp-session-id",
if initial { "initial" } else { "recovered" },
)
.set_body_json(result)
}
Some("notifications/initialized") => ResponseTemplate::new(202),
Some("tools/call") => {
// The first call succeeds; the next expires the old session.
if observed_calls.fetch_add(1, Ordering::SeqCst) == 1 {
return ResponseTemplate::new(404);
}
ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0", "id": body["id"], "result": {
"resultType": "complete", "content": [],
},
}))
}
other => panic!("unexpected request: {other:?}"),
}
})
.mount(&server)
.await;
let client = create_client(&server, McpProtocolMode::Legacy)
.await?
.with_read_only_tools(/*requires_read_only_tools*/ true);
initialize_client(&client).await?;
for phase in ["warmup", "recovery", "later"] {
let result = client
.call_tool(
"echo".to_string(),
Some(json!({"message": phase})),
|capabilities| {
let mut meta = json!({"callId": phase, "openai/readOnly": false});
if capabilities
.experimental
.as_ref()
.is_some_and(|experimental| {
experimental.contains_key("codex/network-policy-meta")
})
{
anyhow::ensure!(!fail_policy, "policy source unavailable");
meta["codex/network-policy-meta"] = json!({"enabled": false});
}
Ok(Some(meta))
},
/*timeout*/ None,
)
.await;
if fail_policy && phase != "warmup" {
assert!(
result
.unwrap_err()
.to_string()
.contains("policy source unavailable")
);
} else {
result?;
}
}
let requests = server.received_requests().await.expect("recorded requests")
.into_iter()
.filter(|request| request.method == "POST")
.filter_map(|request| {
let body: Value = request.body_json().expect("JSON-RPC request");
(body["method"] == "tools/call").then(|| {
let meta = &body["params"]["_meta"];
json!({
"session": request.headers.get("mcp-session-id").map(|value| value.to_str().unwrap()),
"callId": meta["callId"],
"policy": meta["codex/network-policy-meta"],
"readOnly": meta["openai/readOnly"],
})
})
}).collect::<Vec<_>>();
let initial_policy = initial_support.then(|| json!({"enabled": false}));
let recovered_policy = recovered_support.then(|| json!({"enabled": false}));
let mut expected = vec![
json!({"session": "initial", "callId": "warmup", "policy": initial_policy, "readOnly": true}),
json!({"session": "initial", "callId": "recovery", "policy": initial_policy, "readOnly": true}),
];
if !fail_policy {
expected.extend([
json!({"session": "recovered", "callId": "recovery", "policy": recovered_policy, "readOnly": true}),
json!({"session": "recovered", "callId": "later", "policy": recovered_policy, "readOnly": true}),
]);
}
assert_eq!(requests, expected);
assert_eq!(handshakes.load(Ordering::SeqCst), 2);
client.shutdown().await;
}
Ok(())
}

View File

@@ -0,0 +1,293 @@
use std::collections::HashMap;
use std::ffi::OsString;
use std::sync::Arc;
use std::time::Duration;
use akode_config::types::AuthKeyringBackendKind;
use akode_config::types::OAuthCredentialsStoreMode;
use akode_exec_server::Environment;
use akode_rmcp_client::ElicitationAction;
use akode_rmcp_client::ElicitationResponse;
use akode_rmcp_client::ExecutorStdioServerLauncher;
use akode_rmcp_client::LocalStdioServerLauncher;
use akode_rmcp_client::McpProtocolMode;
use akode_rmcp_client::RmcpClient;
use akode_rmcp_client::StdioServerLauncher;
use futures::FutureExt;
use rmcp::model::ClientCapabilities;
use rmcp::model::Implementation;
use rmcp::model::InitializeRequestParams;
use rmcp::model::ProtocolVersion;
use serde_json::Value;
use serde_json::json;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::Request;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
const MAX_MCP_MESSAGE_BYTES: usize = 8 * 1024 * 1024;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum OversizedHttpResponse {
DiscoveryJson,
ToolJson,
ToolError,
ToolSseEvent,
}
fn initialize_params() -> InitializeRequestParams {
InitializeRequestParams::new(
ClientCapabilities::default(),
Implementation::new("codex-message-limit-test", "0.0.0-test"),
)
.with_protocol_version(ProtocolVersion::V_2025_06_18)
}
async fn initialize(client: &RmcpClient) -> anyhow::Result<()> {
client
.initialize(
initialize_params(),
Some(Duration::from_secs(15)),
Box::new(|_, _| {
async {
Ok(ElicitationResponse {
action: ElicitationAction::Accept,
content: Some(json!({})),
meta: None,
})
}
.boxed()
}),
)
.await?;
Ok(())
}
fn discovery_response(request: &Value, padding: Option<&str>) -> Value {
json!({
"jsonrpc": "2.0",
"id": request["id"],
"result": {
"resultType": "complete",
"supportedVersions": ["2026-07-28"],
"capabilities": {"tools": {}},
"instructions": padding.unwrap_or_default(),
"_meta": {
"io.modelcontextprotocol/serverInfo": {
"name": "message-limit-test",
"version": "1.0.0",
},
},
"ttlMs": 0,
"cacheScope": "private",
},
})
}
fn tools_response(request: &Value, padding: &str) -> Value {
json!({
"jsonrpc": "2.0",
"id": request["id"],
"result": {
"resultType": "complete",
"tools": [{
"name": "oversized_tool",
"description": padding,
"inputSchema": {"type": "object"},
}],
},
})
}
async fn http_client(server: &MockServer, mode: McpProtocolMode) -> anyhow::Result<RmcpClient> {
RmcpClient::new_streamable_http_client_with_protocol_mode(
"message-limits",
&format!("{}/mcp", server.uri()),
/*bearer_token*/ None,
/*http_headers*/ None,
/*env_http_headers*/ None,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
Environment::default_for_tests().get_http_client(),
/*auth_provider*/ None,
mode,
)
.await
}
#[tokio::test]
async fn modern_http_rejects_oversized_json_error_and_sse_bodies() -> anyhow::Result<()> {
for oversized in [
OversizedHttpResponse::DiscoveryJson,
OversizedHttpResponse::ToolJson,
OversizedHttpResponse::ToolError,
OversizedHttpResponse::ToolSseEvent,
] {
let server = MockServer::start().await;
let padding = Arc::new("x".repeat(MAX_MCP_MESSAGE_BYTES + 1));
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(move |request: &Request| {
let body: Value = request.body_json().expect("JSON-RPC request");
match body["method"].as_str() {
Some("server/discover") => {
ResponseTemplate::new(200).set_body_json(discovery_response(
&body,
(oversized == OversizedHttpResponse::DiscoveryJson)
.then_some(padding.as_str()),
))
}
Some("tools/list") if oversized == OversizedHttpResponse::ToolError => {
ResponseTemplate::new(500).set_body_json(json!({
"jsonrpc": "2.0",
"id": body["id"],
"error": {"code": -32603, "message": padding.as_str()},
}))
}
Some("tools/list") if oversized == OversizedHttpResponse::ToolSseEvent => {
ResponseTemplate::new(200).set_body_raw(
format!(
"event: message\ndata: {}\n\n",
tools_response(&body, &padding),
),
"text/event-stream; charset=utf-8",
)
}
Some("tools/list") => {
ResponseTemplate::new(200).set_body_json(tools_response(&body, &padding))
}
other => panic!("unexpected MCP method {other:?}"),
}
})
.mount(&server)
.await;
let client = http_client(&server, McpProtocolMode::V20260728).await?;
if oversized == OversizedHttpResponse::DiscoveryJson {
let error = initialize(&client)
.await
.expect_err("oversized discovery must be rejected");
assert!(format!("{error:#}").contains("8388608 bytes"));
} else {
initialize(&client).await?;
let error = client
.list_tools(/*params*/ None, Some(Duration::from_secs(5)))
.await
.expect_err("oversized tools response must be rejected");
let error = format!("{error:#}");
assert!(
error.contains("8388608 bytes")
|| (oversized == OversizedHttpResponse::ToolSseEvent
&& (error.contains("timed out") || error.contains("Transport closed"))),
"unexpected {oversized:?} error: {error}"
);
}
client.shutdown().await;
}
Ok(())
}
#[tokio::test]
async fn legacy_http_keeps_existing_large_json_response_behavior() -> anyhow::Result<()> {
let server = MockServer::start().await;
let padding = Arc::new("x".repeat(MAX_MCP_MESSAGE_BYTES + 1));
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(move |request: &Request| {
let body: Value = request.body_json().expect("JSON-RPC request");
match body["method"].as_str() {
Some("initialize") => ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
"id": body["id"],
"result": {
"protocolVersion": "2025-06-18",
"capabilities": {"tools": {}},
"serverInfo": {"name": "legacy-large-response", "version": "1.0.0"},
},
})),
Some("notifications/initialized") => ResponseTemplate::new(202),
Some("tools/list") => {
ResponseTemplate::new(200).set_body_json(tools_response(&body, &padding))
}
other => panic!("unexpected legacy MCP method {other:?}"),
}
})
.mount(&server)
.await;
let client = http_client(&server, McpProtocolMode::Legacy).await?;
initialize(&client).await?;
let tools = client
.list_tools(/*params*/ None, Some(Duration::from_secs(15)))
.await?;
assert_eq!(
tools.tools[0].description.as_deref().map(str::len),
Some(MAX_MCP_MESSAGE_BYTES + 1)
);
client.shutdown().await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn modern_local_and_executor_stdio_reject_oversized_lines() -> anyhow::Result<()> {
let server = akode_utils_cargo_bin::cargo_bin("test_mcp_2026_stdio_server")?;
for (mode, modern, executor) in [
(McpProtocolMode::Legacy, false, false),
(McpProtocolMode::Legacy, false, true),
(McpProtocolMode::V20260728, true, false),
(McpProtocolMode::V20260728, true, true),
(McpProtocolMode::DiscoverLocalStdio, false, false),
] {
let env = (mode == McpProtocolMode::V20260728).then(|| {
HashMap::from([(
OsString::from("AKODE_MCP_PROTOCOL_VERSION"),
OsString::from("2026-07-28"),
)])
});
let launcher: Arc<dyn StdioServerLauncher> = if executor {
Arc::new(ExecutorStdioServerLauncher::new(
Environment::default_for_tests().get_exec_backend(),
))
} else {
Arc::new(LocalStdioServerLauncher::new(std::env::current_dir()?))
};
let fixture_mode = if modern {
"oversized-stdout"
} else {
"oversized-stdout-legacy"
};
let client = RmcpClient::new_stdio_client_with_protocol_mode(
server.clone().into(),
vec![OsString::from(fixture_mode)],
env,
&[],
Some(std::env::current_dir()?.to_string_lossy().into_owned()),
launcher,
mode,
)
.await?;
initialize(&client).await?;
let result = client
.list_tools(/*params*/ None, Some(Duration::from_secs(10)))
.await;
if !modern && !executor {
let tools = result?;
assert_eq!(
tools.tools[0].description.as_deref().map(str::len),
Some(MAX_MCP_MESSAGE_BYTES + 1),
"legacy local stdio must preserve the existing unbounded native codec"
);
} else {
assert!(
result.is_err(),
"oversized stdio line must be rejected (modern={modern}, executor={executor})"
);
}
client.shutdown().await;
}
Ok(())
}

View File

@@ -0,0 +1,786 @@
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use akode_config::types::AuthKeyringBackendKind;
use akode_config::types::OAuthCredentialsStoreMode;
use akode_exec_server::Environment;
use akode_rmcp_client::Elicitation;
use akode_rmcp_client::ElicitationAction;
use akode_rmcp_client::ElicitationResponse;
use akode_rmcp_client::McpProtocolMode;
use akode_rmcp_client::RmcpClient;
use akode_rmcp_client::SendElicitation;
use futures::FutureExt;
use pretty_assertions::assert_eq;
use rmcp::model::ClientCapabilities;
use rmcp::model::ElicitRequestParams;
use rmcp::model::ElicitationCapability;
use rmcp::model::FormElicitationCapability;
use rmcp::model::Implementation;
use rmcp::model::InitializeRequestParams;
use rmcp::model::ProtocolVersion;
use rmcp::model::ReadResourceRequestParams;
use rmcp::model::ServerResult;
use rmcp::model::UrlElicitationCapability;
use serde_json::Value;
use serde_json::json;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::Request;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
const MODERN_VERSION: &str = "2026-07-28";
const OPAQUE_STATE: &str = " opaque/\u{2603}/=?base64?literal?=\n";
#[path = "mcp_2026_mrtr/native_verification_tests.rs"]
mod native_verification;
fn discover_response(body: &Value) -> ResponseTemplate {
ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
"id": body["id"],
"result": {
"resultType": "complete",
"supportedVersions": [MODERN_VERSION],
"capabilities": {"tools": {}, "resources": {}},
"_meta": {
"io.modelcontextprotocol/serverInfo": {
"name": "mrtr-test",
"version": "1.0.0",
},
},
"ttlMs": 0,
"cacheScope": "private",
},
}))
}
fn result_response(body: &Value, result: Value) -> ResponseTemplate {
ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
"id": body["id"],
"result": result,
}))
}
fn sse_result_response(body: &Value, result: Value) -> ResponseTemplate {
let message = json!({
"jsonrpc": "2.0",
"id": body["id"],
"result": result,
});
ResponseTemplate::new(200).set_body_raw(
format!("event: message\ndata: {message}\n\n"),
"text/event-stream; charset=utf-8",
)
}
fn elicitation_request(mode: &str) -> Value {
let params = match mode {
"form" => json!({
"mode": "form",
"message": "Confirm the MCP request.",
"requestedSchema": {
"type": "object",
"properties": {"confirmed": {"type": "boolean"}},
"required": ["confirmed"],
},
"_meta": {"inputContext": "server-context"},
}),
"url" => json!({
"mode": "url",
"message": "Approve the MCP request.",
"url": "https://example.test/approve",
"elicitationId": "approval-123",
"_meta": {"inputContext": "server-context"},
}),
other => panic!("unexpected elicitation mode: {other}"),
};
json!({"method": "elicitation/create", "params": params})
}
async fn create_client(
server: &MockServer,
elicitation_modes: Arc<Mutex<Vec<String>>>,
) -> anyhow::Result<RmcpClient> {
let client = RmcpClient::new_streamable_http_client_with_protocol_mode(
"mrtr-test",
&format!("{}/mcp", server.uri()),
/*bearer_token*/ None,
/*http_headers*/ None,
/*env_http_headers*/ None,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
Environment::default_for_tests().get_http_client(),
/*auth_provider*/ None,
McpProtocolMode::V20260728,
)
.await?;
let mut capabilities = ClientCapabilities::default();
capabilities.elicitation = Some(
ElicitationCapability::new()
.with_form(FormElicitationCapability::new())
.with_url(UrlElicitationCapability::new()),
);
client
.initialize(
InitializeRequestParams::new(
capabilities,
Implementation::new("codex-mrtr-test", "0.0.0"),
)
.with_protocol_version(ProtocolVersion::V_2025_06_18),
Some(Duration::from_secs(5)),
Box::new(move |_, request| {
let elicitation_modes = Arc::clone(&elicitation_modes);
async move {
let Elicitation::Mcp(request) = request else {
anyhow::bail!("MRTR input must be a standard MCP elicitation");
};
let mode = match request {
ElicitRequestParams::FormElicitationParams { meta, .. } => {
assert_eq!(
meta.and_then(|meta| meta.get("inputContext").cloned()),
Some(json!("server-context"))
);
"form"
}
ElicitRequestParams::UrlElicitationParams { meta, .. } => {
assert_eq!(
meta.and_then(|meta| meta.get("inputContext").cloned()),
Some(json!("server-context"))
);
"url"
}
_ => anyhow::bail!("unsupported elicitation mode"),
};
elicitation_modes
.lock()
.map_err(|_| anyhow::anyhow!("elicitation lock was poisoned"))?
.push(mode.to_owned());
Ok(ElicitationResponse {
action: ElicitationAction::Accept,
content: Some(json!({"confirmed": true})),
meta: Some(json!({"clientContext": "preserved"})),
})
}
.boxed()
}),
)
.await?;
Ok(client)
}
#[tokio::test]
async fn modern_sse_input_required_preserves_response_metadata() -> anyhow::Result<()> {
let server = MockServer::start().await;
let expected_result = json!({
"resultType": "input_required",
"requestState": OPAQUE_STATE,
"_meta": {"responseContext": "preserved"},
});
let result = expected_result.clone();
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(move |request: &Request| {
let body: Value = request.body_json().expect("valid JSON-RPC request");
match body["method"].as_str() {
Some("server/discover") => discover_response(&body),
Some("tools/call") => sse_result_response(&body, result.clone()),
other => panic!("unexpected MRTR request: {other:?}"),
}
})
.expect(2)
.mount(&server)
.await;
let client = create_client(&server, Arc::new(Mutex::new(Vec::new()))).await?;
let result = client
.send_custom_request_with_timeout(
"tools/call",
Some(json!({"name": "confirm", "arguments": {}})),
Some(Duration::from_secs(5)),
)
.await?;
let ServerResult::InputRequiredResult(result) = result else {
anyhow::bail!("SSE response must remain an input_required result");
};
assert_eq!(serde_json::to_value(result)?, expected_result);
client.shutdown().await;
server.verify().await;
Ok(())
}
#[tokio::test]
async fn modern_tool_mrtr_routes_concurrent_inputs_to_their_callers_and_preserves_metadata()
-> anyhow::Result<()> {
for mode in ["form", "url"] {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(move |request: &Request| {
let body: Value = request.body_json().expect("valid JSON-RPC request");
match body["method"].as_str() {
Some("server/discover") => discover_response(&body),
Some("tools/call") => {
let caller = body["params"]["_meta"]["requestContext"].clone();
assert_eq!(
body.pointer("/params/_meta/io.modelcontextprotocol~1protocolVersion"),
Some(&json!(MODERN_VERSION))
);
if body.pointer("/params/inputResponses").is_none() {
result_response(
&body,
json!({
"resultType": "input_required",
"inputRequests": {
"confirmation": elicitation_request(mode),
},
"requestState": OPAQUE_STATE,
"_meta": {
"io.modelcontextprotocol/serverInfo": {
"name": "mrtr-test",
"version": "1.0.0",
},
"responseContext": "preserved",
},
}),
)
} else {
assert_eq!(
body.pointer("/params/requestState"),
Some(&json!(OPAQUE_STATE))
);
assert_eq!(
body.pointer("/params/inputResponses/confirmation"),
Some(&json!({
"action": "accept",
"content": {"confirmed": true, "caller": caller},
"_meta": {"clientContext": "preserved"},
}))
);
result_response(
&body,
json!({
"resultType": "complete",
"content": [{"type": "text", "text": "MRTR completed"}],
}),
)
}
}
other => panic!("unexpected MRTR request: {other:?}"),
}
})
.expect(8)
.mount(&server)
.await;
let client = create_client(&server, Arc::default()).await?;
let other_client = create_client(&server, Arc::default()).await?;
let inputs = Arc::new(Mutex::new(Vec::new()));
let callers = [
(&client, "first"),
(&client, "second"),
(&other_client, "other connection"),
];
let results = futures::future::try_join_all(callers.map(|(client, caller)| {
let inputs = Arc::clone(&inputs);
let sender: SendElicitation = Box::new(move |id, request| {
inputs.lock().unwrap().push((caller, id));
let Elicitation::Mcp(request) = request else {
panic!("expected standard MCP input");
};
let meta = match request {
ElicitRequestParams::FormElicitationParams { meta, .. }
| ElicitRequestParams::UrlElicitationParams { meta, .. } => meta,
_ => panic!("expected form or URL input"),
};
assert_eq!(
meta.and_then(|meta| meta.get("inputContext").cloned()),
Some(json!("server-context"))
);
futures::future::ready(Ok(ElicitationResponse {
action: ElicitationAction::Accept,
content: Some(json!({"confirmed": true, "caller": caller})),
meta: Some(json!({"clientContext": "preserved"})),
}))
.boxed()
});
client.call_tool_with_elicitation(
"confirm".into(),
Some(json!({"mode": mode})),
move |_| Ok(Some(json!({"requestContext": caller}))),
Some(Duration::from_secs(5)),
Arc::new(sender),
)
}))
.await?;
for result in results {
assert_eq!(
result.content[0].as_text().map(|text| text.text.as_str()),
Some("MRTR completed")
);
}
{
let inputs = inputs.lock().unwrap();
assert_eq!(inputs.len(), 3);
let ids = inputs.iter().map(|(_, id)| id).collect::<HashSet<_>>();
assert_eq!(ids.len(), inputs.len());
}
client.shutdown().await;
other_client.shutdown().await;
}
Ok(())
}
#[tokio::test]
async fn modern_tool_mrtr_uses_recovered_protocol_after_legacy_session_expiry() -> anyhow::Result<()>
{
let server = MockServer::start().await;
let calls = Arc::new(Mutex::new(Vec::<Value>::new()));
let sessions = Arc::new(Mutex::new(Vec::<String>::new()));
let recorded_calls = Arc::clone(&calls);
let recorded_sessions = Arc::clone(&sessions);
Mock::given(method("GET"))
.and(path("/mcp"))
.respond_with(ResponseTemplate::new(405))
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(move |request: &Request| {
let body: Value = request.body_json().expect("valid JSON-RPC request");
match body["method"].as_str() {
Some("server/discover") => {
let mut sessions = recorded_sessions.lock().expect("sessions lock");
if sessions.is_empty() {
ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
"id": body["id"],
"error": {"code": -32601, "message": "method not found"},
}))
} else {
sessions.push("modern-session".to_owned());
discover_response(&body).insert_header("mcp-session-id", "modern-session")
}
}
Some("initialize") => {
assert_eq!(
body.pointer("/params/protocolVersion"),
Some(&json!(ProtocolVersion::V_2025_06_18.as_str()))
);
recorded_sessions
.lock()
.expect("sessions lock")
.push("legacy-session".to_owned());
ResponseTemplate::new(200)
.set_body_json(json!({
"jsonrpc": "2.0",
"id": body["id"],
"result": {
"protocolVersion": ProtocolVersion::V_2025_06_18.as_str(),
"capabilities": {"tools": {}},
"serverInfo": {"name": "mrtr-test", "version": "1.0.0"},
},
}))
.insert_header("mcp-session-id", "legacy-session")
}
Some("notifications/initialized") => ResponseTemplate::new(202),
Some("tools/call") => {
assert_eq!(
body.pointer("/params/_meta/requestContext"),
Some(&json!("caller-context"))
);
assert_eq!(
body.pointer("/params/_meta/openai~1readOnly"),
Some(&json!(true))
);
let attempt = {
let mut calls = recorded_calls.lock().expect("requests lock");
calls.push(body.clone());
calls.len()
};
match attempt {
1 => {
assert_eq!(
body.pointer(
"/params/_meta/io.modelcontextprotocol~1protocolVersion"
),
None
);
ResponseTemplate::new(404)
}
2 => {
assert_eq!(
body.pointer(
"/params/_meta/io.modelcontextprotocol~1protocolVersion"
),
Some(&json!(MODERN_VERSION))
);
result_response(
&body,
json!({
"resultType": "input_required",
"inputRequests": {
"confirmation": elicitation_request("form"),
},
"requestState": OPAQUE_STATE,
}),
)
}
3 => {
assert_eq!(
body.pointer(
"/params/_meta/io.modelcontextprotocol~1protocolVersion"
),
Some(&json!(MODERN_VERSION))
);
assert_eq!(
body.pointer("/params/requestState"),
Some(&json!(OPAQUE_STATE))
);
assert_eq!(
body.pointer("/params/inputResponses/confirmation"),
Some(&json!({
"action": "accept",
"content": {"confirmed": true},
"_meta": {"clientContext": "preserved"},
}))
);
result_response(
&body,
json!({
"resultType": "complete",
"content": [{"type": "text", "text": "recovered MRTR completed"}],
}),
)
}
other => panic!("unexpected recovered MRTR attempt: {other}"),
}
}
other => panic!("unexpected recovered MRTR request: {other:?}"),
}
})
.mount(&server)
.await;
let elicitation_modes = Arc::new(Mutex::new(Vec::new()));
let client = create_client(&server, Arc::clone(&elicitation_modes))
.await?
.with_read_only_tools(/*requires_read_only_tools*/ true);
let result = client
.call_tool(
"confirm".into(),
Some(json!({})),
|_| {
Ok(Some(
json!({"requestContext": "caller-context", "openai/readOnly": false}),
))
},
Some(Duration::from_secs(5)),
)
.await?;
assert_eq!(
result.content[0].as_text().map(|text| text.text.as_str()),
Some("recovered MRTR completed")
);
assert_eq!(
*sessions.lock().expect("sessions lock"),
vec!["legacy-session", "modern-session"]
);
assert_eq!(calls.lock().expect("requests lock").len(), 3);
assert_eq!(
*elicitation_modes.lock().expect("elicitation lock"),
vec!["form"]
);
client.shutdown().await;
Ok(())
}
#[tokio::test]
async fn modern_resource_mrtr_retries_with_opaque_request_state() -> anyhow::Result<()> {
let server = MockServer::start().await;
let calls = Arc::new(Mutex::new(Vec::<Value>::new()));
let recorded = Arc::clone(&calls);
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(move |request: &Request| {
let body: Value = request.body_json().expect("valid JSON-RPC request");
match body["method"].as_str() {
Some("server/discover") => discover_response(&body),
Some("resources/read") => {
recorded.lock().expect("requests lock").push(body.clone());
if body.pointer("/params/inputResponses").is_none() {
result_response(
&body,
json!({
"resultType": "input_required",
"inputRequests": {
"confirmation": elicitation_request("form"),
},
"requestState": OPAQUE_STATE,
"_meta": {
"io.modelcontextprotocol/serverInfo": {
"name": "mrtr-test",
"version": "1.0.0",
},
"responseContext": "preserved",
},
}),
)
} else {
assert_eq!(
body.pointer("/params/requestState"),
Some(&json!(OPAQUE_STATE))
);
assert_eq!(
body.pointer("/params/inputResponses/confirmation/_meta/clientContext"),
Some(&json!("preserved"))
);
result_response(
&body,
json!({
"resultType": "complete",
"contents": [{
"uri": "memo://requires-confirmation",
"mimeType": "text/plain",
"text": "approved resource",
}],
}),
)
}
}
other => panic!("unexpected resource MRTR request: {other:?}"),
}
})
.expect(3)
.mount(&server)
.await;
let elicitation_modes = Arc::new(Mutex::new(Vec::new()));
let client = create_client(&server, Arc::default()).await?;
let observed_modes = Arc::clone(&elicitation_modes);
let sender: SendElicitation = Box::new(move |_, request| {
assert!(matches!(
request,
Elicitation::Mcp(ElicitRequestParams::FormElicitationParams { .. })
));
observed_modes.lock().unwrap().push("form");
futures::future::ready(Ok(ElicitationResponse {
action: ElicitationAction::Accept,
content: Some(json!({"confirmed": true})),
meta: Some(json!({"clientContext": "preserved"})),
}))
.boxed()
});
let result = client
.read_resource_with_elicitation(
ReadResourceRequestParams::new("memo://requires-confirmation"),
Some(Duration::from_secs(5)),
Arc::new(sender),
)
.await?;
assert_eq!(result.contents.len(), 1);
assert_eq!(
*elicitation_modes.lock().expect("elicitation lock"),
vec!["form"]
);
{
let calls = calls.lock().expect("requests lock");
assert_eq!(calls.len(), 2);
assert_ne!(calls[0]["id"], calls[1]["id"]);
}
client.shutdown().await;
Ok(())
}
#[tokio::test]
async fn modern_tool_mrtr_accepts_sse_discovery_and_metadata_bearing_rounds() -> anyhow::Result<()>
{
let server = MockServer::start().await;
let calls = Arc::new(Mutex::new(Vec::<Value>::new()));
let recorded = Arc::clone(&calls);
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(move |request: &Request| {
let body: Value = request.body_json().expect("valid JSON-RPC request");
match body["method"].as_str() {
Some("server/discover") => sse_result_response(
&body,
json!({
"resultType": "complete",
"supportedVersions": [MODERN_VERSION],
"capabilities": {"tools": {}},
"_meta": {
"io.modelcontextprotocol/serverInfo": {
"name": "sse-mrtr-test",
"version": "1.0.0",
},
},
"ttlMs": 0,
"cacheScope": "private",
}),
),
Some("tools/call") => {
recorded.lock().expect("requests lock").push(body.clone());
if body.pointer("/params/inputResponses").is_none() {
sse_result_response(
&body,
json!({
"resultType": "input_required",
"inputRequests": {
"confirmation": elicitation_request("form"),
},
"requestState": OPAQUE_STATE,
"_meta": {"responseContext": "sse-round"},
}),
)
} else {
assert_eq!(
body.pointer("/params/requestState"),
Some(&json!(OPAQUE_STATE))
);
assert_eq!(
body.pointer("/params/inputResponses/confirmation/action"),
Some(&json!("accept"))
);
sse_result_response(
&body,
json!({
"resultType": "complete",
"content": [{"type": "text", "text": "SSE MRTR completed"}],
}),
)
}
}
other => panic!("unexpected SSE MRTR request: {other:?}"),
}
})
.expect(3)
.mount(&server)
.await;
let elicitation_modes = Arc::new(Mutex::new(Vec::new()));
let client = create_client(&server, Arc::clone(&elicitation_modes)).await?;
let result = client
.call_tool(
"confirm".to_owned(),
Some(json!({})),
|_| Ok(None),
Some(Duration::from_secs(5)),
)
.await?;
assert_eq!(
result.content[0].as_text().map(|text| text.text.as_str()),
Some("SSE MRTR completed")
);
assert_eq!(
*elicitation_modes.lock().expect("elicitation lock"),
vec!["form"]
);
assert_eq!(calls.lock().expect("requests lock").len(), 2);
client.shutdown().await;
Ok(())
}
#[tokio::test]
async fn modern_tool_mrtr_preserves_state_only_rounds_without_elicitation() -> anyhow::Result<()> {
let server = MockServer::start().await;
let states = Arc::new(Mutex::new(Vec::<Option<String>>::new()));
let recorded = Arc::clone(&states);
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(move |request: &Request| {
let body: Value = request.body_json().expect("valid JSON-RPC request");
match body["method"].as_str() {
Some("server/discover") => discover_response(&body),
Some("tools/call") => {
let state = body
.pointer("/params/requestState")
.and_then(Value::as_str)
.map(str::to_owned);
recorded.lock().expect("states lock").push(state.clone());
match state.as_deref() {
None => result_response(
&body,
json!({
"resultType": "input_required",
"requestState": "state-1",
"_meta": {"responseContext": "first-round"},
}),
),
Some("state-1") => result_response(
&body,
json!({
"resultType": "input_required",
"requestState": "state-2",
"_meta": {"responseContext": "second-round"},
}),
),
Some("state-2") => result_response(
&body,
json!({
"resultType": "complete",
"content": [{"type": "text", "text": "state completed"}],
}),
),
Some(other) => panic!("unexpected opaque state: {other}"),
}
}
other => panic!("unexpected state-only MRTR request: {other:?}"),
}
})
.expect(4)
.mount(&server)
.await;
let elicitation_modes = Arc::new(Mutex::new(Vec::new()));
let client = create_client(&server, Arc::clone(&elicitation_modes)).await?;
let result = client
.call_tool(
"state-only".into(),
Some(json!({})),
|_| Ok(None),
Some(Duration::from_secs(5)),
)
.await?;
assert_eq!(
result.content[0].as_text().map(|text| text.text.as_str()),
Some("state completed")
);
assert!(
elicitation_modes
.lock()
.expect("elicitation lock")
.is_empty()
);
assert_eq!(
*states.lock().expect("states lock"),
vec![
None,
Some("state-1".to_string()),
Some("state-2".to_string())
]
);
client.shutdown().await;
Ok(())
}

View File

@@ -0,0 +1,622 @@
//! Exercises native verification through the HTTP MRTR tool-input envelope.
use super::*;
use akode_protocol::mcp::OPENAI_ELICITATION_EXTENSION_ID;
use akode_rmcp_client::SendElicitation;
use pretty_assertions::assert_eq;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::time::timeout;
fn native_request() -> Value {
json!({
"method": "openai/elicitation/create",
"params": {
"mode": "openai/userVerification", "title": "Verify action",
"description": "Verify the requested operation", "challenge": "AQID",
"_meta": {"example/display": {"label": "Operation"}}
}
})
}
fn rich_form_request() -> Value {
let mut request = elicitation_request("form");
request["method"] = json!("openai/elicitation/create");
request
}
fn input_required(request: Value) -> Value {
json!({
"resultType": "input_required", "content": [], "isError": false,
"inputRequests": {"verification": request}, "requestState": OPAQUE_STATE
})
}
fn capabilities() -> ClientCapabilities {
let mut capabilities = ClientCapabilities::default();
capabilities.extensions = Some(
[(
OPENAI_ELICITATION_EXTENSION_ID.into(),
serde_json::Map::from_iter([("userVerification".into(), json!({}))]),
)]
.into_iter()
.collect(),
);
capabilities
}
async fn client(
server: &MockServer,
capabilities: ClientCapabilities,
handler: SendElicitation,
) -> anyhow::Result<Arc<RmcpClient>> {
let client = RmcpClient::new_streamable_http_client_with_protocol_mode(
"native-mrtr-test",
&format!("{}/mcp", server.uri()),
/*bearer_token*/ None,
/*http_headers*/ None,
/*env_http_headers*/ None,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
Environment::default_for_tests().get_http_client(),
/*auth_provider*/ None,
McpProtocolMode::V20260728,
)
.await?;
client
.initialize(
InitializeRequestParams::new(capabilities, Implementation::new("test", "0.0.0")),
Some(Duration::from_secs(/*secs*/ 5)),
handler,
)
.await?;
Ok(Arc::new(client))
}
async fn call(client: &RmcpClient) -> anyhow::Result<Value> {
Ok(serde_json::to_value(
client
.call_tool(
"verified_operation".into(),
Some(json!({"resource": "example"})),
|_| Ok(Some(json!({"caller": "preserved"}))),
Some(Duration::from_secs(/*secs*/ 5)),
)
.await?,
)?)
}
fn response(action: ElicitationAction, content: Value) -> ElicitationResponse {
ElicitationResponse {
action,
content: Some(content),
meta: Some(json!({"discard": true})),
}
}
#[tokio::test]
async fn native_mrtr_returns_validated_proof_or_cancellation_in_content() -> anyhow::Result<()> {
let proof = json!({"credentialId": "test-credential", "signature": "BAUG"});
for (action, content, expected) in [
(
ElicitationAction::Accept,
proof.clone(),
json!({"action": "accept", "content": proof}),
),
(
ElicitationAction::Cancel,
proof.clone(),
json!({"action": "cancel"}),
),
(
ElicitationAction::Decline,
proof,
json!({"action": "decline"}),
),
(
ElicitationAction::Accept,
json!({"signature": "invalid"}),
json!({
"action": "cancel",
"_meta": {"openai/userVerificationReason": "invalidProof"},
}),
),
] {
let server = MockServer::start().await;
let final_result =
json!({"resultType": "complete", "content": [{"type": "text", "text": "done"}]});
let final_response = final_result.clone();
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(move |request: &Request| {
let body: Value = request.body_json().unwrap();
match body["method"].as_str() {
Some("server/discover") => discover_response(&body),
Some("tools/call") if body.pointer("/params/inputResponses").is_none() => {
let mut result = input_required(native_request());
result["inputRequests"]["confirmation"] = elicitation_request("form");
result["inputRequests"]["richConfirmation"] = rich_form_request();
sse_result_response(&body, result)
}
Some("tools/call") => {
assert_eq!(
body["params"]["inputResponses"],
json!({
"verification": expected,
"confirmation": {"action": "accept", "content": {"confirmed": true}},
"richConfirmation": {"action": "accept", "content": {"confirmed": true}}
})
);
assert_eq!(body["params"]["requestState"], OPAQUE_STATE);
assert_eq!(body["params"]["name"], "verified_operation");
assert_eq!(body["params"]["arguments"], json!({"resource": "example"}));
assert_eq!(body["params"]["_meta"]["caller"], "preserved");
result_response(&body, final_response.clone())
}
other => panic!("unexpected request: {other:?}"),
}
})
.expect(/*r*/ 3)
.mount(&server)
.await;
let mut capabilities = capabilities();
capabilities
.extensions
.as_mut()
.unwrap()
.get_mut(OPENAI_ELICITATION_EXTENSION_ID)
.unwrap()
.insert("form".into(), json!({}));
capabilities.elicitation =
Some(ElicitationCapability::new().with_form(FormElicitationCapability::new()));
let client = client(
&server,
capabilities,
Box::new(move |_, request| {
if let Elicitation::OpenAiElicitationForm { meta, message, requested_schema } = request {
let expected = rich_form_request();
assert_eq!(
json!({"_meta": meta, "message": message, "requestedSchema": requested_schema}),
json!({
"_meta": expected["params"]["_meta"],
"message": expected["params"]["message"],
"requestedSchema": expected["params"]["requestedSchema"]
})
);
return Box::pin(async {
Ok(ElicitationResponse {
action: ElicitationAction::Accept,
content: Some(json!({"confirmed": true})),
meta: None,
})
});
}
if let Elicitation::Mcp(ElicitRequestParams::FormElicitationParams {
meta, ..
}) = request
{
assert_eq!(
meta.and_then(|meta| meta.get("inputContext").cloned()),
Some(json!("server-context"))
);
return Box::pin(async {
Ok(ElicitationResponse {
action: ElicitationAction::Accept,
content: Some(json!({"confirmed": true})),
meta: None,
})
});
}
assert_eq!(
request,
Elicitation::UserVerification {
meta: Some(json!({"example/display": {"label": "Operation"}})),
title: "Verify action".into(),
description: "Verify the requested operation".into(),
challenge: "AQID".into(),
}
);
let response = response(action.clone(), content.clone());
Box::pin(async move { Ok(response) })
}),
)
.await?;
assert_eq!(call(&client).await?, final_result);
let calls: Vec<_> = server
.received_requests()
.await
.unwrap()
.into_iter()
.map(|request| request.body_json::<Value>().unwrap())
.filter(|body| body["method"] == "tools/call")
.collect();
assert_ne!(calls[0]["id"], calls[1]["id"]);
client.shutdown().await;
}
Ok(())
}
#[tokio::test]
async fn native_mrtr_bounds_repeated_input_requests() -> anyhow::Result<()> {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(|request: &Request| {
let body: Value = request.body_json().unwrap();
match body["method"].as_str() {
Some("server/discover") => discover_response(&body),
Some("tools/call") => result_response(&body, input_required(native_request())),
other => panic!("unexpected request: {other:?}"),
}
})
.expect(1 + rmcp::model::DEFAULT_MRTR_MAX_ROUNDS as u64)
.mount(&server)
.await;
let client = client(
&server,
capabilities(),
Box::new(|_, _| {
Box::pin(async {
Ok(response(
ElicitationAction::Accept,
json!({"credentialId": "test", "signature": "BAUG"}),
))
})
}),
)
.await?;
let error = call(&client).await.unwrap_err();
assert!(error.to_string().contains("MRTR"), "{error}");
client.shutdown().await;
Ok(())
}
#[tokio::test]
async fn native_mrtr_rejects_unadvertised_and_malformed_requests_without_prompting()
-> anyhow::Result<()> {
let mut malformed = native_request();
malformed["params"]["challenge"] = json!("not base64!");
for (capabilities, request) in [
(ClientCapabilities::default(), native_request()),
(capabilities(), rich_form_request()),
(capabilities(), malformed),
(
capabilities(),
json!({"method": "arbitrary/custom", "params": {}}),
),
] {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(move |http: &Request| {
let body: Value = http.body_json().unwrap();
match body["method"].as_str() {
Some("server/discover") => discover_response(&body),
Some("tools/call") => result_response(&body, input_required(request.clone())),
other => panic!("unexpected request: {other:?}"),
}
})
.expect(/*r*/ 2)
.mount(&server)
.await;
let client = client(
&server,
capabilities,
Box::new(|_, _| panic!("must not prompt")),
)
.await?;
assert!(call(&client).await.is_err());
client.shutdown().await;
}
Ok(())
}
#[tokio::test]
async fn mrtr_rejects_unsupported_elicitation_modes_without_prompting() -> anyhow::Result<()> {
for mode in [None, Some(json!(null)), Some(json!(0)), Some(json!("url"))] {
let server = MockServer::start().await;
let mut input = native_request();
if let Some(mode) = mode {
input["params"]["mode"] = mode;
} else {
input["params"].as_object_mut().unwrap().remove("mode");
}
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(move |request: &Request| {
let body: Value = request.body_json().unwrap();
match body["method"].as_str() {
Some("server/discover") => discover_response(&body),
Some("tools/call") => result_response(&body, input_required(input.clone())),
other => panic!("unexpected request: {other:?}"),
}
})
.expect(/*r*/ 2)
.mount(&server)
.await;
let client = client(
&server,
capabilities(),
Box::new(|_, _| panic!("must not prompt")),
)
.await?;
let error = call(&client).await.unwrap_err();
assert_eq!(
akode_rmcp_client::mcp_error(&error),
Some(&rmcp::ErrorData::invalid_request(
"unsupported OpenAI elicitation mode",
/*data*/ None
))
);
client.shutdown().await;
}
Ok(())
}
#[tokio::test]
async fn mrtr_preserves_auth_challenges_after_input_responses() -> anyhow::Result<()> {
for (request, action, content) in [
(
elicitation_request("form"),
ElicitationAction::Accept,
json!({"confirmed": true}),
),
(
rich_form_request(),
ElicitationAction::Accept,
json!({"confirmed": true}),
),
(
native_request(),
ElicitationAction::Accept,
json!({"credentialId": "test", "signature": "BAUG"}),
),
(native_request(), ElicitationAction::Cancel, Value::Null),
(native_request(), ElicitationAction::Decline, Value::Null),
] {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(move |http: &Request| {
let body: Value = http.body_json().unwrap();
match body["method"].as_str() {
Some("server/discover") => discover_response(&body),
Some("tools/call") if body.pointer("/params/inputResponses").is_none() => {
result_response(&body, input_required(request.clone()))
}
Some("tools/call") => ResponseTemplate::new(/*s*/ 401)
.insert_header("www-authenticate", "Bearer error=\"invalid_token\""),
other => panic!("unexpected request: {other:?}"),
}
})
.expect(/*r*/ 3)
.mount(&server)
.await;
let mut capabilities = capabilities();
capabilities
.extensions
.as_mut()
.unwrap()
.get_mut(OPENAI_ELICITATION_EXTENSION_ID)
.unwrap()
.insert("form".into(), json!({}));
capabilities.elicitation =
Some(ElicitationCapability::new().with_form(FormElicitationCapability::new()));
let client = client(
&server,
capabilities,
Box::new(move |_, _| {
let response = response(action.clone(), content.clone());
Box::pin(async move { Ok(response) })
}),
)
.await?;
assert_eq!(
call(&client).await?,
serde_json::to_value(
rmcp::model::CallToolResult::error(vec![rmcp::model::ContentBlock::text(
"Authentication required",
)])
.with_meta(Some(rmcp::model::MetaObject::from(
serde_json::Map::from_iter([(
"mcp/www_authenticate".into(),
json!(["Bearer error=\"invalid_token\""]),
)])
)))
)?
);
client.shutdown().await;
server.verify().await;
}
Ok(())
}
#[tokio::test]
async fn native_mrtr_does_not_restart_after_continuation_session_expiry() -> anyhow::Result<()> {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(|request: &Request| {
let body: Value = request.body_json().unwrap();
match body["method"].as_str() {
Some("server/discover") => discover_response(&body),
Some("tools/call") if body.pointer("/params/inputResponses").is_none() => {
result_response(&body, input_required(native_request()))
}
Some("tools/call") => ResponseTemplate::new(/*s*/ 404),
other => panic!("unexpected request: {other:?}"),
}
})
.expect(/*r*/ 3)
.mount(&server)
.await;
let client = client(
&server,
capabilities(),
Box::new(|_, _| {
Box::pin(async {
Ok(response(
ElicitationAction::Accept,
json!({"credentialId": "test", "signature": "BAUG"}),
))
})
}),
)
.await?;
let error = call(&client).await.unwrap_err();
assert!(
error
.to_string()
.contains("the operation was not restarted"),
"{error}"
);
client.shutdown().await;
Ok(())
}
#[tokio::test]
async fn native_mrtr_does_not_restart_after_proof_then_state_only_round() -> anyhow::Result<()> {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(|request: &Request| {
let body: Value = request.body_json().unwrap();
match body["method"].as_str() {
Some("server/discover") => discover_response(&body),
Some("tools/call") if body.pointer("/params/requestState").is_none() => {
result_response(&body, input_required(native_request()))
}
Some("tools/call") if body.pointer("/params/inputResponses").is_some() => {
result_response(
&body,
json!({"resultType": "input_required", "requestState": "after-proof"}),
)
}
Some("tools/call") => ResponseTemplate::new(/*s*/ 404),
other => panic!("unexpected request: {other:?}"),
}
})
.expect(/*r*/ 4)
.mount(&server)
.await;
let client = client(
&server,
capabilities(),
Box::new(|_, _| {
Box::pin(async {
Ok(response(
ElicitationAction::Accept,
json!({"credentialId": "test", "signature": "BAUG"}),
))
})
}),
)
.await?;
let error = call(&client).await.unwrap_err();
assert!(
error
.to_string()
.contains("the operation was not restarted"),
"{error}"
);
client.shutdown().await;
server.verify().await;
Ok(())
}
#[tokio::test]
async fn native_mrtr_shared_calls_isolate_inputs_cancellation_and_timeouts() -> anyhow::Result<()> {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(|request: &Request| {
let body: Value = request.body_json().unwrap();
match body["method"].as_str() {
Some("server/discover") => discover_response(&body),
Some("tools/call") if body["params"]["name"] == "slow" => {
result_response(&body, json!({"resultType": "complete", "content": []}))
.set_delay(Duration::from_secs(1))
}
Some("tools/call") if body.pointer("/params/inputResponses").is_none() => {
result_response(&body, input_required(native_request()))
}
Some("tools/call") => {
assert_eq!(
body["params"]["inputResponses"],
json!({"verification": {"action": "cancel"}})
);
result_response(&body, json!({"resultType": "complete", "content": []}))
}
other => panic!("unexpected request: {other:?}"),
}
})
.expect(/*r*/ 5)
.mount(&server)
.await;
let (tx, mut rx) = mpsc::unbounded_channel();
let client = client(
&server,
capabilities(),
Box::new(|_, _| panic!("shared input must use the calling chat's callback")),
)
.await?;
let launch = |caller| {
let client = Arc::clone(&client);
let tx = tx.clone();
tokio::spawn(async move {
let sender: SendElicitation = Box::new(move |id, _| {
let (reply_tx, reply_rx) = oneshot::channel();
tx.send((caller, id, reply_tx)).unwrap();
Box::pin(async move { Ok(reply_rx.await?) })
});
client
.call_tool_with_elicitation(
"verified_operation".into(),
/*arguments*/ None,
|_| Ok(None),
Some(Duration::from_secs(5)),
Arc::new(sender),
)
.await
})
};
let first_call = launch("first");
let (first_caller, first_id, mut first_reply) =
timeout(Duration::from_secs(/*secs*/ 5), rx.recv())
.await?
.unwrap();
let second_call = launch("second");
let (second_caller, second_id, second_reply) =
timeout(Duration::from_secs(/*secs*/ 5), rx.recv())
.await?
.unwrap();
assert_ne!(first_id, second_id);
assert_eq!((first_caller, second_caller), ("first", "second"));
let timeout_error = client
.call_tool_with_elicitation(
"slow".into(),
/*arguments*/ None,
|_| Ok(None),
Some(Duration::from_millis(100)),
Arc::new(Box::new(|_, _| panic!("slow call must not ask for input"))),
)
.await
.unwrap_err();
assert!(
timeout_error.to_string().contains("timed out"),
"{timeout_error}"
);
first_call.abort();
assert!(first_call.await.unwrap_err().is_cancelled());
timeout(Duration::from_secs(/*secs*/ 5), first_reply.closed()).await?;
assert!(!second_reply.is_closed());
second_reply
.send(response(ElicitationAction::Cancel, Value::Null))
.unwrap();
assert_eq!(
serde_json::to_value(timeout(Duration::from_secs(/*secs*/ 5), second_call).await???)?,
json!({"resultType": "complete", "content": []})
);
client.shutdown().await;
Ok(())
}

View File

@@ -0,0 +1,692 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Context as _;
use akode_config::types::AuthKeyringBackendKind;
use akode_config::types::OAuthCredentialsStoreMode;
use akode_exec_server::Environment;
use akode_exec_server::HttpClient;
use akode_rmcp_client::McpOAuthCallbackMode;
use akode_rmcp_client::McpOAuthClientRegistration;
use akode_rmcp_client::OAuthDiscoveryTimeout;
use akode_rmcp_client::StreamableHttpOAuthDiscovery;
use akode_rmcp_client::StreamableHttpRedirectMode;
use akode_rmcp_client::discover_streamable_http_oauth;
use akode_rmcp_client::perform_oauth_login_return_url;
use pretty_assertions::assert_eq;
use rmcp::transport::auth::AuthError;
use serde_json::json;
use tokio::time::timeout;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
const RESOURCE_AUTHORIZATION: &str = "Bearer resource-only-secret";
const RESOURCE_API_KEY: &str = "resource-api-key-secret";
const RESOURCE_USER_AGENT: &str = "resource-only-user-agent";
const MCP_USER_AGENT: &str = concat!("codex-mcp-client/", env!("CARGO_PKG_VERSION"));
// This is a test safety ceiling, not rmcp's private redirect limit.
const MAX_METADATA_REDIRECT_REQUESTS: u64 = 100;
const REDIRECT_DISCOVERY_TEST_TIMEOUT: Duration = Duration::from_secs(5);
type DiscoveryResult = anyhow::Result<Option<StreamableHttpOAuthDiscovery>>;
#[derive(Clone, Copy)]
enum AuthorizationMetadataIssuer {
Matching,
Missing,
Mismatched,
}
#[derive(Clone, Copy)]
enum MetadataDelivery {
Direct,
SameOriginRedirects,
}
fn resource_headers() -> Option<HashMap<String, String>> {
Some(HashMap::from([
(
"Authorization".to_string(),
RESOURCE_AUTHORIZATION.to_string(),
),
("X-Api-Key".to_string(), RESOURCE_API_KEY.to_string()),
("User-Agent".to_string(), RESOURCE_USER_AGENT.to_string()),
]))
}
fn local_http_client() -> Arc<dyn HttpClient> {
Environment::default_for_tests().get_http_client()
}
async fn discover_with_local_http_client(
resource_url: &str,
redirect_mode: StreamableHttpRedirectMode,
) -> DiscoveryResult {
discover_streamable_http_oauth(
resource_url,
resource_headers(),
/*env_http_headers*/ None,
local_http_client(),
OAuthDiscoveryTimeout::LOCAL,
redirect_mode,
)
.await
}
async fn assert_authorization_requests_exclude_resource_headers(
authorization_server: &MockServer,
) -> anyhow::Result<()> {
let requests = authorization_server
.received_requests()
.await
.context("authorization-server request recording should be enabled")?;
assert!(
!requests.is_empty(),
"OAuth discovery must contact the authorization server"
);
for request in requests {
assert_eq!(request.headers.get("authorization"), None);
assert_eq!(request.headers.get("x-api-key"), None);
assert_eq!(
request
.headers
.get("user-agent")
.map(wiremock::http::HeaderValue::as_bytes),
Some(MCP_USER_AGENT.as_bytes())
);
}
Ok(())
}
fn assert_cross_origin_redirect_rejected(
discovery: DiscoveryResult,
redirect_target: &str,
) -> anyhow::Result<()> {
let error = discovery
.err()
.context("cross-origin OAuth metadata redirects must be rejected")?;
assert!(
matches!(
error.downcast_ref::<AuthError>(),
Some(AuthError::MetadataError(reason))
if reason.contains("OAuth discovery redirect to non-same-origin URL rejected")
&& reason.contains(redirect_target)
),
"expected the cross-origin redirect rejection for `{redirect_target}`: {error:#}",
);
Ok(())
}
async fn assert_legacy_oauth_without_starting_an_mcp_session(
metadata_issuer: AuthorizationMetadataIssuer,
metadata_delivery: MetadataDelivery,
) -> anyhow::Result<()> {
let resource_server = MockServer::start().await;
let authorization_server = MockServer::start().await;
let resource_url = format!("{}/mcp", resource_server.uri());
let resource_metadata_url = format!("{}/resource-metadata", resource_server.uri());
Mock::given(method("GET"))
.and(path("/mcp"))
.and(header("authorization", RESOURCE_AUTHORIZATION))
.and(header("x-api-key", RESOURCE_API_KEY))
.and(header("user-agent", RESOURCE_USER_AGENT))
.respond_with(ResponseTemplate::new(401).insert_header(
"www-authenticate",
format!("Bearer resource_metadata=\"{resource_metadata_url}\""),
))
.expect(2)
.mount(&resource_server)
.await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(ResponseTemplate::new(500))
.expect(0)
.mount(&resource_server)
.await;
let (resource_metadata_path, authorization_metadata_path) = match metadata_delivery {
MetadataDelivery::Direct => (
"/resource-metadata",
"/.well-known/oauth-authorization-server",
),
MetadataDelivery::SameOriginRedirects => {
Mock::given(method("GET"))
.and(path("/resource-metadata"))
.and(header("authorization", RESOURCE_AUTHORIZATION))
.and(header("x-api-key", RESOURCE_API_KEY))
.and(header("user-agent", RESOURCE_USER_AGENT))
.respond_with(
ResponseTemplate::new(302)
.insert_header("location", "/redirected-resource-metadata"),
)
.expect(2)
.mount(&resource_server)
.await;
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server"))
.respond_with(
ResponseTemplate::new(302)
.insert_header("location", "/redirected-authorization-metadata"),
)
.expect(2)
.mount(&authorization_server)
.await;
(
"/redirected-resource-metadata",
"/redirected-authorization-metadata",
)
}
};
Mock::given(method("GET"))
.and(path(resource_metadata_path))
.and(header("authorization", RESOURCE_AUTHORIZATION))
.and(header("x-api-key", RESOURCE_API_KEY))
.and(header("user-agent", RESOURCE_USER_AGENT))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"resource": resource_url,
"authorization_servers": [authorization_server.uri()],
"scopes_supported": ["mcp:read"],
})))
.expect(2)
.mount(&resource_server)
.await;
let mut metadata = json!({
"authorization_endpoint": format!("{}/authorize", authorization_server.uri()),
"token_endpoint": format!("{}/token", authorization_server.uri()),
"code_challenge_methods_supported": ["S256"],
});
match metadata_issuer {
AuthorizationMetadataIssuer::Matching => {
metadata["issuer"] = json!(authorization_server.uri());
}
AuthorizationMetadataIssuer::Missing => {}
AuthorizationMetadataIssuer::Mismatched => {
metadata["issuer"] = json!("https://unexpected-issuer.example");
}
}
Mock::given(method("GET"))
.and(path(authorization_metadata_path))
.respond_with(ResponseTemplate::new(200).set_body_json(metadata))
.expect(2)
.mount(&authorization_server)
.await;
for redirect_mode in [
StreamableHttpRedirectMode::Legacy,
StreamableHttpRedirectMode::AgentPluginV1,
] {
let discovery = discover_with_local_http_client(&resource_url, redirect_mode).await;
match metadata_issuer {
AuthorizationMetadataIssuer::Matching | AuthorizationMetadataIssuer::Missing => {
assert_eq!(
discovery?,
Some(StreamableHttpOAuthDiscovery {
scopes_supported: Some(vec!["mcp:read".to_string()]),
callback_mode: McpOAuthCallbackMode::CallbackSpecific,
}),
);
}
AuthorizationMetadataIssuer::Mismatched => {
let error = discovery
.err()
.context("a mismatched issuer must not be accepted")?;
assert!(
matches!(
error.downcast_ref::<AuthError>(),
Some(AuthError::MetadataError(reason))
if reason.contains("issuer does not match authorization metadata origin")
),
"expected the original authorization-server issuer to remain bound: {error:#}",
);
}
}
}
resource_server.verify().await;
authorization_server.verify().await;
assert_authorization_requests_exclude_resource_headers(&authorization_server).await?;
Ok(())
}
#[tokio::test]
async fn oauth_discovery_uses_get_first_without_starting_a_legacy_mcp_session() -> anyhow::Result<()>
{
assert_legacy_oauth_without_starting_an_mcp_session(
AuthorizationMetadataIssuer::Matching,
MetadataDelivery::Direct,
)
.await
}
#[tokio::test]
async fn legacy_oauth_discovery_follows_same_origin_metadata_redirects() -> anyhow::Result<()> {
assert_legacy_oauth_without_starting_an_mcp_session(
AuthorizationMetadataIssuer::Matching,
MetadataDelivery::SameOriginRedirects,
)
.await
}
#[tokio::test]
async fn legacy_oauth_discovery_rejects_cross_origin_authorization_metadata_redirects()
-> anyhow::Result<()> {
let resource_server = MockServer::start().await;
let authorization_server = MockServer::start().await;
let redirect_target = MockServer::start().await;
let resource_url = format!("{}/mcp", resource_server.uri());
let resource_metadata_url = format!("{}/resource-metadata", resource_server.uri());
Mock::given(method("GET"))
.and(path("/mcp"))
.and(header("authorization", RESOURCE_AUTHORIZATION))
.and(header("x-api-key", RESOURCE_API_KEY))
.and(header("user-agent", RESOURCE_USER_AGENT))
.respond_with(ResponseTemplate::new(401).insert_header(
"www-authenticate",
format!("Bearer resource_metadata=\"{resource_metadata_url}\""),
))
.expect(1)
.mount(&resource_server)
.await;
Mock::given(method("GET"))
.and(path("/resource-metadata"))
.and(header("authorization", RESOURCE_AUTHORIZATION))
.and(header("x-api-key", RESOURCE_API_KEY))
.and(header("user-agent", RESOURCE_USER_AGENT))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"resource": resource_url,
"authorization_servers": [authorization_server.uri()],
})))
.expect(1)
.mount(&resource_server)
.await;
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server"))
.respond_with(ResponseTemplate::new(302).insert_header(
"location",
format!(
"{}/redirected-authorization-metadata",
redirect_target.uri()
),
))
.expect(1)
.mount(&authorization_server)
.await;
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(200))
.expect(0)
.mount(&redirect_target)
.await;
let discovery =
discover_with_local_http_client(&resource_url, StreamableHttpRedirectMode::Legacy).await;
assert_cross_origin_redirect_rejected(discovery, &redirect_target.uri())?;
assert!(
redirect_target
.received_requests()
.await
.context("cross-origin request recording should be enabled")?
.is_empty(),
"OAuth authorization-server metadata discovery must not contact a cross-origin redirect target",
);
redirect_target.verify().await;
authorization_server.verify().await;
resource_server.verify().await;
assert_authorization_requests_exclude_resource_headers(&authorization_server).await?;
Ok(())
}
#[tokio::test]
async fn legacy_oauth_discovery_rejects_authorization_metadata_redirect_cycles()
-> anyhow::Result<()> {
let resource_server = MockServer::start().await;
let authorization_server = MockServer::start().await;
let resource_url = format!("{}/mcp", resource_server.uri());
let resource_metadata_url = format!("{}/resource-metadata", resource_server.uri());
Mock::given(method("GET"))
.and(path("/mcp"))
.and(header("authorization", RESOURCE_AUTHORIZATION))
.and(header("x-api-key", RESOURCE_API_KEY))
.and(header("user-agent", RESOURCE_USER_AGENT))
.respond_with(ResponseTemplate::new(401).insert_header(
"www-authenticate",
format!("Bearer resource_metadata=\"{resource_metadata_url}\""),
))
.expect(1)
.mount(&resource_server)
.await;
Mock::given(method("GET"))
.and(path("/resource-metadata"))
.and(header("authorization", RESOURCE_AUTHORIZATION))
.and(header("x-api-key", RESOURCE_API_KEY))
.and(header("user-agent", RESOURCE_USER_AGENT))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"resource": resource_url,
"authorization_servers": [authorization_server.uri()],
})))
.expect(1)
.mount(&resource_server)
.await;
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server"))
.respond_with(
ResponseTemplate::new(302)
.insert_header("location", "/.well-known/oauth-authorization-server"),
)
.expect(2..=MAX_METADATA_REDIRECT_REQUESTS)
.mount(&authorization_server)
.await;
let discovery = timeout(
REDIRECT_DISCOVERY_TEST_TIMEOUT,
discover_with_local_http_client(&resource_url, StreamableHttpRedirectMode::Legacy),
)
.await
.context("OAuth metadata redirect cycles must fail within the bounded discovery timeout")?;
let error = discovery
.err()
.context("OAuth metadata redirect cycles must be rejected")?;
assert!(
matches!(
error.downcast_ref::<AuthError>(),
Some(AuthError::MetadataError(reason))
if reason.contains("OAuth discovery exceeded ") && reason.contains(" redirects")
),
"expected the SDK to report its bounded OAuth discovery redirect limit: {error:#}",
);
authorization_server.verify().await;
resource_server.verify().await;
assert_authorization_requests_exclude_resource_headers(&authorization_server).await?;
Ok(())
}
#[tokio::test]
async fn legacy_oauth_discovery_rejects_cross_origin_resource_metadata_redirects()
-> anyhow::Result<()> {
let resource_server = MockServer::start().await;
let redirect_target = MockServer::start().await;
let resource_url = format!("{}/mcp", resource_server.uri());
let resource_metadata_url = format!("{}/resource-metadata", resource_server.uri());
Mock::given(method("GET"))
.and(path("/mcp"))
.and(header("authorization", RESOURCE_AUTHORIZATION))
.and(header("x-api-key", RESOURCE_API_KEY))
.and(header("user-agent", RESOURCE_USER_AGENT))
.respond_with(ResponseTemplate::new(401).insert_header(
"www-authenticate",
format!("Bearer resource_metadata=\"{resource_metadata_url}\""),
))
.expect(1)
.mount(&resource_server)
.await;
Mock::given(method("GET"))
.and(path("/resource-metadata"))
.and(header("authorization", RESOURCE_AUTHORIZATION))
.and(header("x-api-key", RESOURCE_API_KEY))
.and(header("user-agent", RESOURCE_USER_AGENT))
.respond_with(ResponseTemplate::new(302).insert_header(
"location",
format!("{}/redirect-target", redirect_target.uri()),
))
.expect(1)
.mount(&resource_server)
.await;
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(200))
.expect(0)
.mount(&redirect_target)
.await;
let discovery =
discover_with_local_http_client(&resource_url, StreamableHttpRedirectMode::Legacy).await;
assert_cross_origin_redirect_rejected(discovery, &redirect_target.uri())?;
assert!(
redirect_target
.received_requests()
.await
.context("cross-origin request recording should be enabled")?
.is_empty(),
"OAuth discovery must not contact a cross-origin redirect target",
);
redirect_target.verify().await;
resource_server.verify().await;
Ok(())
}
#[tokio::test]
async fn legacy_oauth_discovery_accepts_authorization_metadata_without_an_issuer()
-> anyhow::Result<()> {
for metadata_delivery in [
MetadataDelivery::Direct,
MetadataDelivery::SameOriginRedirects,
] {
assert_legacy_oauth_without_starting_an_mcp_session(
AuthorizationMetadataIssuer::Missing,
metadata_delivery,
)
.await?;
}
Ok(())
}
#[tokio::test]
async fn legacy_oauth_discovery_rejects_an_explicit_mismatched_issuer() -> anyhow::Result<()> {
for metadata_delivery in [
MetadataDelivery::Direct,
MetadataDelivery::SameOriginRedirects,
] {
assert_legacy_oauth_without_starting_an_mcp_session(
AuthorizationMetadataIssuer::Mismatched,
metadata_delivery,
)
.await?;
}
Ok(())
}
#[tokio::test]
async fn oauth_discovery_does_not_invent_support_for_an_unauthenticated_legacy_server()
-> anyhow::Result<()> {
let resource_server = MockServer::start().await;
let server_url = format!("{}/mcp", resource_server.uri());
let local_discovery = discover_streamable_http_oauth(
&server_url,
/*http_headers*/ None,
/*env_http_headers*/ None,
local_http_client(),
OAuthDiscoveryTimeout::LOCAL,
StreamableHttpRedirectMode::Legacy,
)
.await?;
assert_eq!(local_discovery, None);
Ok(())
}
#[tokio::test]
async fn interactive_oauth_rejects_untrusted_authorization_metadata() -> anyhow::Result<()> {
for (metadata_issuer, authorization_metadata_path, issuer_bound_callbacks) in [
(
AuthorizationMetadataIssuer::Missing,
"/.well-known/untrusted-provider",
false,
),
(
AuthorizationMetadataIssuer::Mismatched,
"/.well-known/untrusted-provider",
true,
),
(
AuthorizationMetadataIssuer::Mismatched,
"/metadata.json",
false,
),
(
AuthorizationMetadataIssuer::Mismatched,
"/metadata.json",
true,
),
(
AuthorizationMetadataIssuer::Mismatched,
"/.well-known/oauth-authorization-server",
false,
),
(
AuthorizationMetadataIssuer::Mismatched,
"/.well-known/oauth-authorization-server",
true,
),
(
AuthorizationMetadataIssuer::Mismatched,
"/.well-known/openid-configuration",
true,
),
(
AuthorizationMetadataIssuer::Matching,
"/.well-known/untrusted-provider",
false,
),
] {
let resource_server = MockServer::start().await;
let authorization_server = MockServer::start().await;
let attacker_token_server = MockServer::start().await;
let resource_url = format!("{}/mcp", resource_server.uri());
let resource_metadata_url = format!("{}/resource-metadata", resource_server.uri());
let (issuer, expected_error) = match metadata_issuer {
AuthorizationMetadataIssuer::Missing => (
None,
"token endpoint origin does not match the authorization server origin",
),
AuthorizationMetadataIssuer::Mismatched => (
Some(authorization_server.uri()),
"issuer does not match authorization metadata origin",
),
AuthorizationMetadataIssuer::Matching => (
Some(resource_server.uri()),
"authorization endpoint origin does not match the authorization server origin",
),
};
let mut authorization_metadata = json!({
"authorization_endpoint": format!("{}/authorize", authorization_server.uri()),
"registration_endpoint": format!("{}/register", authorization_server.uri()),
"token_endpoint": format!("{}/token", attacker_token_server.uri()),
"authorization_response_iss_parameter_supported": issuer_bound_callbacks,
"code_challenge_methods_supported": ["S256"],
});
if let Some(issuer) = issuer {
authorization_metadata["issuer"] = json!(issuer);
}
Mock::given(method("GET"))
.and(path("/mcp"))
.respond_with(ResponseTemplate::new(401).insert_header(
"www-authenticate",
format!("Bearer resource_metadata=\"{resource_metadata_url}\""),
))
.expect(2)
.mount(&resource_server)
.await;
Mock::given(method("GET"))
.and(path("/resource-metadata"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"resource": resource_url,
"authorization_servers": [format!(
"{}/.well-known/untrusted-provider",
resource_server.uri()
)],
})))
.expect(2)
.mount(&resource_server)
.await;
if authorization_metadata_path != "/.well-known/untrusted-provider" {
Mock::given(method("GET"))
.and(path("/.well-known/untrusted-provider"))
.respond_with(
ResponseTemplate::new(302)
.insert_header("location", authorization_metadata_path),
)
.expect(2)
.mount(&resource_server)
.await;
}
Mock::given(method("GET"))
.and(path(authorization_metadata_path))
.respond_with(ResponseTemplate::new(200).set_body_json(authorization_metadata))
.expect(2)
.mount(&resource_server)
.await;
Mock::given(method("POST"))
.respond_with(ResponseTemplate::new(200))
.expect(0)
.mount(&attacker_token_server)
.await;
for oauth_client_id in [None, Some("preregistered-client")] {
let oauth_config =
oauth_client_id.map(|client_id| akode_config::McpServerOAuthConfig {
client_id: Some(client_id.to_string()),
..Default::default()
});
let error = perform_oauth_login_return_url(
"untrusted-oauth-metadata",
&resource_url,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::Direct,
/*http_headers*/ None,
/*env_http_headers*/ None,
/*scopes*/ &[],
oauth_config.as_ref(),
McpOAuthClientRegistration::Dcr,
/*oauth_resource*/ None,
Some(/*timeout_secs*/ 5),
/*callback_port*/ None,
/*callback_url*/ None,
/*global_callback_url*/ None,
local_http_client(),
StreamableHttpRedirectMode::Legacy,
)
.await
.err()
.context("untrusted OAuth authorization metadata must fail")?;
assert!(
format!("{error:#}").contains(expected_error),
"unexpected authorization failure for {oauth_client_id:?}: {error:#}",
);
}
assert!(
attacker_token_server
.received_requests()
.await
.context("attacker token server request recording should be enabled")?
.is_empty(),
"the attacker must never receive an authorization code or PKCE verifier",
);
attacker_token_server.verify().await;
authorization_server.verify().await;
resource_server.verify().await;
}
Ok(())
}

View File

@@ -0,0 +1,203 @@
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use akode_config::types::AuthKeyringBackendKind;
use akode_config::types::OAuthCredentialsStoreMode;
use akode_exec_server::Environment;
use akode_rmcp_client::ElicitationAction;
use akode_rmcp_client::ElicitationResponse;
use akode_rmcp_client::McpProtocolMode;
use akode_rmcp_client::RmcpClient;
use futures::FutureExt;
use pretty_assertions::assert_eq;
use rmcp::model::ClientCapabilities;
use rmcp::model::Implementation;
use rmcp::model::InitializeRequestParams;
use rmcp::model::ProtocolVersion;
use serde_json::Value;
use serde_json::json;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::Request;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
const MODERN_VERSION: &str = "2026-07-28";
const LEGACY_VERSION: &str = "2025-06-18";
async fn initialize_modern_client(server: &MockServer) -> anyhow::Result<RmcpClient> {
let client = RmcpClient::new_streamable_http_client_with_protocol_mode(
"sse-discovery-test",
&format!("{}/mcp", server.uri()),
/*bearer_token*/ None,
/*http_headers*/ None,
/*env_http_headers*/ None,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
Environment::default_for_tests().get_http_client(),
/*auth_provider*/ None,
McpProtocolMode::V20260728,
)
.await?;
let params = InitializeRequestParams::new(
ClientCapabilities::default(),
Implementation::new("codex-sse-discovery-test", "0.0.0"),
)
.with_protocol_version(ProtocolVersion::V_2025_06_18);
client
.initialize(
params,
Some(Duration::from_secs(5)),
Box::new(|_, _| {
async {
Ok(ElicitationResponse {
action: ElicitationAction::Accept,
content: Some(json!({})),
meta: None,
})
}
.boxed()
}),
)
.await?;
Ok(client)
}
fn sse_response(message: Value) -> ResponseTemplate {
ResponseTemplate::new(200).set_body_raw(
format!("event: message\ndata: {message}\n\n"),
"text/event-stream",
)
}
#[tokio::test]
async fn modern_sse_discovery_accepts_metadata_namespaced_server_identity() -> anyhow::Result<()> {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(|request: &Request| {
let body: Value = request.body_json().expect("valid JSON-RPC request");
assert_eq!(body["method"], "server/discover");
sse_response(json!({
"jsonrpc": "2.0",
"id": body["id"],
"result": {
"resultType": "complete",
"supportedVersions": [MODERN_VERSION],
"capabilities": {"tools": {}},
"_meta": {
"io.modelcontextprotocol/serverInfo": {
"name": "modern-sse-test",
"version": "1.0.0",
},
},
"ttlMs": 0,
"cacheScope": "private",
},
}))
})
.expect(1)
.mount(&server)
.await;
let client = initialize_modern_client(&server).await?;
client.shutdown().await;
Ok(())
}
#[tokio::test]
async fn modern_sse_discovery_falls_back_for_correlated_method_not_found() -> anyhow::Result<()> {
let server = MockServer::start().await;
let observed = Arc::new(Mutex::new(Vec::<String>::new()));
let recorded = Arc::clone(&observed);
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(move |request: &Request| {
let body: Value = request.body_json().expect("valid JSON-RPC request");
let method = body["method"].as_str().expect("JSON-RPC method");
recorded.lock().expect("requests lock").push(method.into());
match method {
"server/discover" => sse_response(json!({
"jsonrpc": "2.0",
"id": body["id"],
"error": {"code": -32601, "message": "method not found"},
})),
"initialize" => {
assert_eq!(body["params"]["protocolVersion"], LEGACY_VERSION);
ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
"id": body["id"],
"result": {
"protocolVersion": LEGACY_VERSION,
"capabilities": {"tools": {}},
"serverInfo": {
"name": "legacy-sse-test",
"version": "1.0.0",
},
},
}))
}
"notifications/initialized" => ResponseTemplate::new(202),
other => panic!("unexpected legacy SSE fallback request: {other}"),
}
})
.expect(3)
.mount(&server)
.await;
let client = initialize_modern_client(&server).await?;
assert_eq!(
*observed.lock().expect("requests lock"),
vec!["server/discover", "initialize", "notifications/initialized"]
);
client.shutdown().await;
Ok(())
}
#[tokio::test]
async fn modern_sse_discovery_rejects_uncorrelated_method_not_found() -> anyhow::Result<()> {
for (case, rejected_id) in [("null", json!(null)), ("mismatched", json!("unrelated"))] {
let server = MockServer::start().await;
let observed = Arc::new(Mutex::new(Vec::<String>::new()));
let recorded = Arc::clone(&observed);
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(move |request: &Request| {
let body: Value = request.body_json().expect("valid JSON-RPC request");
let method = body["method"].as_str().expect("JSON-RPC method");
recorded.lock().expect("requests lock").push(method.into());
assert_eq!(method, "server/discover");
sse_response(json!({
"jsonrpc": "2.0",
"id": rejected_id.clone(),
"error": {"code": -32601, "message": "method not found"},
}))
})
.expect(1)
.mount(&server)
.await;
assert!(
initialize_modern_client(&server).await.is_err(),
"{case} SSE discovery error must not downgrade to legacy"
);
assert_eq!(
*observed.lock().expect("requests lock"),
vec!["server/discover"],
"{case} SSE discovery error must not initialize a legacy session"
);
}
Ok(())
}

View File

@@ -0,0 +1,279 @@
use std::collections::HashMap;
use std::ffi::OsString;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use akode_exec_server::Environment;
use akode_rmcp_client::Elicitation;
use akode_rmcp_client::ElicitationAction;
use akode_rmcp_client::ElicitationResponse;
use akode_rmcp_client::ExecutorStdioServerLauncher;
use akode_rmcp_client::LocalStdioServerLauncher;
use akode_rmcp_client::McpProtocolMode;
use akode_rmcp_client::RmcpClient;
use akode_rmcp_client::StdioServerLauncher;
use futures::FutureExt;
use pretty_assertions::assert_eq;
use rmcp::model::ClientCapabilities;
use rmcp::model::ElicitRequestParams;
use rmcp::model::ElicitationCapability;
use rmcp::model::FormElicitationCapability;
use rmcp::model::Implementation;
use rmcp::model::InitializeRequestParams;
use rmcp::model::ProtocolVersion;
use serde_json::json;
async fn exercise_stdio_server(
server_mode: &str,
protocol_mode: McpProtocolMode,
opt_in: bool,
use_executor: bool,
) -> anyhow::Result<()> {
let server = akode_utils_cargo_bin::cargo_bin("test_mcp_2026_stdio_server")?;
let launcher: Arc<dyn StdioServerLauncher> = if use_executor {
Arc::new(ExecutorStdioServerLauncher::new(
Environment::default_for_tests().get_exec_backend(),
))
} else {
Arc::new(LocalStdioServerLauncher::new(std::env::current_dir()?))
};
let mut env = HashMap::new();
if opt_in {
env.insert(
OsString::from("AKODE_MCP_PROTOCOL_VERSION"),
OsString::from("2026-07-28"),
);
}
let root = tempfile::tempdir()?;
let cwd = if use_executor {
std::env::current_dir()?
} else {
root.path().to_path_buf()
};
#[cfg(unix)]
let server = if use_executor {
server
} else {
let wrapper = root.path().join("server");
let script = "#!/bin/sh\nprintf '%s' \"$0\" > argv0\nexec \"$MCP_SERVER\" \"$@\"\n";
akode_utils_cargo_bin::write_executable(&wrapper, script)?;
env.insert(OsString::from("MCP_SERVER"), server.into_os_string());
std::path::PathBuf::from("./server")
};
let client = RmcpClient::new_stdio_client_with_protocol_mode(
server.into(),
vec![OsString::from(server_mode)],
Some(env),
&[],
Some(cwd.to_string_lossy().into_owned()),
launcher,
protocol_mode,
)
.await?;
let mut capabilities = ClientCapabilities::default();
capabilities.elicitation =
Some(ElicitationCapability::new().with_form(FormElicitationCapability::new()));
let elicitation_count = Arc::new(AtomicUsize::new(0));
let observed_elicitations = Arc::clone(&elicitation_count);
let legacy_session = server_mode.starts_with("legacy");
let initialized = client
.initialize(
InitializeRequestParams::new(
capabilities,
Implementation::new("codex-mcp-client", "0.0.0-test"),
)
.with_protocol_version(ProtocolVersion::V_2025_06_18),
Some(Duration::from_secs(if server_mode.ends_with("-late") {
30
} else {
5
})),
Box::new(move |_request_id, request| {
let observed_elicitations = Arc::clone(&observed_elicitations);
async move {
observed_elicitations.fetch_add(1, Ordering::Relaxed);
let Elicitation::Mcp(ElicitRequestParams::FormElicitationParams {
requested_schema,
..
}) = request
else {
anyhow::bail!("expected a standard MCP form elicitation");
};
let content = if legacy_session {
assert_eq!(
serde_json::to_value(requested_schema)?,
json!({
"type": "object",
"properties": {
"name": {"type": "string", "default": "John Doe"},
"age": {"type": "integer", "default": 30},
"score": {"type": "number", "default": 95.5},
"status": {
"type": "string",
"enum": ["active", "inactive"],
"default": "active",
},
"verified": {"type": "boolean", "default": true},
},
"required": [],
}),
);
json!({
"name": "John Doe",
"age": 30,
"score": 95.5,
"status": "active",
"verified": true,
})
} else {
json!({"approved": true})
};
Ok(ElicitationResponse {
action: ElicitationAction::Accept,
content: Some(content),
meta: None,
})
}
.boxed()
}),
)
.await?;
let expected_version = if legacy_session {
ProtocolVersion::V_2025_06_18
} else {
ProtocolVersion::V_2026_07_28
};
assert_eq!(initialized.protocol_version, expected_version);
assert_eq!(
initialized
.server_info
.as_ref()
.map(|server_info| server_info.name.as_str()),
Some(if legacy_session {
"legacy-stdio-test"
} else {
"strict-stdio-test"
})
);
let tools = client
.list_tools(/*params*/ None, Some(Duration::from_secs(5)))
.await?;
assert_eq!(
tools
.tools
.iter()
.map(|tool| tool.name.as_ref())
.collect::<Vec<_>>(),
vec!["echo"]
);
let result = client
.call_tool(
"echo".to_owned(),
Some(json!({"message": "hello stdio"})),
|_| Ok(None),
Some(Duration::from_secs(5)),
)
.await?;
assert_eq!(
result.content[0].as_text().map(|text| text.text.as_str()),
Some(if legacy_session {
"legacy approved"
} else {
"modern approved"
})
);
assert_eq!(elicitation_count.load(Ordering::Relaxed), 1);
#[cfg(unix)]
if !use_executor {
assert_eq!(
std::fs::read_to_string(root.path().join("argv0"))?,
"./server"
);
}
client.shutdown().await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn modern_local_stdio_discovers_metadata_only_identity_and_drives_mrtr() -> anyhow::Result<()>
{
exercise_stdio_server(
"modern",
McpProtocolMode::V20260728,
/*opt_in*/ true,
/*use_executor*/ false,
)
.await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn modern_executor_stdio_discovers_metadata_only_identity_and_drives_mrtr()
-> anyhow::Result<()> {
exercise_stdio_server(
"modern",
McpProtocolMode::V20260728,
/*opt_in*/ true,
/*use_executor*/ true,
)
.await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn legacy_stdio_supports_sep1034_defaults_without_the_rollout_flag() -> anyhow::Result<()> {
exercise_stdio_server(
"legacy",
McpProtocolMode::Legacy,
/*opt_in*/ false,
/*use_executor*/ false,
)
.await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn rollout_flag_alone_preserves_legacy_stdio_and_sep1034_defaults() -> anyhow::Result<()> {
exercise_stdio_server(
"legacy",
McpProtocolMode::V20260728,
/*opt_in*/ false,
/*use_executor*/ false,
)
.await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn unmarked_stdio_helpers_recover_from_failed_or_late_discovery() -> anyhow::Result<()> {
for mode in [
"legacy",
"legacy-init-first",
"legacy-reject-late-initialize",
"legacy-reject-and-exit",
"legacy-late",
"legacy-silent",
"legacy-versions",
"modern-late",
] {
exercise_stdio_server(
mode,
McpProtocolMode::DiscoverLocalStdio,
/*opt_in*/ false,
/*use_executor*/ false,
)
.await?;
}
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn modern_stdio_safely_falls_back_to_legacy_elicitation() -> anyhow::Result<()> {
exercise_stdio_server(
"legacy-fallback",
McpProtocolMode::V20260728,
/*opt_in*/ true,
/*use_executor*/ false,
)
.await
}

View File

@@ -0,0 +1,285 @@
use std::collections::HashMap;
use std::ffi::OsString;
use std::process::Command;
use std::sync::Arc;
use std::time::Duration;
use akode_exec_server::Environment;
use akode_network_proxy::CUSTOM_CA_ENV_KEYS;
use akode_rmcp_client::ElicitationAction;
use akode_rmcp_client::ElicitationResponse;
use akode_rmcp_client::ExecutorStdioServerLauncher;
use akode_rmcp_client::LocalStdioServerLauncher;
use akode_rmcp_client::McpProtocolMode;
use akode_rmcp_client::RmcpClient;
use akode_rmcp_client::StdioServerLauncher;
use futures::FutureExt;
use pretty_assertions::assert_eq;
use rmcp::model::ClientCapabilities;
use rmcp::model::Implementation;
use rmcp::model::InitializeRequestParams;
use rmcp::model::ProtocolVersion;
use serde_json::json;
#[test]
fn local_stdio_inherits_ca_certificate_variables() -> anyhow::Result<()> {
let directories = tempfile::tempdir()?;
let source_dir = directories.path().join("source");
let server_dir = directories.path().join("server");
std::fs::create_dir_all(source_dir.join("certs"))?;
std::fs::create_dir_all(&server_dir)?;
#[cfg(windows)]
let requests_ca_bundle = match source_dir.components().next() {
Some(std::path::Component::Prefix(prefix)) => match prefix.kind() {
std::path::Prefix::Disk(drive) | std::path::Prefix::VerbatimDisk(drive) => {
format!("{}:certs\\custom-ca.pem", char::from(drive))
}
_ => "certs/custom-ca.pem".to_string(),
},
_ => "certs/custom-ca.pem".to_string(),
};
#[cfg(not(windows))]
let requests_ca_bundle = "certs/custom-ca.pem";
let output = Command::new(std::env::current_exe()?)
.arg("--exact")
.arg("local_stdio_inherits_ca_certificate_variables_child")
.arg("--ignored")
.current_dir(&source_dir)
.envs(
CUSTOM_CA_ENV_KEYS
.into_iter()
.map(|name| (name, "certs/custom-ca.pem")),
)
.env("AKODE_CA_CERTIFICATE", "")
.env("REQUESTS_CA_BUNDLE", requests_ca_bundle)
.env("AKODE_MCP_TEST_SERVER_CWD", &server_dir)
.output()?;
assert!(
output.status.success(),
"MCP subprocess inheritance test failed:\n{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "child process for local_stdio_inherits_ca_certificate_variables"]
async fn local_stdio_inherits_ca_certificate_variables_child() -> anyhow::Result<()> {
let server = akode_utils_cargo_bin::cargo_bin("test_stdio_server")?;
let source_dir = std::env::current_dir()?;
let server_dir = std::env::var("AKODE_MCP_TEST_SERVER_CWD")?;
let expected = source_dir.join("certs").join("custom-ca.pem");
let npm_override = HashMap::from([(
OsString::from("NPM_CONFIG_CAFILE"),
OsString::from("explicit/custom-ca.pem"),
)]);
for (overrides, env_name, expected) in [
(
None,
"SSL_CERT_FILE",
Some(expected.to_string_lossy().into_owned()),
),
(
None,
"REQUESTS_CA_BUNDLE",
Some(expected.to_string_lossy().into_owned()),
),
(None, "AKODE_CA_CERTIFICATE", None),
(
Some(npm_override.clone()),
"NPM_CONFIG_CAFILE",
Some("explicit/custom-ca.pem".to_string()),
),
(Some(npm_override), "npm_config_cafile", None),
] {
let client = RmcpClient::new_stdio_client(
server.clone().into(),
Vec::new(),
overrides,
&[],
Some(server_dir.clone()),
Arc::new(LocalStdioServerLauncher::new(source_dir.clone())),
)
.await?;
client
.initialize(
InitializeRequestParams::new(
ClientCapabilities::default(),
Implementation::new("stdio-ca-inheritance-test", "1.0.0"),
)
.with_protocol_version(ProtocolVersion::V_2025_06_18),
Some(Duration::from_secs(10)),
Box::new(|_, _| {
async {
Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
})
}
.boxed()
}),
)
.await?;
let result = client
.call_tool(
"echo".to_string(),
Some(json!({ "message": "ca inheritance", "env_var": env_name })),
|_| Ok(None),
Some(Duration::from_secs(10)),
)
.await?;
assert_eq!(
result.structured_content,
Some(json!({ "echo": "ECHOING: ca inheritance", "env": expected }))
);
client.shutdown().await;
}
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn modern_local_and_executor_stdio_discover_metadata_identity_and_catalogs()
-> anyhow::Result<()> {
let server = akode_utils_cargo_bin::cargo_bin("test_mcp_2026_discovery_stdio_server")?;
for executor in [false, true] {
let launcher: Arc<dyn StdioServerLauncher> = if executor {
Arc::new(ExecutorStdioServerLauncher::new(
Environment::default_for_tests().get_exec_backend(),
))
} else {
Arc::new(LocalStdioServerLauncher::new(std::env::current_dir()?))
};
let client = RmcpClient::new_stdio_client_with_protocol_mode(
server.clone().into(),
Vec::new(),
Some(HashMap::from([(
OsString::from("AKODE_MCP_PROTOCOL_VERSION"),
OsString::from("2026-07-28"),
)])),
&[],
Some(std::env::current_dir()?.to_string_lossy().into_owned()),
launcher,
McpProtocolMode::V20260728,
)
.await?;
client
.initialize(
InitializeRequestParams::new(
ClientCapabilities::default(),
Implementation::new("stdio-discovery-test", "1.0.0"),
)
.with_protocol_version(ProtocolVersion::V_2025_06_18),
Some(Duration::from_secs(10)),
Box::new(|_, _| {
async {
Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
})
}
.boxed()
}),
)
.await?;
let tools = client
.list_tools(/*params*/ None, Some(Duration::from_secs(10)))
.await?;
assert_eq!(tools.tools[0].name.as_ref(), "stdio_echo");
let resources = client
.list_resources(/*params*/ None, Some(Duration::from_secs(10)))
.await?;
assert_eq!(resources.resources[0].uri, "test://stdio/resource");
let templates = client
.list_resource_templates(/*params*/ None, Some(Duration::from_secs(10)))
.await?;
assert_eq!(
templates.resource_templates[0].name,
"stdio resource template"
);
client.shutdown().await;
}
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn legacy_stdio_preserves_existing_protocol_marker_environment() -> anyhow::Result<()> {
let server = akode_utils_cargo_bin::cargo_bin("test_stdio_server")?;
for executor in [false, true] {
for version in ["2026-07-28", "1999-01-01"] {
let launcher: Arc<dyn StdioServerLauncher> = if executor {
Arc::new(ExecutorStdioServerLauncher::new(
Environment::default_for_tests().get_exec_backend(),
))
} else {
Arc::new(LocalStdioServerLauncher::new(std::env::current_dir()?))
};
let client = RmcpClient::new_stdio_client_with_protocol_mode(
server.clone().into(),
Vec::new(),
Some(HashMap::from([(
OsString::from("AKODE_MCP_PROTOCOL_VERSION"),
OsString::from(version),
)])),
&[],
Some(std::env::current_dir()?.to_string_lossy().into_owned()),
launcher,
McpProtocolMode::Legacy,
)
.await?;
client
.initialize(
InitializeRequestParams::new(
ClientCapabilities::default(),
Implementation::new("stdio-legacy-environment-test", "1.0.0"),
)
.with_protocol_version(ProtocolVersion::V_2025_06_18),
Some(Duration::from_secs(10)),
Box::new(|_, _| {
async {
Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
})
}
.boxed()
}),
)
.await?;
let result = client
.call_tool(
"echo".to_string(),
Some(json!({
"message": "legacy environment",
"env_var": "AKODE_MCP_PROTOCOL_VERSION",
})),
|_| Ok(None),
Some(Duration::from_secs(10)),
)
.await?;
assert_eq!(
result.structured_content,
Some(json!({
"echo": "ECHOING: legacy environment",
"env": version,
}))
);
client.shutdown().await;
}
}
Ok(())
}

View File

@@ -0,0 +1,291 @@
mod streamable_http_test_support;
use std::convert::Infallible;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::time::Duration;
use anyhow::Context as _;
use axum::Json;
use axum::Router;
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::response::sse::Event;
use axum::response::sse::Sse;
use axum::routing::post;
use akode_api::AuthError;
use akode_api::AuthProvider;
use akode_api::SharedAuthProvider;
use akode_config::types::AuthKeyringBackendKind;
use akode_config::types::OAuthCredentialsStoreMode;
use akode_exec_server::Environment;
use akode_rmcp_client::RmcpClient;
use futures::StreamExt as _;
use futures::stream;
use http::HeaderMap;
use http::HeaderValue;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tokio::net::TcpListener;
use tokio::sync::Notify;
use tokio::sync::mpsc;
use tokio::time::timeout;
use streamable_http_test_support::create_client;
use streamable_http_test_support::initialize_client;
#[derive(Default)]
struct RevocableAuth {
unavailable: AtomicBool,
}
impl AuthProvider for RevocableAuth {
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), AuthError> {
if self.unavailable.load(Ordering::SeqCst) {
return Err(AuthError::Transient(
"authentication unavailable".to_string(),
));
}
headers.insert(
http::header::AUTHORIZATION,
HeaderValue::from_static("Bearer test-bearer"),
);
Ok(())
}
}
struct StreamClosed {
event_name: String,
closed: mpsc::UnboundedSender<String>,
}
impl Drop for StreamClosed {
fn drop(&mut self) {
let _ = self.closed.send(self.event_name.clone());
}
}
fn initialize_response(message: &Value) -> axum::response::Response {
Json(json!({
"jsonrpc": "2.0",
"id": message["id"],
"result": {
"protocolVersion": "2025-06-18",
"capabilities": {},
"serverInfo": {"name": "plugin-runtime", "version": "1.0.0"},
},
}))
.into_response()
}
fn plugin_runtime_notifications(event_name: &str, request_id: Value) -> [Value; 2] {
let metadata = json!({"io.modelcontextprotocol/subscriptionId": request_id});
[
json!({
"jsonrpc": "2.0",
"method": "notifications/events/active",
"params": {"cursor": null, "truncated": false, "_meta": metadata},
}),
json!({
"jsonrpc": "2.0",
"method": "notifications/events/event",
"params": {
"eventId": format!("event-{event_name}"),
"name": event_name,
"timestamp": "2026-08-07T12:00:00Z",
"data": {"issue": 42},
"cursor": null,
"_meta": metadata,
},
}),
]
}
#[tokio::test]
async fn plugin_runtime_event_streams_are_isolated_and_cancel_locally() -> anyhow::Result<()> {
let (stream_closed_tx, mut stream_closed_rx) = mpsc::unbounded_channel::<String>();
let router = Router::new().route(
"/mcp",
post(move |Json(message): Json<Value>| {
let stream_closed_tx = stream_closed_tx.clone();
async move {
match message["method"].as_str() {
Some("initialize") => initialize_response(&message),
Some("notifications/initialized") => StatusCode::ACCEPTED.into_response(),
Some("events/stream") => {
let event_name = message["params"]["name"]
.as_str()
.expect("event stream request must contain a name")
.to_string();
assert_eq!(
message.pointer("/params/arguments"),
Some(&json!({"project": "codex"}))
);
assert!(message["params"].get("cursor").is_none());
let closed = StreamClosed {
event_name: event_name.clone(),
closed: stream_closed_tx,
};
let events = stream::iter(
plugin_runtime_notifications(&event_name, message["id"].clone())
.into_iter()
.map(|notification| {
Ok::<_, Infallible>(
Event::default()
.event("message")
.data(notification.to_string()),
)
}),
)
.chain(stream::pending())
.map(move |event| {
let _ = &closed;
event
});
Sse::new(events).into_response()
}
Some("notifications/cancelled") => {
panic!("event cancellation should close the local stream without a POST")
}
method => panic!("unexpected Plugin Runtime request: {method:?}"),
}
}
}),
);
let listener = TcpListener::bind("127.0.0.1:0").await?;
let base_url = format!("http://{}", listener.local_addr()?);
let server = tokio::spawn(async move { axum::serve(listener, router).await });
let auth = Arc::new(RevocableAuth::default());
let request_auth: SharedAuthProvider = auth.clone();
let client = RmcpClient::new_streamable_http_client(
"test-streamable-http",
&format!("{base_url}/mcp"),
/*bearer_token*/ None,
/*http_headers*/ None,
/*env_http_headers*/ None,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
Environment::default_for_tests().get_http_client(),
Some(Arc::new(request_auth)),
)
.await?;
initialize_client(&client).await?;
let mut first = client
.send_event_stream_request(Some(json!({
"name": "github.pull_request.opened",
"arguments": {"project": "codex"},
})))
.await?;
let mut second = client
.send_event_stream_request(Some(json!({
"name": "gmail.message.received",
"arguments": {"project": "codex"},
})))
.await?;
for (event_name, request) in [
("github.pull_request.opened", &mut first),
("gmail.message.received", &mut second),
] {
let active = timeout(Duration::from_secs(5), request.notifications.recv())
.await?
.context("event stream closed before activation")?;
assert_eq!(active.method, "notifications/events/active");
assert_eq!(
active.params,
Some(json!({"cursor": null, "truncated": false}))
);
let event = timeout(Duration::from_secs(5), request.notifications.recv())
.await?
.context("event stream closed before delivery")?;
assert_eq!(event.method, "notifications/events/event");
assert_eq!(
event.params.as_ref().and_then(|params| params.get("name")),
Some(&json!(event_name))
);
}
first
.handle
.cancel(Some("event subscription closed".to_string()))
.await?;
let closed = timeout(Duration::from_secs(5), stream_closed_rx.recv())
.await?
.context("cancelled stream did not close")?;
assert_eq!(closed, "github.pull_request.opened");
// Local cleanup must still work if authentication fails after the stream starts.
auth.unavailable.store(true, Ordering::SeqCst);
second
.handle
.cancel(Some("event subscription closed".to_string()))
.await?;
let closed = timeout(Duration::from_secs(5), stream_closed_rx.recv())
.await?
.context("cancelled stream did not close")?;
assert_eq!(closed, "gmail.message.received");
client.shutdown().await;
server.abort();
let _ = server.await;
Ok(())
}
#[tokio::test]
async fn plugin_runtime_event_stream_times_out_before_stalled_headers() -> anyhow::Result<()> {
let request_started = std::sync::Arc::new(Notify::new());
let server_request_started = std::sync::Arc::clone(&request_started);
let router = Router::new().route(
"/mcp",
post(move |Json(message): Json<Value>| {
let request_started = std::sync::Arc::clone(&server_request_started);
async move {
match message["method"].as_str() {
Some("initialize") => initialize_response(&message),
Some("notifications/initialized") => StatusCode::ACCEPTED.into_response(),
Some("events/stream") => {
request_started.notify_one();
std::future::pending().await
}
method => panic!("unexpected Plugin Runtime request: {method:?}"),
}
}
}),
);
let listener = TcpListener::bind("127.0.0.1:0").await?;
let base_url = format!("http://{}", listener.local_addr()?);
let server = tokio::spawn(async move { axum::serve(listener, router).await });
let client = create_client(&base_url).await?;
let request = client
.send_event_stream_request(Some(json!({
"name": "github.pull_request.opened",
"arguments": {},
})))
.await?;
timeout(Duration::from_secs(5), request_started.notified())
.await
.context("event stream request did not reach the server")?;
tokio::time::pause();
tokio::time::advance(Duration::from_secs(31)).await;
let error = request
.handle
.rx
.await?
.expect_err("stalled response headers must time out");
tokio::time::resume();
assert!(error.to_string().contains("timed out"));
client.shutdown().await;
server.abort();
let _ = server.await;
Ok(())
}

View File

@@ -0,0 +1,180 @@
#![cfg(unix)]
use std::collections::HashMap;
use std::ffi::OsString;
use std::fs;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use akode_rmcp_client::ElicitationAction;
use akode_rmcp_client::ElicitationResponse;
use akode_rmcp_client::LocalStdioServerLauncher;
use akode_rmcp_client::RmcpClient;
use futures::FutureExt as _;
use rmcp::model::ClientCapabilities;
use rmcp::model::Implementation;
use rmcp::model::InitializeRequestParams;
use rmcp::model::ProtocolVersion;
use serde_json::json;
fn stdio_server_bin() -> Result<std::path::PathBuf> {
akode_utils_cargo_bin::cargo_bin("test_stdio_server").map_err(Into::into)
}
fn init_params() -> InitializeRequestParams {
InitializeRequestParams::new(
ClientCapabilities::default(),
Implementation::new("codex-test", "0.0.0-test").with_title("Codex rmcp shutdown test"),
)
.with_protocol_version(ProtocolVersion::V_2025_06_18)
}
fn process_exists(pid: u32) -> bool {
std::process::Command::new("kill")
.arg("-0")
.arg(pid.to_string())
.stderr(std::process::Stdio::null())
.status()
.map(|status| status.success())
.unwrap_or(false)
}
async fn wait_for_pid_file(path: &Path) -> Result<u32> {
for _ in 0..50 {
match fs::read_to_string(path) {
Ok(content) => {
let trimmed = content.trim();
if trimmed.is_empty() {
tokio::time::sleep(Duration::from_millis(100)).await;
continue;
}
let pid = trimmed
.parse::<u32>()
.with_context(|| format!("failed to parse pid from {}", path.display()))?;
return Ok(pid);
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
tokio::time::sleep(Duration::from_millis(100)).await;
}
Err(error) => {
return Err(error).with_context(|| format!("failed to read {}", path.display()));
}
}
}
anyhow::bail!("timed out waiting for child pid file at {}", path.display());
}
async fn wait_for_process_exit(pid: u32) -> Result<()> {
for _ in 0..50 {
if !process_exists(pid) {
return Ok(());
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
anyhow::bail!("process {pid} still running after timeout");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn drop_kills_wrapper_process_group() -> Result<()> {
let temp_dir = tempfile::tempdir()?;
let child_pid_file = temp_dir.path().join("child.pid");
let child_pid_file_str = child_pid_file.to_string_lossy().into_owned();
let wrapper = temp_dir.path().join("wrapper");
akode_utils_cargo_bin::write_executable(
&wrapper,
"#!/bin/sh\nsleep 300 & child_pid=$!; echo \"$child_pid\" > \"$CHILD_PID_FILE\"; cat >/dev/null\n",
)?;
let client = RmcpClient::new_stdio_client(
OsString::from("./wrapper"),
vec![],
Some(HashMap::from([(
OsString::from("CHILD_PID_FILE"),
OsString::from(child_pid_file_str),
)])),
&[],
Some(temp_dir.path().to_string_lossy().into_owned()),
Arc::new(LocalStdioServerLauncher::new(std::env::current_dir()?)),
)
.await?;
let grandchild_pid = wait_for_pid_file(&child_pid_file).await?;
assert!(
process_exists(grandchild_pid),
"expected grandchild process {grandchild_pid} to be running before dropping client"
);
drop(client);
wait_for_process_exit(grandchild_pid).await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shutdown_kills_initialized_stdio_server_with_in_flight_operation() -> Result<()> {
let temp_dir = tempfile::tempdir()?;
let server_pid_file = temp_dir.path().join("server.pid");
let server_pid_file_str = server_pid_file.to_string_lossy().into_owned();
let client = Arc::new(
RmcpClient::new_stdio_client(
stdio_server_bin()?.into(),
Vec::<OsString>::new(),
Some(HashMap::from([(
OsString::from("MCP_TEST_PID_FILE"),
OsString::from(server_pid_file_str),
)])),
&[],
/*cwd*/ None,
Arc::new(LocalStdioServerLauncher::new(std::env::current_dir()?)),
)
.await?,
);
client
.initialize(
init_params(),
Some(Duration::from_secs(5)),
Box::new(|_, _| {
async {
Ok(ElicitationResponse {
action: ElicitationAction::Accept,
content: Some(json!({})),
meta: None,
})
}
.boxed()
}),
)
.await?;
let server_pid = wait_for_pid_file(&server_pid_file).await?;
assert!(
process_exists(server_pid),
"expected MCP server process {server_pid} to be running before shutdown"
);
let call_client = Arc::clone(&client);
let call_task = tokio::spawn(async move {
call_client
.call_tool(
"sync".to_string(),
Some(json!({ "sleep_after_ms": 300_000 })),
|_| Ok(None),
Some(Duration::from_secs(300)),
)
.await
});
tokio::time::sleep(Duration::from_millis(200)).await;
client.shutdown().await;
wait_for_process_exit(server_pid).await?;
let _ = tokio::time::timeout(Duration::from_secs(5), call_task).await?;
Ok(())
}

View File

@@ -0,0 +1,144 @@
use std::ffi::OsString;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use akode_rmcp_client::ElicitationAction;
use akode_rmcp_client::ElicitationResponse;
use akode_rmcp_client::LocalStdioServerLauncher;
use akode_rmcp_client::RmcpClient;
use akode_rmcp_client::mcp_error;
use akode_utils_cargo_bin::CargoBinError;
use futures::FutureExt as _;
use pretty_assertions::assert_eq;
use rmcp::model::ClientCapabilities;
use rmcp::model::ElicitationCapability;
use rmcp::model::FormElicitationCapability;
use rmcp::model::Implementation;
use rmcp::model::InitializeRequestParams;
use rmcp::model::ListResourceTemplatesResult;
use rmcp::model::ProtocolVersion;
use rmcp::model::ReadResourceRequestParams;
use rmcp::model::ResourceContents;
use serde_json::json;
const RESOURCE_URI: &str = "memo://codex/example-note";
fn stdio_server_bin() -> Result<PathBuf, CargoBinError> {
akode_utils_cargo_bin::cargo_bin("test_stdio_server")
}
fn init_params() -> InitializeRequestParams {
let mut capabilities = ClientCapabilities::default();
capabilities.elicitation =
Some(ElicitationCapability::new().with_form(FormElicitationCapability::new()));
InitializeRequestParams::new(
capabilities,
Implementation::new("codex-test", "0.0.0-test").with_title("Codex rmcp resource test"),
)
.with_protocol_version(ProtocolVersion::V_2025_06_18)
}
async fn resource_client() -> anyhow::Result<RmcpClient> {
let client = RmcpClient::new_stdio_client(
stdio_server_bin()?.into(),
Vec::<OsString>::new(),
/*env*/ None,
&[],
/*cwd*/ None,
Arc::new(LocalStdioServerLauncher::new(std::env::current_dir()?)),
)
.await?;
client
.initialize(
init_params(),
Some(Duration::from_secs(5)),
Box::new(|_, _| {
async {
Ok(ElicitationResponse {
action: ElicitationAction::Accept,
content: Some(json!({})),
meta: None,
})
}
.boxed()
}),
)
.await?;
Ok(client)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn rmcp_client_can_list_and_read_resources() -> anyhow::Result<()> {
let client = resource_client().await?;
let list = client
.list_resources(/*params*/ None, Some(Duration::from_secs(5)))
.await?;
let memo = list
.resources
.iter()
.find(|resource| resource.uri == RESOURCE_URI)
.expect("memo resource present");
assert_eq!(
memo,
&rmcp::model::Resource::new(RESOURCE_URI, "example-note")
.with_title("Example Note")
.with_description("A sample MCP resource exposed for integration tests.")
.with_mime_type("text/plain")
);
let templates = client
.list_resource_templates(/*params*/ None, Some(Duration::from_secs(5)))
.await?;
let mut expected_templates = ListResourceTemplatesResult::with_all_items(vec![
rmcp::model::ResourceTemplate::new("memo://codex/{slug}", "codex-memo")
.with_title("Codex Memo")
.with_description("Template for memo://codex/{slug} resources used in tests.")
.with_mime_type("text/plain"),
]);
expected_templates.result_type = None;
assert_eq!(templates, expected_templates);
let read = client
.read_resource(
ReadResourceRequestParams::new(RESOURCE_URI),
Some(Duration::from_secs(5)),
)
.await?;
let text = read.contents.first().expect("resource contents present");
assert_eq!(
text,
&ResourceContents::TextResourceContents {
uri: RESOURCE_URI.to_string(),
mime_type: Some("text/plain".to_string()),
text: "This is a sample MCP resource served by the rmcp test server.".to_string(),
meta: None,
}
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn rmcp_client_preserves_each_resource_error() -> anyhow::Result<()> {
let client = resource_client().await?;
for uri in ["memo://codex/missing-first", "memo://codex/missing-second"] {
let error = client
.read_resource(
ReadResourceRequestParams::new(uri),
Some(Duration::from_secs(5)),
)
.await
.expect_err("missing resource must return a protocol error")
.context("resources/read failed");
assert_eq!(
mcp_error(&error),
Some(&rmcp::ErrorData::resource_not_found(
"resource_not_found",
Some(json!({ "uri": uri })),
))
);
}
Ok(())
}

View File

@@ -0,0 +1,189 @@
//! Unix local MCP servers and their descendants must not inherit unrelated
//! parent descriptors, while their explicit stdio transport remains usable.
#![cfg(unix)]
use std::ffi::OsString;
use std::fs;
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
use std::os::fd::OwnedFd;
use std::os::unix::fs::symlink;
use std::process::Command;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use akode_rmcp_client::ElicitationAction;
use akode_rmcp_client::ElicitationResponse;
use akode_rmcp_client::LocalStdioServerLauncher;
use akode_rmcp_client::RmcpClient;
use futures::FutureExt as _;
use pretty_assertions::assert_eq;
use rmcp::model::ClientCapabilities;
use rmcp::model::Implementation;
use rmcp::model::InitializeRequestParams;
use rmcp::model::ProtocolVersion;
use serde_json::json;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn local_stdio_excludes_inheritable_fds_from_server_and_descendant() -> Result<()> {
let temporary = tempfile::tempdir()?;
let script = temporary.path().join("server.py");
fs::write(
&script,
r#"import errno, json, os, signal, subprocess, sys
signal.alarm(30)
sentinel = int(sys.argv[2])
def probe():
for fd in (0, 1, 2):
os.fstat(fd)
print("descriptor fixture stderr", file=sys.stderr, flush=True)
try:
os.fstat(sentinel)
return True
except OSError as error:
if error.errno != errno.EBADF:
raise
return False
if sys.argv[1] == "probe":
print(json.dumps(probe()), flush=True)
sys.exit(0)
for line in sys.stdin:
message = json.loads(line)
method = message.get("method")
if method == "initialize":
result = {"protocolVersion": "2025-06-18", "capabilities": {"tools": {}}, "serverInfo": {"name": "descriptor-fixture", "version": "1"}}
elif method == "tools/call":
# Python normally closes extra descriptors itself. Disable that cleanup
# so the descendant actually exercises the MCP launch boundary.
child = subprocess.run([sys.executable, __file__, "probe", sys.argv[2]], close_fds=False, capture_output=True, text=True, check=True, timeout=5)
result = {"content": [], "structuredContent": {
"server": probe(), "descendant": json.loads(child.stdout),
"descendantStderr": child.stderr}}
else:
continue
print(json.dumps({"jsonrpc": "2.0", "id": message["id"], "result": result}), flush=True)
"#,
)?;
let file = tempfile::tempfile()?;
// F_DUPFD reserves an unused inheritable descriptor without overwriting
// a descriptor owned by the test runner/runtime.
let raw = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_DUPFD, 200) };
if raw < 0 {
return Err(std::io::Error::last_os_error().into());
}
// SAFETY: fcntl returned a new descriptor owned only by this test.
let sentinel = unsafe { OwnedFd::from_raw_fd(raw) };
let sentinel_arg = raw.to_string();
let python = which::which("python3")?;
// Qualify the oracle: the same executable must see the sentinel when
// spawned without the local MCP descriptor policy.
let control = Command::new(&python)
.arg(&script)
.arg("probe")
.arg(&sentinel_arg)
.output()?;
assert!(control.status.success());
assert!(serde_json::from_slice::<bool>(&control.stdout)?);
symlink(&python, temporary.path().join("python-fixture"))?;
let wrapper = temporary.path().join("executable-text");
// No shebang: exercise Command's shell fallback after native macOS spawn
// returns ENOEXEC, including the fallback descriptor cleanup.
akode_utils_cargo_bin::write_executable(&wrapper, "exec \"$@\"\n")?;
for (launch, program, mut args) in [
("absolute", python.clone().into_os_string(), Vec::new()),
("relative", OsString::from("./python-fixture"), Vec::new()),
(
"shell fallback",
OsString::from("./executable-text"),
vec![python.clone().into_os_string()],
),
] {
args.extend([
script.clone().into_os_string(),
"server".into(),
sentinel_arg.clone().into(),
]);
let client = RmcpClient::new_stdio_client(
program,
args,
/*env*/ None,
&[],
Some(temporary.path().to_string_lossy().into_owned()),
Arc::new(LocalStdioServerLauncher::new(std::env::current_dir()?)),
)
.await?;
client
.initialize(
InitializeRequestParams::new(
ClientCapabilities::default(),
Implementation::new("descriptor-boundary-test", "1"),
)
.with_protocol_version(ProtocolVersion::V_2025_06_18),
Some(Duration::from_secs(/*secs*/ 5)),
Box::new(|_, _| {
async {
Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
})
}
.boxed()
}),
)
.await?;
let result = client
.call_tool(
"probe".to_string(),
/*arguments*/ None,
|_| Ok(None),
Some(Duration::from_secs(/*secs*/ 5)),
)
.await?;
client.shutdown().await;
assert_eq!(
result.structured_content,
Some(json!({
"server": false,
"descendant": false,
"descendantStderr": "descriptor fixture stderr\n"
})),
"{launch} launch"
);
}
// Cleanup must not close or change the parent's descriptor.
assert_eq!(
unsafe { libc::fcntl(sentinel.as_raw_fd(), libc::F_GETFD) },
0
);
Ok(())
}
#[tokio::test]
async fn local_stdio_preserves_exec_failure_reporting() -> Result<()> {
let temporary = tempfile::tempdir()?;
let script = temporary.path().join("missing-interpreter");
let interpreter = temporary.path().join("does-not-exist");
akode_utils_cargo_bin::write_executable(&script, &format!("#!{}\n", interpreter.display()))?;
// Program resolution succeeds, but exec fails. Descriptor cleanup must
// preserve the internal error pipe so launch reports the failure directly.
let result = RmcpClient::new_stdio_client(
script.into_os_string(),
Vec::new(),
/*env*/ None,
&[],
/*cwd*/ None,
Arc::new(LocalStdioServerLauncher::new(std::env::current_dir()?)),
)
.await;
assert!(
result.is_err(),
"exec failure was reported as a successful launch"
);
Ok(())
}

View File

@@ -0,0 +1,310 @@
use std::collections::HashMap;
use std::ffi::OsString;
#[cfg(windows)]
use std::os::windows::io::AsRawHandle;
#[cfg(windows)]
use std::os::windows::io::FromRawHandle;
#[cfg(windows)]
use std::os::windows::io::OwnedHandle;
use std::sync::Arc;
use std::time::Duration;
use akode_exec_server::Environment;
use akode_rmcp_client::ElicitationAction;
use akode_rmcp_client::ElicitationResponse;
use akode_rmcp_client::ExecutorStdioServerLauncher;
use akode_rmcp_client::LocalStdioServerLauncher;
use akode_rmcp_client::McpProtocolMode;
use akode_rmcp_client::RmcpClient;
use akode_rmcp_client::StdioServerLauncher;
use futures::FutureExt;
use rmcp::model::ClientCapabilities;
use rmcp::model::Implementation;
use rmcp::model::InitializeRequestParams;
use rmcp::model::ProtocolVersion;
#[cfg(windows)]
#[link(name = "kernel32")]
unsafe extern "system" {
fn OpenProcess(
desired_access: u32,
inherit_handle: i32,
process_id: u32,
) -> *mut std::ffi::c_void;
fn TerminateProcess(handle: *mut std::ffi::c_void, exit_code: u32) -> i32;
fn WaitForSingleObject(handle: *mut std::ffi::c_void, milliseconds: u32) -> u32;
}
#[cfg(windows)]
fn open_process_for_wait(process_id: u32) -> std::io::Result<OwnedHandle> {
let handle = unsafe {
OpenProcess(
/*desired_access*/ 0x0010_0001,
/*inherit_handle*/ 0,
process_id,
)
};
if handle.is_null() {
return Err(std::io::Error::last_os_error());
}
Ok(unsafe { OwnedHandle::from_raw_handle(handle.cast()) })
}
#[cfg(windows)]
fn wait_for_process_exit(process: &OwnedHandle) -> std::io::Result<()> {
match unsafe {
WaitForSingleObject(process.as_raw_handle().cast(), /*milliseconds*/ 5_000)
} {
0 => Ok(()),
u32::MAX => Err(std::io::Error::last_os_error()),
_ => Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"process did not exit",
)),
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn stdio_message_limits_preserve_legacy_local_compatibility() -> anyhow::Result<()> {
let server = akode_utils_cargo_bin::cargo_bin("test_stdio_server")?;
for (executor, protocol_mode, accepts_oversized) in [
(false, McpProtocolMode::Legacy, true),
(false, McpProtocolMode::V20260728, false),
(true, McpProtocolMode::Legacy, false),
] {
let launcher: Arc<dyn StdioServerLauncher> = if executor {
Arc::new(ExecutorStdioServerLauncher::new(
Environment::default_for_tests().get_exec_backend(),
))
} else {
Arc::new(LocalStdioServerLauncher::new(std::env::current_dir()?))
};
let mut env = HashMap::from([(
OsString::from("MCP_TEST_OVERSIZED_TOOL_DESCRIPTION"),
OsString::from("1"),
)]);
if protocol_mode == McpProtocolMode::V20260728 {
env.insert(
OsString::from("AKODE_MCP_PROTOCOL_VERSION"),
OsString::from("2026-07-28"),
);
}
let client = RmcpClient::new_stdio_client_with_protocol_mode(
server.clone().into(),
Vec::new(),
Some(env),
&[],
Some(std::env::current_dir()?.to_string_lossy().into_owned()),
launcher,
protocol_mode,
)
.await?;
client
.initialize(
InitializeRequestParams::new(
ClientCapabilities::default(),
Implementation::new("stdio-limit-test", "1.0.0"),
)
.with_protocol_version(ProtocolVersion::V_2025_06_18),
Some(Duration::from_secs(10)),
Box::new(|_, _| {
async {
Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
})
}
.boxed()
}),
)
.await?;
let result = client
.list_tools(/*params*/ None, Some(Duration::from_secs(10)))
.await;
assert_eq!(
result.is_ok(),
accepts_oversized,
"unexpected stdio size handling (executor={executor}, mode={protocol_mode:?})"
);
client.shutdown().await;
}
Ok(())
}
#[cfg(windows)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn local_stdio_initializes_without_a_console_directly_and_through_cmd() -> anyhow::Result<()>
{
let server = akode_utils_cargo_bin::cargo_bin("test_stdio_server")?;
let temp_dir = tempfile::tempdir()?;
let console_state_file = temp_dir.path().join("console-state");
let server_pid_file = temp_dir.path().join("server.pid");
std::fs::write(
temp_dir.path().join("launch.cmd"),
"@echo off\r\n\"%MCP_TEST_SERVER_BINARY%\"\r\n",
)?;
let env = HashMap::from([
(
OsString::from("MCP_TEST_CONSOLE_STATE_FILE"),
console_state_file.clone().into_os_string(),
),
(
OsString::from("MCP_TEST_PID_FILE"),
server_pid_file.clone().into_os_string(),
),
(
OsString::from("MCP_TEST_SERVER_BINARY"),
server.clone().into(),
),
]);
for (program, args) in [
(server.into(), Vec::new()),
(
OsString::from("cmd.exe"),
["/d", "/s", "/c", "call", ".\\launch.cmd"]
.map(OsString::from)
.to_vec(),
),
] {
let client = RmcpClient::new_stdio_client(
program,
args,
Some(env.clone()),
&[],
Some(temp_dir.path().to_string_lossy().into_owned()),
Arc::new(LocalStdioServerLauncher::new(temp_dir.path().to_path_buf())),
)
.await?;
client
.initialize(
InitializeRequestParams::new(
ClientCapabilities::default(),
Implementation::new("stdio-console-test", "1.0.0"),
)
.with_protocol_version(ProtocolVersion::V_2025_06_18),
Some(Duration::from_secs(10)),
Box::new(|_, _| {
async {
Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
})
}
.boxed()
}),
)
.await?;
let console_state = std::fs::read_to_string(&console_state_file)?;
let server_pid = std::fs::read_to_string(&server_pid_file)?
.trim()
.parse::<u32>()?;
let server_process = open_process_for_wait(server_pid)?;
let tools = client
.list_tools(/*params*/ None, Some(Duration::from_secs(10)))
.await;
client.shutdown().await;
wait_for_process_exit(&server_process)?;
pretty_assertions::assert_eq!(console_state, "false");
assert!(!tools?.tools.is_empty());
std::fs::remove_file(&console_state_file)?;
std::fs::remove_file(&server_pid_file)?;
}
Ok(())
}
#[cfg(windows)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn local_stdio_shutdown_terminates_descendants_after_server_exit() -> anyhow::Result<()> {
let server = akode_utils_cargo_bin::cargo_bin("test_stdio_server")?;
for protocol_mode in [McpProtocolMode::Legacy, McpProtocolMode::V20260728] {
let temp_dir = tempfile::tempdir()?;
let server_pid_file = temp_dir.path().join("server.pid");
let descendant_pid_file = temp_dir.path().join("descendant.pid");
let breakaway_denied_file = temp_dir.path().join("breakaway.denied");
let mut env = HashMap::from([
(
OsString::from("MCP_TEST_PID_FILE"),
server_pid_file.clone().into(),
),
(
OsString::from("MCP_TEST_DESCENDANT_PID_FILE"),
descendant_pid_file.clone().into(),
),
(
OsString::from("MCP_TEST_BREAKAWAY_DENIED_FILE"),
breakaway_denied_file.clone().into(),
),
]);
if protocol_mode == McpProtocolMode::V20260728 {
env.insert(
OsString::from("AKODE_MCP_PROTOCOL_VERSION"),
OsString::from("2026-07-28"),
);
}
let client = RmcpClient::new_stdio_client_with_protocol_mode(
server.clone().into(),
Vec::new(),
Some(env),
&[],
Some(std::env::current_dir()?.to_string_lossy().into_owned()),
Arc::new(LocalStdioServerLauncher::new(std::env::current_dir()?)),
protocol_mode,
)
.await?;
client
.initialize(
InitializeRequestParams::new(
ClientCapabilities::default(),
Implementation::new("stdio-cleanup-test", "1.0.0"),
)
.with_protocol_version(ProtocolVersion::V_2025_06_18),
Some(Duration::from_secs(10)),
Box::new(|_, _| {
async {
Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
})
}
.boxed()
}),
)
.await?;
assert_eq!(
std::fs::read_to_string(breakaway_denied_file)?,
"denied",
"MCP descendant escaped its Windows job (mode={protocol_mode:?})"
);
let server_pid = std::fs::read_to_string(server_pid_file)?
.trim()
.parse::<u32>()?;
let descendant_pid = std::fs::read_to_string(descendant_pid_file)?
.trim()
.parse::<u32>()?;
let server_process = open_process_for_wait(server_pid)?;
let descendant_process = open_process_for_wait(descendant_pid)?;
let terminated = unsafe {
TerminateProcess(server_process.as_raw_handle().cast(), /*exit_code*/ 0)
};
assert_ne!(terminated, 0, "failed to terminate test MCP server");
wait_for_process_exit(&server_process)?;
client.shutdown().await;
assert!(
wait_for_process_exit(&descendant_process).is_ok(),
"MCP descendant survived its exited server (mode={protocol_mode:?})"
);
}
Ok(())
}

View File

@@ -0,0 +1,222 @@
//! The local stderr reader must close when its MCP transport ends, even when
//! a descendant outside the server process group still has stderr open.
#![cfg(unix)]
use std::fs;
use std::io::Write;
use std::path::Path;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use anyhow::Result;
use akode_rmcp_client::ElicitationAction;
use akode_rmcp_client::ElicitationResponse;
use akode_rmcp_client::LocalStdioServerLauncher;
use akode_rmcp_client::RmcpClient;
use futures::FutureExt as _;
use pretty_assertions::assert_eq;
use rmcp::model::ClientCapabilities;
use rmcp::model::Implementation;
use rmcp::model::InitializeRequestParams;
use rmcp::model::ProtocolVersion;
struct EscapedChild(i32);
enum Cleanup {
Shutdown,
Drop,
}
#[derive(Clone)]
struct TestLogWriter(Arc<Mutex<Vec<u8>>>);
impl Write for TestLogWriter {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0
.lock()
.map_err(|_| std::io::Error::other("log buffer lock"))?
.extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl Drop for EscapedChild {
fn drop(&mut self) {
// Only this test's PID, written after setsid(), is eligible for cleanup.
// The fixture also exits independently after 30 seconds.
unsafe { libc::kill(self.0, libc::SIGKILL) };
}
}
fn fd_count() -> Result<usize> {
let directory = if cfg!(target_os = "linux") {
"/proc/self/fd"
} else {
"/dev/fd"
};
Ok(fs::read_dir(directory)?.count())
}
fn read_pid(path: &Path) -> Result<i32> {
let pid = fs::read_to_string(path)?.trim().parse::<i32>()?;
anyhow::ensure!(pid > 1, "invalid fixture PID in {}", path.display());
Ok(pid)
}
#[tokio::test(flavor = "current_thread")]
async fn client_teardown_closes_stderr_fd_and_logs_queued_diagnostics() -> Result<()> {
let logs = Arc::new(Mutex::new(Vec::new()));
let writer_logs = Arc::clone(&logs);
// The reader task runs on this thread, so its logs use this subscriber.
let _subscriber_guard = tracing::subscriber::set_default(
tracing_subscriber::fmt()
.with_ansi(false)
.with_max_level(tracing::Level::INFO)
.with_writer(move || TestLogWriter(Arc::clone(&writer_logs)))
.finish(),
);
// FD counts are process-wide, so run the two teardown paths sequentially.
assert_stderr_reader_closed(Cleanup::Shutdown, &logs).await?;
assert_stderr_reader_closed(Cleanup::Drop, &logs).await
}
async fn assert_stderr_reader_closed(cleanup: Cleanup, logs: &Arc<Mutex<Vec<u8>>>) -> Result<()> {
let temporary = tempfile::tempdir()?;
let server_pid_file = temporary.path().join("server.pid");
let child_pid_file = temporary.path().join("escaped.pid");
let trigger_file = temporary.path().join("emit-stderr");
let written_file = temporary.path().join("stderr-written");
let diagnostic = match &cleanup {
Cleanup::Shutdown => "queued diagnostic before shutdown",
Cleanup::Drop => "queued diagnostic before drop",
};
let script = temporary.path().join("server.py");
fs::write(
&script,
r#"import json, os, pathlib, signal, sys, threading, time
# Keep either process bounded if test cleanup fails.
MAX_FIXTURE_LIFETIME_SECONDS = 30
server_pid_path = pathlib.Path(sys.argv[1])
escaped_pid_path = pathlib.Path(sys.argv[2])
trigger_path = pathlib.Path(sys.argv[3])
written_path = pathlib.Path(sys.argv[4])
signal.alarm(MAX_FIXTURE_LIFETIME_SECONDS)
server_pid_path.write_text(str(os.getpid()))
ready_reader, ready_writer = os.pipe()
if os.fork() == 0: # fork() returns zero in the child.
os.close(ready_reader)
os.setsid()
signal.alarm(MAX_FIXTURE_LIFETIME_SECONDS)
os.close(sys.stdin.fileno())
os.close(sys.stdout.fileno())
escaped_pid_path.write_text(str(os.getpid()))
os.write(ready_writer, b"1")
os.close(ready_writer)
# Exit even if SIGALRM was ignored; the test normally kills this child sooner.
time.sleep(MAX_FIXTURE_LIFETIME_SECONDS)
os._exit(os.EX_OK)
os.close(ready_writer)
with os.fdopen(ready_reader, "rb") as ready:
assert ready.read(1) == b"1"
def emit_diagnostic():
while not trigger_path.exists():
time.sleep(0.01)
print(sys.argv[5], file=sys.stderr, flush=True)
written_path.write_text("written")
threading.Thread(target=emit_diagnostic, daemon=True).start()
for line in sys.stdin:
message = json.loads(line)
if message.get("method") == "initialize":
result = {"protocolVersion": "2025-06-18", "capabilities": {}, "serverInfo": {"name": "stderr-reader-fixture", "version": "1"}}
print(json.dumps({"jsonrpc": "2.0", "id": message["id"], "result": result}), flush=True)
"#,
)?;
let baseline = fd_count()?;
let client = RmcpClient::new_stdio_client(
which::which("python3")?.into(),
vec![
script.into_os_string(),
server_pid_file.clone().into_os_string(),
child_pid_file.clone().into_os_string(),
trigger_file.clone().into_os_string(),
written_file.clone().into_os_string(),
diagnostic.into(),
],
/*env*/ None,
&[],
/*cwd*/ None,
Arc::new(LocalStdioServerLauncher::new(std::env::current_dir()?)),
)
.await?;
client
.initialize(
InitializeRequestParams::new(
ClientCapabilities::default(),
Implementation::new("stderr-reader-test", "1"),
)
.with_protocol_version(ProtocolVersion::V_2025_06_18),
Some(Duration::from_secs(5)),
Box::new(|_, _| {
async {
Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
})
}
.boxed()
}),
)
.await?;
let server_pid = read_pid(&server_pid_file)?;
let escaped = EscapedChild(read_pid(&child_pid_file)?);
assert_eq!(unsafe { libc::getpgid(server_pid) }, server_pid);
assert_eq!(unsafe { libc::getpgid(escaped.0) }, escaped.0);
// Keep the current-thread Tokio runtime blocked until the server has
// written stderr. The reader cannot run before teardown starts.
fs::write(&trigger_file, "")?;
for _ in 0..250 {
if written_file.exists() {
break;
}
std::thread::sleep(Duration::from_millis(20));
}
assert!(written_file.exists(), "fixture did not write stderr");
// For Shutdown, keep the client alive until after the FD assertion so
// final Drop cannot hide missing cleanup in the explicit shutdown path.
if matches!(cleanup, Cleanup::Shutdown) {
client.shutdown().await;
} else {
drop(client);
}
let mut after_shutdown = fd_count()?;
for _ in 0..250 {
if after_shutdown == baseline {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
after_shutdown = fd_count()?;
}
assert_eq!(
after_shutdown, baseline,
"stderr reader still owns a file descriptor while the escaped child is alive"
);
assert_eq!(unsafe { libc::kill(escaped.0, 0) }, 0);
let captured_logs = String::from_utf8(
logs.lock()
.map_err(|_| anyhow::anyhow!("log buffer lock"))?
.clone(),
)?;
assert!(
captured_logs.contains(diagnostic),
"stderr diagnostic written before teardown was lost: {captured_logs}"
);
drop(escaped);
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,376 @@
mod streamable_http_test_support;
use std::any::Any;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::PoisonError;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use akode_config::types::AuthKeyringBackendKind;
use akode_config::types::OAuthCredentialsStoreMode;
use akode_exec_server::Environment;
use akode_exec_server::ExecServerError;
use akode_exec_server::HttpClient;
use akode_exec_server::HttpRedirectPolicy;
use akode_exec_server::HttpRequestParams;
use akode_exec_server::HttpRequestResponse;
use akode_exec_server::HttpResponseBodyStream;
use akode_rmcp_client::McpProtocolMode;
use akode_rmcp_client::RmcpClient;
use akode_rmcp_client::StoredOAuthTokens;
use akode_rmcp_client::StreamableHttpBearerToken;
use akode_rmcp_client::StreamableHttpRedirectMode;
use akode_rmcp_client::WrappedOAuthTokenResponse;
use akode_rmcp_client::save_oauth_tokens;
use akode_rmcp_client::stored_oauth_credential_snapshot;
use futures::future::BoxFuture;
use keyring::credential::Credential;
use keyring::credential::CredentialApi;
use keyring::credential::CredentialBuilderApi;
use keyring::credential::CredentialPersistence;
use oauth2::AccessToken;
use oauth2::basic::BasicTokenType;
use pretty_assertions::assert_eq;
use rmcp::transport::auth::OAuthTokenResponse;
use rmcp::transport::auth::VendorExtraTokenFields;
use tempfile::TempDir;
use tokio::process::Command;
use streamable_http_test_support::arm_session_post_failure;
use streamable_http_test_support::call_echo_tool;
use streamable_http_test_support::expected_echo_result;
use streamable_http_test_support::initialize_client;
use streamable_http_test_support::spawn_streamable_http_server;
const SERVER_NAME: &str = "test-streamable-http-oauth-store-pinning";
const CHILD_SERVER_URL_ENV: &str = "MCP_TEST_OAUTH_PINNED_STORE_SERVER_URL";
const KEYRING_ACCESS_TOKEN: &str = "keyring-access-token";
const FILE_ACCESS_TOKEN: &str = "stale-file-access-token";
#[derive(Clone)]
struct RecordingHttpClient {
inner: Arc<dyn HttpClient>,
bearer_tokens: Arc<Mutex<Vec<String>>>,
redirect_policies: Arc<Mutex<Vec<HttpRedirectPolicy>>>,
}
impl RecordingHttpClient {
fn new(inner: Arc<dyn HttpClient>) -> Self {
Self {
inner,
bearer_tokens: Arc::new(Mutex::new(Vec::new())),
redirect_policies: Arc::new(Mutex::new(Vec::new())),
}
}
fn record_request(&self, params: &HttpRequestParams) {
self.redirect_policies
.lock()
.unwrap_or_else(PoisonError::into_inner)
.push(params.redirect_policy);
let Some(header) = params
.headers
.iter()
.find(|header| header.name.eq_ignore_ascii_case("authorization"))
else {
return;
};
self.bearer_tokens
.lock()
.unwrap_or_else(PoisonError::into_inner)
.push(header.value.clone());
}
fn bearer_tokens(&self) -> Vec<String> {
self.bearer_tokens
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone()
}
}
impl HttpClient for RecordingHttpClient {
fn http_request(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
self.record_request(&params);
self.inner.http_request(params)
}
fn http_request_stream(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
self.record_request(&params);
self.inner.http_request_stream(params)
}
}
#[derive(Debug, Default)]
struct TestKeyringState {
secret: Mutex<Option<Vec<u8>>>,
fail_reads: AtomicBool,
}
#[derive(Clone, Debug)]
struct TestCredential {
state: Arc<TestKeyringState>,
}
impl CredentialApi for TestCredential {
fn set_secret(&self, secret: &[u8]) -> keyring::Result<()> {
*self
.state
.secret
.lock()
.unwrap_or_else(PoisonError::into_inner) = Some(secret.to_vec());
Ok(())
}
fn get_secret(&self) -> keyring::Result<Vec<u8>> {
if self.state.fail_reads.load(Ordering::SeqCst) {
return Err(keyring::Error::Invalid(
"simulated keyring read failure".to_string(),
"load".to_string(),
));
}
self.state
.secret
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone()
.ok_or(keyring::Error::NoEntry)
}
fn delete_credential(&self) -> keyring::Result<()> {
self.state
.secret
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take()
.map(|_| ())
.ok_or(keyring::Error::NoEntry)
}
fn as_any(&self) -> &dyn Any {
self
}
}
#[derive(Debug)]
struct TestCredentialBuilder {
state: Arc<TestKeyringState>,
}
impl CredentialBuilderApi for TestCredentialBuilder {
fn build(
&self,
_target: Option<&str>,
_service: &str,
_user: &str,
) -> keyring::Result<Box<Credential>> {
Ok(Box::new(TestCredential {
state: Arc::clone(&self.state),
}))
}
fn as_any(&self) -> &dyn Any {
self
}
fn persistence(&self) -> CredentialPersistence {
CredentialPersistence::ProcessOnly
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn transport_provided_bearer_token_avoids_placeholder_headers_and_redirects()
-> anyhow::Result<()> {
let (_server, base_url) = spawn_streamable_http_server().await?;
let http_client = RecordingHttpClient::new(Environment::default_for_tests().get_http_client());
let client = RmcpClient::new_streamable_http_client_with_protocol_mode_and_redirect_mode(
"transport-provided-bearer-token",
&format!("{base_url}/mcp"),
Some(StreamableHttpBearerToken::ProvidedByHttpClient),
/*http_headers*/ None,
/*env_http_headers*/ None,
/*oauth_config*/ None,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::Direct,
Arc::new(http_client.clone()),
/*auth_provider*/ None,
McpProtocolMode::Legacy,
StreamableHttpRedirectMode::AgentPluginV1,
akode_rmcp_client::McpOAuthRefreshMode::Legacy,
)
.await?;
initialize_client(&client).await?;
assert_eq!(
call_echo_tool(&client, "transport-provided").await?,
expected_echo_result("transport-provided")
);
assert_eq!(http_client.bearer_tokens(), Vec::<String>::new());
let redirect_policies = http_client
.redirect_policies
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone();
assert!(!redirect_policies.is_empty());
assert_eq!(
redirect_policies,
vec![HttpRedirectPolicy::Stop; redirect_policies.len()]
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn auto_store_remains_pinned_across_session_recovery() -> anyhow::Result<()> {
let (_server, base_url) = spawn_streamable_http_server().await?;
let codex_home = TempDir::new()?;
let status = Command::new(std::env::current_exe()?)
.args([
"auto_store_remains_pinned_across_session_recovery_child",
"--exact",
"--ignored",
"--nocapture",
])
.env("AKODE_HOME", codex_home.path())
.env(CHILD_SERVER_URL_ENV, &base_url)
.status()
.await?;
assert!(
status.success(),
"OAuth store-pinning child failed: {status}"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
#[ignore = "spawned by auto_store_remains_pinned_across_session_recovery"]
async fn auto_store_remains_pinned_across_session_recovery_child() -> anyhow::Result<()> {
let state = Arc::new(TestKeyringState::default());
keyring::set_default_credential_builder(Box::new(TestCredentialBuilder {
state: Arc::clone(&state),
}));
let base_url = std::env::var(CHILD_SERVER_URL_ENV)?;
let server_url = format!("{base_url}/mcp");
let file_tokens = stored_tokens(&server_url, FILE_ACCESS_TOKEN);
save_oauth_tokens(
SERVER_NAME,
&file_tokens,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::Direct,
)
.await?;
let file_snapshot = stored_oauth_credential_snapshot(
SERVER_NAME,
&server_url,
OAuthCredentialsStoreMode::Auto,
AuthKeyringBackendKind::Direct,
)?
.expect("Auto should initially resolve the fallback File");
let keyring_tokens = stored_tokens(&server_url, KEYRING_ACCESS_TOKEN);
save_oauth_tokens(
SERVER_NAME,
&keyring_tokens,
OAuthCredentialsStoreMode::Auto,
AuthKeyringBackendKind::Direct,
)
.await?;
save_oauth_tokens(
SERVER_NAME,
&file_tokens,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::Direct,
)
.await?;
assert_eq!(
file_snapshot.reload(
SERVER_NAME,
&server_url,
OAuthCredentialsStoreMode::Auto,
AuthKeyringBackendKind::Direct,
)?,
Some(keyring_tokens.clone()),
);
let http_client = RecordingHttpClient::new(Environment::default_for_tests().get_http_client());
let client = RmcpClient::new_streamable_http_client(
SERVER_NAME,
&server_url,
/*bearer_token*/ None,
/*http_headers*/ None,
/*env_http_headers*/ None,
OAuthCredentialsStoreMode::Auto,
AuthKeyringBackendKind::Direct,
Arc::new(http_client.clone()),
/*auth_provider*/ None,
)
.await?;
initialize_client(&client).await?;
assert_eq!(
call_echo_tool(&client, "warmup").await?,
expected_echo_result("warmup")
);
arm_session_post_failure(
&base_url,
/*status*/ 404,
/*remaining*/ 1,
/*www_authenticate_headers*/ &[],
)
.await?;
// The selected keyring becomes unavailable only after initial construction. If recovery
// reevaluates Auto, it adopts the stale File token and this operation incorrectly succeeds.
state.fail_reads.store(true, Ordering::SeqCst);
match call_echo_tool(&client, "recovery-must-not-fallback").await {
Ok(result) => assert_eq!(result, expected_echo_result("recovery-must-not-fallback")),
Err(error) => {
let error_chain = format!("{error:#}");
assert!(
error_chain.contains("failed to reread OAuth tokens from resolved keyring storage"),
"unexpected recovery error: {error_chain}"
);
}
}
let bearer_tokens = http_client.bearer_tokens();
assert!(
bearer_tokens
.iter()
.any(|token| token == &format!("Bearer {KEYRING_ACCESS_TOKEN}")),
"expected requests authenticated by the keyring token: {bearer_tokens:?}"
);
assert!(
bearer_tokens
.iter()
.all(|token| token != &format!("Bearer {FILE_ACCESS_TOKEN}")),
"stale File token must never be sent during recovery: {bearer_tokens:?}"
);
Ok(())
}
fn stored_tokens(server_url: &str, access_token: &str) -> StoredOAuthTokens {
StoredOAuthTokens {
server_name: SERVER_NAME.to_string(),
url: server_url.to_string(),
issuer: None,
client_id: "test-client-id".to_string(),
token_response: WrappedOAuthTokenResponse(OAuthTokenResponse::new(
AccessToken::new(access_token.to_string()),
BasicTokenType::Bearer,
VendorExtraTokenFields::default(),
)),
expires_at: None,
}
}

View File

@@ -0,0 +1,387 @@
//! Exercises OAuth recovery through a real MCP client, with isolated file credentials.
mod streamable_http_test_support;
use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use akode_config::types::AuthKeyringBackendKind;
use akode_config::types::OAuthCredentialsStoreMode;
use akode_exec_server::Environment;
use akode_rmcp_client::RmcpClient;
use akode_rmcp_client::StoredOAuthTokens;
use akode_rmcp_client::WrappedOAuthTokenResponse;
use akode_rmcp_client::is_authentication_required_error;
use akode_rmcp_client::save_oauth_tokens;
use akode_rmcp_client::stored_oauth_credentials;
use oauth2::AccessToken;
use oauth2::RefreshToken;
use oauth2::basic::BasicTokenType;
use pretty_assertions::assert_eq;
use rmcp::model::CallToolResult;
use rmcp::model::ContentBlock;
use rmcp::transport::auth::OAuthTokenResponse;
use rmcp::transport::auth::VendorExtraTokenFields;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
use tokio::process::Command;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::Request;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_string_contains;
use wiremock::matchers::method;
use wiremock::matchers::path;
use streamable_http_test_support::initialize_client;
const SERVER_NAME: &str = "runtime-oauth";
const SCENARIO_ENV: &str = "MCP_TEST_RUNTIME_OAUTH_SCENARIO";
#[tokio::test]
async fn runtime_oauth_recovery() -> anyhow::Result<()> {
run_scenarios(&[
"no-refresh",
"rejected",
"malformed",
"transient",
"early-malformed",
"early-transient",
"refreshable",
"unexpired",
"unknown-expiry",
"revoked",
])
.await
}
#[tokio::test]
async fn startup_oauth_recovery() -> anyhow::Result<()> {
run_scenarios(&[
"startup-malformed",
"startup-transient",
"startup-refreshable",
])
.await
}
async fn run_scenarios(scenarios: &[&str]) -> anyhow::Result<()> {
for scenario in scenarios {
let home = TempDir::new()?;
let output = Command::new(std::env::current_exe()?)
.args(["runtime_oauth_child", "--exact", "--ignored", "--nocapture"])
.env("AKODE_HOME", home.path())
.env(SCENARIO_ENV, scenario)
.output()
.await?;
assert!(
output.status.success(),
"{scenario}: {}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
Ok(())
}
#[tokio::test]
#[ignore = "spawned by OAuth recovery tests with an isolated AKODE_HOME"]
async fn runtime_oauth_child() -> anyhow::Result<()> {
let scenario = std::env::var(SCENARIO_ENV)?;
let mcp = MockServer::start().await;
let authorization = MockServer::start().await;
let server_url = format!("{}/mcp", mcp.uri());
let startup = scenario.starts_with("startup-");
let revoked = scenario == "revoked";
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server/mcp"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"issuer": server_url,
"authorization_endpoint": format!("{}/authorize", authorization.uri()),
"token_endpoint": format!("{}/token", authorization.uri()),
})))
.mount(&mcp)
.await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(move |request: &Request| {
let body: Value = request.body_json().expect("JSON-RPC request");
match body["method"].as_str() {
Some("initialize") => ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0", "id": body["id"],
"result": {
"protocolVersion": body["params"]["protocolVersion"],
"capabilities": {"tools": {}},
"serverInfo": {"name": "runtime-oauth", "version": "1"},
},
})),
Some("notifications/initialized") => ResponseTemplate::new(202),
Some("tools/list") => ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0", "id": body["id"], "result": {"tools": []},
})),
Some("tools/call") if revoked => ResponseTemplate::new(401)
.insert_header("www-authenticate", "Bearer error=\"invalid_token\""),
Some("tools/call") => ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0", "id": body["id"],
"result": {"content": [{"type": "text", "text": "tool ran"}]},
})),
_ => ResponseTemplate::new(400),
}
})
.mount(&mcp)
.await;
// A zero lifetime expires after the handshake; 30 seconds exercises the early-refresh
// window while the token remains valid. Neither case needs sleeps or clock changes.
let expires_in = match scenario.as_str() {
"unexpired" | "startup-refreshable" => Some(3600),
"early-malformed" | "early-transient" => Some(30),
"unknown-expiry" => None,
_ => Some(0),
};
let bootstrap_response = match scenario.as_str() {
"startup-malformed" => ResponseTemplate::new(200).set_body_raw("{", "application/json"),
"startup-transient" => {
ResponseTemplate::new(503).set_body_json(json!({"error": "temporarily_unavailable"}))
}
_ => ResponseTemplate::new(200).set_body_json(json!({
"access_token": "initial-token", "token_type": "Bearer",
"refresh_token": "refresh-token", "expires_in": expires_in,
})),
};
let bootstrap = Mock::given(method("POST"))
.and(path("/token"))
.respond_with(bootstrap_response)
.mount_as_scoped(&authorization)
.await;
let mut response = OAuthTokenResponse::new(
AccessToken::new("old-token".to_string()),
BasicTokenType::Bearer,
VendorExtraTokenFields::default(),
);
if !revoked {
response.set_refresh_token(Some(RefreshToken::new("refresh-token".to_string())));
}
let tokens = StoredOAuthTokens {
server_name: SERVER_NAME.to_string(),
url: server_url.clone(),
issuer: Some(server_url.clone()),
client_id: "test-client".to_string(),
token_response: WrappedOAuthTokenResponse(response),
expires_at: Some(if revoked {
u64::try_from(SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis())? + 3_600_000
} else {
0
}),
};
save_oauth_tokens(
SERVER_NAME,
&tokens,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)
.await?;
let client = RmcpClient::new_streamable_http_client(
SERVER_NAME,
&server_url,
/*bearer_token*/ None,
/*http_headers*/ None,
/*env_http_headers*/ None,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
Environment::default_for_tests().get_http_client(),
/*auth_provider*/ None,
)
.await?;
let initialization = initialize_client(&client).await;
if startup {
if scenario == "startup-refreshable" {
initialization?;
let tools = client
.list_tools(/*params*/ None, Some(Duration::from_secs(5)))
.await?;
assert!(tools.tools.is_empty());
} else {
let error = initialization.expect_err("expired credentials must require reconnect");
assert!(is_authentication_required_error(&error), "{error:#}");
}
let requests = mcp.received_requests().await.expect("request recording");
let rpc_requests = requests
.iter()
.filter(|request| request.method.as_str() == "POST" && request.url.path() == "/mcp")
.collect::<Vec<_>>();
let methods = rpc_requests
.iter()
.map(|request| {
request.body_json::<Value>().expect("JSON-RPC request")["method"].clone()
})
.collect::<Vec<_>>();
assert_eq!(
methods,
if scenario == "startup-refreshable" {
vec![
json!("initialize"),
json!("notifications/initialized"),
json!("tools/list"),
]
} else {
Vec::<Value>::new()
}
);
for request in rpc_requests {
assert_eq!(
request
.headers
.get("authorization")
.and_then(|value| value.to_str().ok()),
Some("Bearer initial-token")
);
}
let after = stored_oauth_credentials(
SERVER_NAME,
&server_url,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)?
.expect("credentials are not deleted");
if scenario != "startup-refreshable" {
assert_eq!(after, tokens);
}
assert_eq!(
authorization
.received_requests()
.await
.expect("request recording")
.len(),
1
);
return Ok(());
}
initialization?;
drop(bootstrap);
let mut before = stored_oauth_credentials(
SERVER_NAME,
&server_url,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)?
.expect("saved credentials");
if scenario == "no-refresh" {
before.token_response.0.set_refresh_token(None);
save_oauth_tokens(
SERVER_NAME,
&before,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)
.await?;
}
let refresh_response = match scenario.as_str() {
"refreshable" => ResponseTemplate::new(200).set_body_json(json!({
"access_token": "renewed-token", "token_type": "Bearer", "expires_in": 3600,
})),
"malformed" | "early-malformed" => {
ResponseTemplate::new(200).set_body_raw("{", "application/json")
}
"transient" | "early-transient" => {
ResponseTemplate::new(503).set_body_json(json!({"error": "temporarily_unavailable"}))
}
_ => ResponseTemplate::new(400).set_body_json(json!({
"error": "invalid_grant", "error_description": "private provider details",
})),
};
Mock::given(method("POST"))
.and(path("/token"))
.and(body_string_contains("grant_type=refresh_token"))
.respond_with(refresh_response)
.expect(
if matches!(
scenario.as_str(),
"no-refresh" | "unexpired" | "unknown-expiry" | "revoked"
) {
0
} else {
1
},
)
.mount(&authorization)
.await;
let result = client
.call_tool(
"echo".to_string(),
/*arguments*/ None,
|_| Ok(None),
Some(Duration::from_secs(5)),
)
.await;
match scenario.as_str() {
"no-refresh" | "rejected" | "malformed" | "transient" => {
let mut expected = CallToolResult::error(vec![ContentBlock::text(
"MCP authentication required. Reconnect to continue using this server.",
)]);
expected.meta = Some(
serde_json::Map::from_iter([(
"mcp/www_authenticate".to_string(),
json!("Bearer error=\"invalid_token\""),
)])
.into(),
);
assert_eq!(result?, expected);
}
"revoked" => {
let mut expected =
CallToolResult::error(vec![ContentBlock::text("Authentication required")]);
expected.meta = Some(
serde_json::Map::from_iter([(
"mcp/www_authenticate".to_string(),
json!(["Bearer error=\"invalid_token\""]),
)])
.into(),
);
assert_eq!(result?, expected);
}
"early-malformed" | "early-transient" => {
let error = result.expect_err("early refresh failures must remain ordinary errors");
assert!(!is_authentication_required_error(&error));
}
"refreshable" | "unexpired" | "unknown-expiry" => {
let result = result?;
assert_eq!(result.content, vec![ContentBlock::text("tool ran")]);
assert_eq!(result.meta, None);
}
_ => unreachable!("scenario selected by parent test"),
}
let tool_calls = mcp
.received_requests()
.await
.expect("request recording")
.iter()
.filter(|request| {
request
.body_json::<Value>()
.ok()
.is_some_and(|body| body["method"] == "tools/call")
})
.count();
assert_eq!(
tool_calls,
usize::from(matches!(
scenario.as_str(),
"refreshable" | "unexpired" | "unknown-expiry" | "revoked"
))
);
let after = stored_oauth_credentials(
SERVER_NAME,
&server_url,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)?
.expect("credentials are not deleted");
if scenario != "refreshable" {
assert_eq!(before, after);
}
authorization.verify().await;
Ok(())
}

View File

@@ -0,0 +1,456 @@
mod streamable_http_test_support;
#[path = "streamable_http_recovery/telemetry_tests.rs"]
mod telemetry_tests;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use akode_exec_server::Environment;
use akode_exec_server::ExecServerError;
use akode_exec_server::HttpClient;
use akode_exec_server::HttpRequestParams;
use akode_exec_server::HttpRequestResponse;
use akode_exec_server::HttpResponseBodyStream;
use futures::FutureExt as _;
use futures::future::BoxFuture;
use pretty_assertions::assert_eq;
use rmcp::model::CallToolResult;
use rmcp::model::ContentBlock;
use rmcp::model::MetaObject;
use serde_json::Value;
use serde_json::json;
use streamable_http_test_support::arm_initialize_post_failure;
use streamable_http_test_support::arm_initialize_post_json_rpc_failure;
use streamable_http_test_support::arm_initialized_notification_post_json_rpc_failure;
use streamable_http_test_support::arm_session_post_failure;
use streamable_http_test_support::arm_session_post_json_rpc_failure;
use streamable_http_test_support::call_echo_tool;
use streamable_http_test_support::create_client;
use streamable_http_test_support::create_client_with_http_client;
use streamable_http_test_support::expected_echo_result;
use streamable_http_test_support::spawn_streamable_http_server;
const JSON_RPC_INTERNAL_ERROR_CODE: i64 = -32603;
const SIMULATED_NO_RESPONSE_MESSAGE: &str =
"http/request failed: error sending request for url (simulated no response)";
#[derive(Clone)]
struct FailFirstInitializeHttpClient {
inner: Arc<dyn HttpClient>,
failures_remaining: Arc<AtomicUsize>,
initialize_attempts: Arc<AtomicUsize>,
}
impl FailFirstInitializeHttpClient {
fn new(inner: Arc<dyn HttpClient>, failures_remaining: usize) -> Self {
Self {
inner,
failures_remaining: Arc::new(AtomicUsize::new(failures_remaining)),
initialize_attempts: Arc::new(AtomicUsize::new(0)),
}
}
fn initialize_attempts(&self) -> usize {
self.initialize_attempts.load(Ordering::SeqCst)
}
fn fail_next_initialize(&self) {
self.failures_remaining.store(1, Ordering::SeqCst);
}
}
impl HttpClient for FailFirstInitializeHttpClient {
fn http_request(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
self.inner.http_request(params)
}
fn http_request_stream(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
let inner = Arc::clone(&self.inner);
let failures_remaining = Arc::clone(&self.failures_remaining);
let initialize_attempts = Arc::clone(&self.initialize_attempts);
async move {
if is_initialize_post(&params) {
initialize_attempts.fetch_add(1, Ordering::SeqCst);
if failures_remaining.swap(0, Ordering::SeqCst) > 0 {
return Err(ExecServerError::Server {
code: JSON_RPC_INTERNAL_ERROR_CODE,
message: SIMULATED_NO_RESPONSE_MESSAGE.to_string(),
});
}
}
inner.http_request_stream(params).await
}
.boxed()
}
}
fn is_initialize_post(params: &HttpRequestParams) -> bool {
params.method.eq_ignore_ascii_case("POST")
&& params
.body
.as_ref()
.and_then(|body| serde_json::from_slice::<Value>(&body.0).ok())
.and_then(|body| {
body.get("method")
.and_then(Value::as_str)
.map(|method| method == "initialize")
})
.unwrap_or(false)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn streamable_http_initialize_retries_remote_no_response_error() -> anyhow::Result<()> {
let (_server, base_url) = spawn_streamable_http_server().await?;
let http_client = FailFirstInitializeHttpClient::new(
Environment::default_for_tests().get_http_client(),
/*failures_remaining*/ 1,
);
let client = create_client_with_http_client(&base_url, Arc::new(http_client.clone())).await?;
let result = call_echo_tool(&client, "after-init-retry").await?;
assert_eq!(http_client.initialize_attempts(), 2);
assert_eq!(result, expected_echo_result("after-init-retry"));
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn streamable_http_initialize_retries_transient_http_status() -> anyhow::Result<()> {
let (_server, base_url) = spawn_streamable_http_server().await?;
arm_initialize_post_failure(&base_url, /*status*/ 502, /*remaining*/ 1).await?;
let client = create_client(&base_url).await?;
let result = call_echo_tool(&client, "after-status-retry").await?;
assert_eq!(result, expected_echo_result("after-status-retry"));
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn streamable_http_initialize_retries_json_rpc_transient_status() -> anyhow::Result<()> {
let (_server, base_url) = spawn_streamable_http_server().await?;
arm_initialize_post_json_rpc_failure(&base_url, /*status*/ 502, /*remaining*/ 1).await?;
let client = create_client(&base_url).await?;
let result = call_echo_tool(&client, "after-json-status-retry").await?;
assert_eq!(result, expected_echo_result("after-json-status-retry"));
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn streamable_http_retries_initialized_notification_status() -> anyhow::Result<()> {
let (_server, base_url) = spawn_streamable_http_server().await?;
arm_initialized_notification_post_json_rpc_failure(
&base_url, /*status*/ 502, /*remaining*/ 1,
)
.await?;
let client = create_client(&base_url).await?;
let result = call_echo_tool(&client, "after-notification-status-retry").await?;
assert_eq!(
result,
expected_echo_result("after-notification-status-retry")
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn streamable_http_tools_list_retries_transient_http_status() -> anyhow::Result<()> {
let (_server, base_url) = spawn_streamable_http_server().await?;
let client = create_client(&base_url).await?;
let expected = client
.list_tools(
/*params*/ None,
/*timeout*/ Some(Duration::from_secs(5)),
)
.await?;
arm_session_post_failure(
&base_url,
/*status*/ 502,
/*remaining*/ 1,
/*www_authenticate_headers*/ &[],
)
.await?;
let result = client
.list_tools(
/*params*/ None,
/*timeout*/ Some(Duration::from_secs(5)),
)
.await?;
assert_eq!(result, expected);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn streamable_http_tools_list_retries_json_rpc_transient_status() -> anyhow::Result<()> {
let (_server, base_url) = spawn_streamable_http_server().await?;
let client = create_client(&base_url).await?;
let expected = client
.list_tools(
/*params*/ None,
/*timeout*/ Some(Duration::from_secs(5)),
)
.await?;
arm_session_post_json_rpc_failure(&base_url, /*status*/ 502, /*remaining*/ 1).await?;
let result = client
.list_tools(
/*params*/ None,
/*timeout*/ Some(Duration::from_secs(5)),
)
.await?;
assert_eq!(result, expected);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn streamable_http_404_session_expiry_recovers_and_retries_once() -> anyhow::Result<()> {
let (_server, base_url) = spawn_streamable_http_server().await?;
let client = create_client(&base_url).await?;
let warmup = call_echo_tool(&client, "warmup").await?;
assert_eq!(warmup, expected_echo_result("warmup"));
arm_session_post_failure(
&base_url,
/*status*/ 404,
/*remaining*/ 1,
/*www_authenticate_headers*/ &[],
)
.await?;
let recovered = call_echo_tool(&client, "recovered").await?;
assert_eq!(recovered, expected_echo_result("recovered"));
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn streamable_http_session_recovery_retries_initialize_failure() -> anyhow::Result<()> {
let (_server, base_url) = spawn_streamable_http_server().await?;
let http_client = FailFirstInitializeHttpClient::new(
Environment::default_for_tests().get_http_client(),
/*failures_remaining*/ 0,
);
let client = create_client_with_http_client(&base_url, Arc::new(http_client.clone())).await?;
let warmup = call_echo_tool(&client, "warmup").await?;
assert_eq!(warmup, expected_echo_result("warmup"));
arm_session_post_failure(
&base_url,
/*status*/ 404,
/*remaining*/ 1,
/*www_authenticate_headers*/ &[],
)
.await?;
http_client.fail_next_initialize();
let recovered = call_echo_tool(&client, "recovered-after-retry").await?;
assert_eq!(http_client.initialize_attempts(), 3);
assert_eq!(recovered, expected_echo_result("recovered-after-retry"));
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn streamable_http_401_does_not_trigger_recovery() -> anyhow::Result<()> {
let (_server, base_url) = spawn_streamable_http_server().await?;
let client = create_client(&base_url).await?;
let warmup = call_echo_tool(&client, "warmup").await?;
assert_eq!(warmup, expected_echo_result("warmup"));
arm_session_post_failure(
&base_url,
/*status*/ 401,
/*remaining*/ 2,
/*www_authenticate_headers*/ &[],
)
.await?;
let first_error = call_echo_tool(&client, "unauthorized").await.unwrap_err();
assert!(first_error.to_string().contains("401"));
let second_error = call_echo_tool(&client, "still-unauthorized")
.await
.unwrap_err();
assert!(second_error.to_string().contains("401"));
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn streamable_http_401_challenge_is_a_tool_error_without_replay() -> anyhow::Result<()> {
let challenge = r#"Bearer error="invalid_token", resource_metadata="https://example.com/.well-known/oauth-protected-resource""#;
for challenges in [
vec![challenge],
vec![r#"Basic realm="proxy, login""#, challenge],
] {
let (_server, base_url) = spawn_streamable_http_server().await?;
let client = create_client(&base_url).await?;
arm_session_post_failure(
&base_url,
/*status*/ 401,
/*remaining*/ 1,
&challenges,
)
.await?;
let result = call_echo_tool(&client, "rejected").await?;
let mut expected =
CallToolResult::error(vec![ContentBlock::text("Authentication required")]);
expected.meta = Some(MetaObject::from(serde_json::Map::from_iter([(
"mcp/www_authenticate".to_string(),
json!([challenges.join(", ")]),
)])));
assert_eq!(result, expected);
// A retry inside the failed call would consume the single rejection and return success.
assert_eq!(
call_echo_tool(&client, "next-user-call").await?,
expected_echo_result("next-user-call"),
);
}
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn streamable_http_403_scope_challenge_returns_insufficient_scope() -> anyhow::Result<()> {
let (_server, base_url) = spawn_streamable_http_server().await?;
let client = create_client(&base_url).await?;
let warmup = call_echo_tool(&client, "warmup").await?;
assert_eq!(warmup, expected_echo_result("warmup"));
arm_session_post_failure(
&base_url,
/*status*/ 403,
/*remaining*/ 1,
/*www_authenticate_headers*/
&[r#"Bearer error="insufficient_scope", scope="files:read files:write""#],
)
.await?;
let error = call_echo_tool(&client, "forbidden").await.unwrap_err();
assert!(
error.to_string().contains("Insufficient scope"),
"expected insufficient-scope transport error, got: {error:#}"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn streamable_http_403_finds_bearer_challenge_in_later_header_value() -> anyhow::Result<()> {
let (_server, base_url) = spawn_streamable_http_server().await?;
let client = create_client(&base_url).await?;
let warmup = call_echo_tool(&client, "warmup").await?;
assert_eq!(warmup, expected_echo_result("warmup"));
arm_session_post_failure(
&base_url,
/*status*/ 403,
/*remaining*/ 1,
/*www_authenticate_headers*/
&[
r#"Basic realm="example""#,
r#"Bearer error="insufficient_scope", scope="files:read""#,
],
)
.await?;
let error = call_echo_tool(&client, "forbidden").await.unwrap_err();
assert!(
error.to_string().contains("Insufficient scope"),
"expected insufficient-scope transport error, got: {error:#}"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn streamable_http_404_recovery_only_retries_once() -> anyhow::Result<()> {
let (_server, base_url) = spawn_streamable_http_server().await?;
let client = create_client(&base_url).await?;
let warmup = call_echo_tool(&client, "warmup").await?;
assert_eq!(warmup, expected_echo_result("warmup"));
arm_session_post_failure(
&base_url,
/*status*/ 404,
/*remaining*/ 2,
/*www_authenticate_headers*/ &[],
)
.await?;
let error = call_echo_tool(&client, "double-404").await.unwrap_err();
let error_message = error.to_string();
assert!(
error_message.contains("404") || error_message.contains("session expired"),
"expected session-expiry error, got: {error:#}"
);
let recovered = call_echo_tool(&client, "after-double-404").await?;
assert_eq!(recovered, expected_echo_result("after-double-404"));
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn streamable_http_non_session_failure_does_not_trigger_recovery() -> anyhow::Result<()> {
let (_server, base_url) = spawn_streamable_http_server().await?;
let client = create_client(&base_url).await?;
let warmup = call_echo_tool(&client, "warmup").await?;
assert_eq!(warmup, expected_echo_result("warmup"));
arm_session_post_failure(
&base_url,
/*status*/ 500,
/*remaining*/ 2,
/*www_authenticate_headers*/ &[],
)
.await?;
let first_error = call_echo_tool(&client, "server-error").await.unwrap_err();
assert!(first_error.to_string().contains("500"));
let second_error = call_echo_tool(&client, "still-server-error")
.await
.unwrap_err();
assert!(second_error.to_string().contains("500"));
Ok(())
}

View File

@@ -0,0 +1,152 @@
//! Checks attribution when a session rebuild discovers credentials after anonymous startup.
use super::streamable_http_test_support::arm_session_post_failure;
use super::streamable_http_test_support::call_echo_tool;
use super::streamable_http_test_support::expected_echo_result;
use super::streamable_http_test_support::initialize_client;
use super::streamable_http_test_support::spawn_streamable_http_server;
use akode_config::types::AuthKeyringBackendKind;
use akode_config::types::OAuthCredentialsStoreMode;
use akode_exec_server::Environment;
use akode_otel::MetricsClient;
use akode_otel::MetricsConfig;
use akode_otel::auth_storage::AuthStorageOriginator;
use akode_rmcp_client::RmcpClient;
use akode_rmcp_client::StoredOAuthTokens;
use akode_rmcp_client::WrappedOAuthTokenResponse;
use akode_rmcp_client::save_oauth_tokens;
use oauth2::AccessToken;
use oauth2::basic::BasicTokenType;
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
use opentelemetry_sdk::metrics::data::MetricData;
use pretty_assertions::assert_eq;
use rmcp::transport::auth::OAuthTokenResponse;
use std::collections::BTreeMap;
#[tokio::test]
async fn recovery_retains_originator_without_initial_credentials() -> anyhow::Result<()> {
if std::env::var_os("AKODE_MCP_RECOVERY_TELEMETRY_TEST_CHILD").is_none() {
let home = tempfile::tempdir()?;
let output = tokio::process::Command::new(std::env::current_exe()?)
.args([
"--exact",
"telemetry_tests::recovery_retains_originator_without_initial_credentials",
"--nocapture",
])
.env("AKODE_MCP_RECOVERY_TELEMETRY_TEST_CHILD", "1")
.env("AKODE_HOME", home.path())
.output()
.await?;
assert!(
output.status.success(),
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
return Ok(());
}
let metrics = akode_otel::install_global_metrics(MetricsClient::new(
MetricsConfig::in_memory("test", "test", "1", Default::default()).with_runtime_reader(),
)?);
let (_server, base_url) = spawn_streamable_http_server().await?;
let url = format!("{base_url}/mcp");
let client = AuthStorageOriginator::from_client_name("codex_vscode")
.scope(async {
let client = RmcpClient::new_streamable_http_client(
"recovery-telemetry",
&url,
/*bearer_token*/ None,
/*http_headers*/ None,
/*env_http_headers*/ None,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::Direct,
Environment::default_for_tests().get_http_client(),
/*auth_provider*/ None,
)
.await?;
initialize_client(&client).await?;
anyhow::Ok(client)
})
.await?;
assert_eq!(
call_echo_tool(&client, "warmup").await?,
expected_echo_result("warmup")
);
for recovery in 0..3 {
if recovery == 1 {
// Credentials arrive after startup and the first anonymous recovery.
save_oauth_tokens(
"recovery-telemetry",
&StoredOAuthTokens {
server_name: "recovery-telemetry".into(),
url: url.clone(),
issuer: Some(url.clone()),
client_id: "client-id".into(),
token_response: WrappedOAuthTokenResponse(OAuthTokenResponse::new(
AccessToken::new("saved-access-token".into()),
BasicTokenType::Bearer,
Default::default(),
)),
expires_at: None,
},
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::Direct,
)
.await?;
}
arm_session_post_failure(
&base_url,
/*status*/ 404,
/*remaining*/ 1,
/*www_authenticate_headers*/ &[],
)
.await?;
assert_eq!(
call_echo_tool(&client, "recovered").await?,
expected_echo_result("recovered")
);
}
let snapshot = metrics.snapshot()?;
let mut loads = Vec::new();
for metric in snapshot
.scope_metrics()
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
{
if metric.name() == "codex.auth_storage.operation"
&& let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data()
{
for point in sum.data_points() {
let tags: BTreeMap<_, _> = point
.attributes()
.map(|tag| (tag.key.to_string(), tag.value.to_string()))
.collect();
if tags["credential_kind"] == "mcp" && tags["operation"] == "load" {
loads.push((
tags["originator"].clone(),
tags["storage_phase"].clone(),
tags["outcome"].clone(),
point.value(),
));
}
}
}
}
loads.sort();
assert_eq!(
loads,
vec![
("codex_vscode".into(), "pinned".into(), "success".into(), 1),
(
"codex_vscode".into(),
"policy".into(),
"not_found".into(),
2
),
("codex_vscode".into(), "policy".into(), "success".into(), 1),
]
);
metrics.shutdown()?;
Ok(())
}

View File

@@ -0,0 +1,134 @@
//! Integration coverage for the remote Streamable HTTP RMCP path.
//!
//! These tests exercise the orchestrator-side RMCP adapter against a real
//! `exec-server` process so HTTP requests go through the remote runtime path
//! instead of direct local `reqwest` calls.
mod streamable_http_test_support;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Context;
use akode_config::types::AuthKeyringBackendKind;
use akode_config::types::OAuthCredentialsStoreMode;
use akode_rmcp_client::ElicitationAction;
use akode_rmcp_client::ElicitationResponse;
use akode_rmcp_client::McpProtocolMode;
use akode_rmcp_client::RmcpClient;
use futures::FutureExt as _;
use pretty_assertions::assert_eq;
use rmcp::model::ClientCapabilities;
use rmcp::model::Implementation;
use rmcp::model::InitializeRequestParams;
use rmcp::model::ProtocolVersion;
use serde_json::json;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_partial_json;
use wiremock::matchers::method;
use streamable_http_test_support::call_echo_tool;
use streamable_http_test_support::create_remote_client;
use streamable_http_test_support::expected_echo_result;
use streamable_http_test_support::spawn_exec_server;
use streamable_http_test_support::spawn_streamable_http_server;
/// What this tests: the RMCP remote Streamable HTTP adapter can initialize
/// a server and call a tool while every MCP HTTP request goes through a real
/// exec-server process instead of a direct reqwest transport.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn streamable_http_remote_client_round_trips_through_exec_server() -> anyhow::Result<()> {
// Phase 1: start the MCP Streamable HTTP test server and a local
// exec-server process that will own the HTTP network calls.
let (_server, base_url) = spawn_streamable_http_server().await?;
let exec_server = spawn_exec_server().await?;
// Phase 2: create and initialize the RMCP client using the executor-backed
// Streamable HTTP transport.
let client = create_remote_client(&base_url, exec_server.client.clone()).await?;
// Phase 3: prove the initialized client can complete a tool call and
// preserve the normal RMCP response shape.
let result = call_echo_tool(&client, "remote").await?;
assert_eq!(result, expected_echo_result("remote"));
Ok(())
}
/// A timed-out MCP handshake must release the remote executor for later requests.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn streamable_http_handshake_timeout_unblocks_remote_executor() -> anyhow::Result<()> {
stalled_handshake_unblocks_remote_executor(McpProtocolMode::Legacy, "initialize").await
}
/// MCP 2026 discovery must also release the remote executor when it times out.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn streamable_http_discovery_timeout_unblocks_remote_executor() -> anyhow::Result<()> {
stalled_handshake_unblocks_remote_executor(McpProtocolMode::V20260728, "server/discover").await
}
async fn stalled_handshake_unblocks_remote_executor(
protocol_mode: McpProtocolMode,
expected_method: &str,
) -> anyhow::Result<()> {
let http_server = MockServer::start().await;
Mock::given(method("POST"))
.and(body_partial_json(json!({ "method": expected_method })))
.respond_with(ResponseTemplate::new(200).set_delay(Duration::from_secs(60)))
.expect(1)
.mount(&http_server)
.await;
let exec_server = spawn_exec_server().await?;
let client = RmcpClient::new_streamable_http_client_with_protocol_mode(
"stalled-remote-http",
&format!("{}/mcp", http_server.uri()),
Some("test-bearer".to_string()),
/*http_headers*/ None,
/*env_http_headers*/ None,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
Arc::new(exec_server.client.clone()),
/*auth_provider*/ None,
protocol_mode,
)
.await?;
let params = InitializeRequestParams::new(
ClientCapabilities::default(),
Implementation::new("codex-test", "0.0.0-test"),
)
.with_protocol_version(ProtocolVersion::V_2025_06_18);
let error = client
.initialize(
params,
// Allow the request to reach the remote HTTP server on loaded CI
// workers before testing cancellation of its stalled response.
Some(Duration::from_secs(5)),
Box::new(|_, _| {
async {
Ok(ElicitationResponse {
action: ElicitationAction::Accept,
content: None,
meta: None,
})
}
.boxed()
}),
)
.await
.err()
.context("the stalled MCP handshake must time out")?;
assert!(
error.to_string().contains("timed out"),
"unexpected MCP handshake error: {error}"
);
tokio::time::timeout(
Duration::from_secs(2),
exec_server.client.environment_status(),
)
.await
.context("a timed-out handshake must not leave the serial executor blocked")??;
Ok(())
}

View File

@@ -0,0 +1,435 @@
//! Shared helpers for Streamable HTTP RMCP integration tests.
//!
//! This support module starts the test HTTP server, launches a real
//! `exec-server` when remote coverage is needed, and provides small helpers for
//! creating RMCP clients and asserting round-trip behavior.
//! HTTP server startup uses the address published by the child that owns the listener.
// This support module is included by multiple integration-test crates. Each
// crate uses a different subset of the helpers, so dead-code warnings would
// otherwise depend on which test file compiled the module.
#![allow(dead_code)]
use std::net::SocketAddr;
use std::path::Path;
use std::path::PathBuf;
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use anyhow::Context as _;
use akode_config::types::AuthKeyringBackendKind;
use akode_config::types::OAuthCredentialsStoreMode;
use akode_exec_server::Environment;
use akode_exec_server::ExecServerClient;
use akode_exec_server::HttpClient;
use akode_exec_server::RemoteExecServerConnectArgs;
use akode_http_client::HttpClientFactory;
use akode_http_client::OutboundProxyPolicy;
use akode_rmcp_client::ElicitationAction;
use akode_rmcp_client::ElicitationResponse;
use akode_rmcp_client::RmcpClient;
use akode_utils_cargo_bin::CargoBinError;
use futures::FutureExt as _;
use pretty_assertions::assert_eq;
use rmcp::model::CallToolResult;
use rmcp::model::ClientCapabilities;
use rmcp::model::ElicitationCapability;
use rmcp::model::FormElicitationCapability;
use rmcp::model::Implementation;
use rmcp::model::InitializeRequestParams;
use rmcp::model::ProtocolVersion;
use serde_json::json;
use tempfile::TempDir;
use tokio::io::AsyncBufReadExt;
use tokio::io::BufReader;
use tokio::process::Child;
use tokio::process::Command;
use tokio::time::sleep;
const SESSION_POST_FAILURE_CONTROL_PATH: &str = "/test/control/session-post-failure";
const INITIALIZE_POST_FAILURE_CONTROL_PATH: &str = "/test/control/initialize-post-failure";
const INITIALIZED_NOTIFICATION_POST_FAILURE_CONTROL_PATH: &str =
"/test/control/initialized-notification-post-failure";
fn streamable_http_server_bin() -> Result<PathBuf, CargoBinError> {
akode_utils_cargo_bin::cargo_bin("test_streamable_http_server")
}
fn init_params() -> InitializeRequestParams {
let mut capabilities = ClientCapabilities::default();
capabilities.elicitation =
Some(ElicitationCapability::new().with_form(FormElicitationCapability::new()));
InitializeRequestParams::new(
capabilities,
Implementation::new("codex-test", "0.0.0-test").with_title("Codex rmcp recovery test"),
)
.with_protocol_version(ProtocolVersion::V_2025_06_18)
}
pub(crate) fn expected_echo_result(message: &str) -> CallToolResult {
let mut result = CallToolResult::success(Vec::new());
result.result_type = None;
result.structured_content = Some(json!({
"echo": format!("ECHOING: {message}"),
"env": null,
}));
result
}
pub(crate) async fn create_client(base_url: &str) -> anyhow::Result<RmcpClient> {
create_client_with_http_client(base_url, Environment::default_for_tests().get_http_client())
.await
}
pub(crate) async fn create_client_with_http_client(
base_url: &str,
http_client: Arc<dyn HttpClient>,
) -> anyhow::Result<RmcpClient> {
let client = RmcpClient::new_streamable_http_client(
"test-streamable-http",
&format!("{base_url}/mcp"),
Some("test-bearer".to_string()),
/*http_headers*/ None,
/*env_http_headers*/ None,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
http_client,
/*auth_provider*/ None,
)
.await?;
initialize_client(&client).await?;
Ok(client)
}
pub(crate) async fn initialize_client(client: &RmcpClient) -> anyhow::Result<()> {
initialize_client_with_timeout(client, Duration::from_secs(/*secs*/ 5)).await
}
pub(crate) async fn initialize_client_with_timeout(
client: &RmcpClient,
timeout: Duration,
) -> anyhow::Result<()> {
client
.initialize(
init_params(),
Some(timeout),
Box::new(|_, _| {
async {
Ok(ElicitationResponse {
action: ElicitationAction::Accept,
content: Some(json!({})),
meta: None,
})
}
.boxed()
}),
)
.await?;
Ok(())
}
/// Creates a Streamable HTTP RMCP client that sends traffic through the remote
/// runtime HTTP API.
pub(crate) async fn create_remote_client(
base_url: &str,
http_client: ExecServerClient,
) -> anyhow::Result<RmcpClient> {
let client = RmcpClient::new_streamable_http_client(
"test-streamable-http-remote",
&format!("{base_url}/mcp"),
Some("test-bearer".to_string()),
/*http_headers*/ None,
/*env_http_headers*/ None,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
Arc::new(http_client),
/*auth_provider*/ None,
)
.await?;
client
.initialize(
init_params(),
Some(Duration::from_secs(5)),
Box::new(|_, _| {
async {
Ok(ElicitationResponse {
action: ElicitationAction::Accept,
content: Some(json!({})),
meta: None,
})
}
.boxed()
}),
)
.await?;
Ok(client)
}
pub(crate) async fn call_echo_tool(
client: &RmcpClient,
message: &str,
) -> anyhow::Result<CallToolResult> {
client
.call_tool(
"echo".to_string(),
Some(json!({ "message": message })),
|_| Ok(None),
Some(Duration::from_secs(5)),
)
.await
}
fn control_client() -> anyhow::Result<akode_http_client::HttpClient> {
Ok(akode_http_client::HttpClientBuilder::new().build_direct()?)
}
pub(crate) async fn arm_session_post_failure(
base_url: &str,
status: u16,
remaining: usize,
www_authenticate_headers: &[&str],
) -> anyhow::Result<()> {
let response = control_client()?
.post(format!("{base_url}{SESSION_POST_FAILURE_CONTROL_PATH}"))
.json(&json!({
"status": status,
"remaining": remaining,
"www_authenticate_headers": www_authenticate_headers,
}))
.send()
.await?;
assert_eq!(response.status(), http::StatusCode::NO_CONTENT);
Ok(())
}
pub(crate) async fn arm_session_post_json_rpc_failure(
base_url: &str,
status: u16,
remaining: usize,
) -> anyhow::Result<()> {
let response = control_client()?
.post(format!("{base_url}{SESSION_POST_FAILURE_CONTROL_PATH}"))
.json(&json!({
"status": status,
"remaining": remaining,
"content_type": "application/json",
"body": json!({
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32000,
"message": "transient session failure",
},
}).to_string(),
}))
.send()
.await?;
assert_eq!(response.status(), http::StatusCode::NO_CONTENT);
Ok(())
}
pub(crate) async fn arm_initialized_notification_post_json_rpc_failure(
base_url: &str,
status: u16,
remaining: usize,
) -> anyhow::Result<()> {
let response = control_client()?
.post(format!(
"{base_url}{INITIALIZED_NOTIFICATION_POST_FAILURE_CONTROL_PATH}"
))
.json(&json!({
"status": status,
"remaining": remaining,
"content_type": "application/json",
"body": json!({
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32000,
"message": "transient session failure",
},
}).to_string(),
}))
.send()
.await?;
assert_eq!(response.status(), http::StatusCode::NO_CONTENT);
Ok(())
}
pub(crate) async fn arm_initialize_post_failure(
base_url: &str,
status: u16,
remaining: usize,
) -> anyhow::Result<()> {
let response = control_client()?
.post(format!("{base_url}{INITIALIZE_POST_FAILURE_CONTROL_PATH}"))
.json(&json!({
"status": status,
"remaining": remaining,
}))
.send()
.await?;
assert_eq!(response.status(), http::StatusCode::NO_CONTENT);
Ok(())
}
pub(crate) async fn arm_initialize_post_json_rpc_failure(
base_url: &str,
status: u16,
remaining: usize,
) -> anyhow::Result<()> {
let response = control_client()?
.post(format!("{base_url}{INITIALIZE_POST_FAILURE_CONTROL_PATH}"))
.json(&json!({
"status": status,
"remaining": remaining,
"content_type": "application/json",
"body": json!({
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32000,
"message": "transient initialize failure",
},
}).to_string(),
}))
.send()
.await?;
assert_eq!(response.status(), http::StatusCode::NO_CONTENT);
Ok(())
}
pub(crate) async fn spawn_streamable_http_server() -> anyhow::Result<(Child, String)> {
let startup_dir = tempfile::tempdir()?;
let bound_addr_path = startup_dir.path().join("bound_addr");
// Let the child reserve its own port; releasing a parent-owned port before
// spawning can let another test claim it and satisfy the readiness probe.
let mut child = Command::new(streamable_http_server_bin()?)
.kill_on_drop(true)
.env("MCP_STREAMABLE_HTTP_BIND_ADDR", "127.0.0.1:0")
.env("MCP_STREAMABLE_HTTP_BOUND_ADDR_FILE", &bound_addr_path)
.spawn()?;
let address = wait_for_streamable_http_server(
&mut child,
&bound_addr_path,
Duration::from_secs(/*secs*/ 5),
)
.await?;
Ok((child, format!("http://{address}")))
}
/// Owns the exec-server process used by the remote-client integration test.
pub(crate) struct ExecServerProcess {
_codex_home: TempDir,
child: Child,
pub(crate) client: ExecServerClient,
}
impl Drop for ExecServerProcess {
/// Stops the local exec-server process best-effort when the test exits.
fn drop(&mut self) {
let _ = self.child.start_kill();
}
}
/// Starts a local exec-server and connects an initialized `ExecServerClient`.
pub(crate) async fn spawn_exec_server() -> anyhow::Result<ExecServerProcess> {
let codex_home = TempDir::new()?;
let mut child = Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.args(["exec-server", "--listen", "ws://127.0.0.1:0"])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.kill_on_drop(true)
.env("AKODE_HOME", codex_home.path())
.spawn()?;
let websocket_url = read_exec_server_listen_url(&mut child).await?;
let client = ExecServerClient::connect_websocket(RemoteExecServerConnectArgs::new(
websocket_url,
"rmcp-client-remote-http-test".to_string(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
))
.await?;
Ok(ExecServerProcess {
_codex_home: codex_home,
child,
client,
})
}
/// Reads the websocket URL printed by `akode exec-server --listen`.
async fn read_exec_server_listen_url(child: &mut Child) -> anyhow::Result<String> {
let stdout = child
.stdout
.take()
.context("failed to capture exec-server stdout")?;
let mut lines = BufReader::new(stdout).lines();
let deadline = Instant::now() + Duration::from_secs(10);
loop {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
anyhow::bail!("timed out waiting for exec-server listen URL");
}
let line = tokio::time::timeout(remaining, lines.next_line())
.await
.context("timed out waiting for exec-server stdout")??
.context("exec-server stdout closed before emitting listen URL")?;
let listen_url = line.trim();
if listen_url.starts_with("ws://") {
return Ok(listen_url.to_string());
}
}
}
async fn wait_for_streamable_http_server(
server_child: &mut Child,
bound_addr_path: &Path,
timeout: Duration,
) -> anyhow::Result<SocketAddr> {
let deadline = Instant::now() + timeout;
loop {
if let Some(status) = server_child.try_wait()? {
return Err(anyhow::anyhow!(
"streamable HTTP server exited early with status {status}"
));
}
if Instant::now() >= deadline {
return Err(anyhow::anyhow!(
"timed out waiting for streamable HTTP server to publish its bound address"
));
}
match std::fs::read_to_string(bound_addr_path) {
Ok(contents) => {
// The child creates the file before writing the address into it.
if let Ok(address) = contents.parse() {
return Ok(address);
}
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => {
return Err(error).context("failed to read streamable HTTP server bound address");
}
}
sleep(Duration::from_millis(50)).await;
}
}

View File

@@ -0,0 +1,70 @@
mod streamable_http_test_support;
use std::collections::HashMap;
use akode_config::types::AuthKeyringBackendKind;
use akode_config::types::OAuthCredentialsStoreMode;
use akode_exec_server::Environment;
use akode_rmcp_client::RmcpClient;
use serde_json::Value;
use serde_json::json;
use streamable_http_test_support::initialize_client;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::Request;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn streamable_http_requests_preserve_configured_user_agent() -> anyhow::Result<()> {
let custom_user_agent = "custom-agent/9.9";
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/mcp"))
.and(header("user-agent", custom_user_agent))
.respond_with(|request: &Request| {
let body: Value = request.body_json().expect("valid JSON-RPC request");
match body.get("method").and_then(Value::as_str) {
Some("initialize") => ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
"id": body.get("id").cloned().unwrap_or(Value::Null),
"result": {
"protocolVersion": "2025-06-18",
"capabilities": {},
"serverInfo": {
"name": "user-agent-test",
"version": "0.0.0-test",
},
},
})),
Some("notifications/initialized") => ResponseTemplate::new(202),
method => ResponseTemplate::new(400)
.set_body_string(format!("unexpected JSON-RPC method: {method:?}")),
}
})
.expect(2)
.mount(&server)
.await;
let custom_client = RmcpClient::new_streamable_http_client(
"test-streamable-http",
&format!("{}/mcp", server.uri()),
Some("test-bearer".to_string()),
Some(HashMap::from([(
"user-agent".to_string(),
custom_user_agent.to_string(),
)])),
/*env_http_headers*/ None,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
Environment::default_for_tests().get_http_client(),
/*auth_provider*/ None,
)
.await?;
initialize_client(&custom_client).await?;
server.verify().await;
Ok(())
}