Base: codex-main originale (prima del fork aKode)
This commit is contained in:
151
codex-rs/rmcp-client/src/bin/rmcp_test_server.rs
Normal file
151
codex-rs/rmcp-client/src/bin/rmcp_test_server.rs
Normal file
@@ -0,0 +1,151 @@
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use rmcp::ErrorData as McpError;
|
||||
use rmcp::ServiceExt;
|
||||
use rmcp::handler::server::ServerHandler;
|
||||
use rmcp::model::CallToolRequestParams;
|
||||
use rmcp::model::CallToolResult;
|
||||
use rmcp::model::JsonObject;
|
||||
use rmcp::model::ListToolsResult;
|
||||
use rmcp::model::PaginatedRequestParams;
|
||||
use rmcp::model::ServerCapabilities;
|
||||
use rmcp::model::ServerConfig;
|
||||
use rmcp::model::Tool;
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use tokio::task;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TestToolServer {
|
||||
tools: Arc<Vec<Tool>>,
|
||||
}
|
||||
pub fn stdio() -> (tokio::io::Stdin, tokio::io::Stdout) {
|
||||
(tokio::io::stdin(), tokio::io::stdout())
|
||||
}
|
||||
impl TestToolServer {
|
||||
fn new() -> Self {
|
||||
let tools = vec![Self::echo_tool()];
|
||||
Self {
|
||||
tools: Arc::new(tools),
|
||||
}
|
||||
}
|
||||
|
||||
fn echo_tool() -> Tool {
|
||||
#[expect(clippy::expect_used)]
|
||||
let schema: JsonObject = serde_json::from_value(json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"message": { "type": "string" },
|
||||
"env_var": { "type": "string" }
|
||||
},
|
||||
"required": ["message"],
|
||||
"additionalProperties": false
|
||||
}))
|
||||
.expect("echo tool schema should deserialize");
|
||||
|
||||
let mut tool = Tool::new(
|
||||
Cow::Borrowed("echo"),
|
||||
Cow::Borrowed("Echo back the provided message and include environment data."),
|
||||
Arc::new(schema),
|
||||
);
|
||||
#[expect(clippy::expect_used)]
|
||||
let output_schema: JsonObject = serde_json::from_value(json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"echo": { "type": "string" },
|
||||
"env": {
|
||||
"anyOf": [
|
||||
{ "type": "string" },
|
||||
{ "type": "null" }
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": ["echo", "env"],
|
||||
"additionalProperties": false
|
||||
}))
|
||||
.expect("echo tool output schema should deserialize");
|
||||
tool.output_schema = Some(Arc::new(output_schema));
|
||||
tool
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct EchoArgs {
|
||||
message: String,
|
||||
env_var: Option<String>,
|
||||
}
|
||||
|
||||
impl ServerHandler for TestToolServer {
|
||||
fn get_info(&self) -> ServerConfig {
|
||||
ServerConfig::new(
|
||||
ServerCapabilities::builder()
|
||||
.enable_tools()
|
||||
.enable_tool_list_changed()
|
||||
.build(),
|
||||
)
|
||||
}
|
||||
|
||||
fn list_tools(
|
||||
&self,
|
||||
_request: Option<PaginatedRequestParams>,
|
||||
_context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
|
||||
) -> impl std::future::Future<Output = Result<ListToolsResult, McpError>> + Send + '_ {
|
||||
let tools = self.tools.clone();
|
||||
async move { Ok(ListToolsResult::with_all_items((*tools).clone())) }
|
||||
}
|
||||
|
||||
async fn call_tool(
|
||||
&self,
|
||||
request: CallToolRequestParams,
|
||||
_context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
|
||||
) -> Result<rmcp::model::CallToolResponse, McpError> {
|
||||
match request.name.as_ref() {
|
||||
"echo" => {
|
||||
let args: EchoArgs = match request.arguments {
|
||||
Some(arguments) => serde_json::from_value(serde_json::Value::Object(
|
||||
arguments.into_iter().collect(),
|
||||
))
|
||||
.map_err(|err| McpError::invalid_params(err.to_string(), None))?,
|
||||
None => {
|
||||
return Err(McpError::invalid_params(
|
||||
"missing arguments for echo tool",
|
||||
None,
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let env_snapshot: HashMap<String, String> = std::env::vars().collect();
|
||||
let env_name = args.env_var.as_deref().unwrap_or("MCP_TEST_VALUE");
|
||||
let structured_content = json!({
|
||||
"echo": args.message,
|
||||
"env": env_snapshot.get(env_name),
|
||||
});
|
||||
|
||||
let mut result = CallToolResult::success(Vec::new());
|
||||
result.structured_content = Some(structured_content);
|
||||
Ok(result.into())
|
||||
}
|
||||
other => Err(McpError::invalid_params(
|
||||
format!("unknown tool: {other}"),
|
||||
None,
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
eprintln!("starting rmcp test server");
|
||||
// Run the server with STDIO transport. If the client disconnects we simply
|
||||
// bubble up the error so the process exits.
|
||||
let service = TestToolServer::new();
|
||||
let running = service.serve(stdio()).await?;
|
||||
|
||||
// Wait for the client to finish interacting with the server.
|
||||
running.waiting().await?;
|
||||
// Drain background tasks to ensure clean shutdown.
|
||||
task::yield_now().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use std::io;
|
||||
use std::io::BufRead;
|
||||
use std::io::Write;
|
||||
|
||||
use anyhow::Result;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
|
||||
fn main() -> Result<()> {
|
||||
assert!(std::env::var_os("CODEX_MCP_PROTOCOL_VERSION").is_none());
|
||||
let mut stdout = io::stdout().lock();
|
||||
|
||||
for line in io::stdin().lock().lines() {
|
||||
let request: Value = serde_json::from_str(&line?)?;
|
||||
let result = match request["method"].as_str() {
|
||||
Some("server/discover") => {
|
||||
assert_eq!(
|
||||
request["params"]["_meta"]["io.modelcontextprotocol/protocolVersion"],
|
||||
"2026-07-28"
|
||||
);
|
||||
json!({
|
||||
"resultType": "complete",
|
||||
"supportedVersions": ["2026-07-28"],
|
||||
"capabilities": {"tools": {}, "resources": {}},
|
||||
"_meta": {
|
||||
"io.modelcontextprotocol/serverInfo": {
|
||||
"name": "strict-stdio-discovery",
|
||||
"version": "1.0.0",
|
||||
},
|
||||
},
|
||||
"ttlMs": 0,
|
||||
"cacheScope": "private",
|
||||
})
|
||||
}
|
||||
Some("tools/list") => json!({
|
||||
"resultType": "complete",
|
||||
"tools": [{
|
||||
"name": "stdio_echo",
|
||||
"inputSchema": {"type": "object"},
|
||||
}],
|
||||
}),
|
||||
Some("resources/list") => json!({
|
||||
"resultType": "complete",
|
||||
"resources": [{
|
||||
"uri": "test://stdio/resource",
|
||||
"name": "stdio resource",
|
||||
}],
|
||||
}),
|
||||
Some("resources/templates/list") => json!({
|
||||
"resultType": "complete",
|
||||
"resourceTemplates": [{
|
||||
"uriTemplate": "test://stdio/{name}",
|
||||
"name": "stdio resource template",
|
||||
}],
|
||||
}),
|
||||
method => anyhow::bail!("unexpected modern stdio discovery method: {method:?}"),
|
||||
};
|
||||
serde_json::to_writer(
|
||||
&mut stdout,
|
||||
&json!({"jsonrpc": "2.0", "id": request["id"], "result": result}),
|
||||
)?;
|
||||
stdout.write_all(b"\n")?;
|
||||
stdout.flush()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
339
codex-rs/rmcp-client/src/bin/test_mcp_2026_stdio_server.rs
Normal file
339
codex-rs/rmcp-client/src/bin/test_mcp_2026_stdio_server.rs
Normal file
@@ -0,0 +1,339 @@
|
||||
use std::io;
|
||||
use std::io::BufRead;
|
||||
use std::io::Write;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
|
||||
const MODERN_VERSION: &str = "2026-07-28";
|
||||
const LEGACY_VERSION: &str = "2025-06-18";
|
||||
const MAX_MESSAGE_BYTES: usize = 8 * 1024 * 1024;
|
||||
|
||||
fn write_message(stdout: &mut io::StdoutLock<'_>, message: Value) -> Result<()> {
|
||||
serde_json::to_writer(&mut *stdout, &message)?;
|
||||
stdout.write_all(b"\n")?;
|
||||
stdout.flush()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn assert_modern_metadata(message: &Value) {
|
||||
let metadata = &message["params"]["_meta"];
|
||||
assert_eq!(
|
||||
metadata["io.modelcontextprotocol/protocolVersion"],
|
||||
MODERN_VERSION
|
||||
);
|
||||
assert!(metadata["io.modelcontextprotocol/clientInfo"].is_object());
|
||||
assert!(metadata["io.modelcontextprotocol/clientCapabilities"].is_object());
|
||||
}
|
||||
|
||||
fn legacy_schema_defaults() -> Value {
|
||||
json!({
|
||||
"name": "John Doe",
|
||||
"age": 30,
|
||||
"score": 95.5,
|
||||
"status": "active",
|
||||
"verified": true,
|
||||
})
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let mode = std::env::args().nth(1).unwrap_or_default();
|
||||
assert!(matches!(
|
||||
mode.as_str(),
|
||||
"modern"
|
||||
| "modern-late"
|
||||
| "legacy"
|
||||
| "legacy-fallback"
|
||||
| "legacy-reject-and-exit"
|
||||
| "legacy-init-first"
|
||||
| "legacy-reject-late-initialize"
|
||||
| "legacy-late"
|
||||
| "legacy-silent"
|
||||
| "legacy-versions"
|
||||
| "oversized-stdout"
|
||||
| "oversized-stdout-legacy"
|
||||
));
|
||||
assert!(std::env::var_os("CODEX_MCP_PROTOCOL_VERSION").is_none());
|
||||
let is_legacy = mode.starts_with("legacy") || mode.ends_with("-legacy");
|
||||
let oversized = mode.starts_with("oversized-stdout");
|
||||
let mut stdout = io::stdout().lock();
|
||||
let mut initialized = false;
|
||||
let mut pending_legacy_call = None;
|
||||
let mut late_discovery_id = None;
|
||||
|
||||
for (index, line) in io::stdin().lock().lines().enumerate() {
|
||||
let message: Value = serde_json::from_str(&line?)?;
|
||||
let Some(method) = message.get("method").and_then(Value::as_str) else {
|
||||
let pending_call = pending_legacy_call
|
||||
.take()
|
||||
.ok_or_else(|| anyhow::anyhow!("unexpected server-request response"))?;
|
||||
assert_eq!(message["id"], "legacy-approval");
|
||||
assert_eq!(message["result"]["action"], "accept");
|
||||
assert_eq!(message["result"]["content"], legacy_schema_defaults());
|
||||
write_message(
|
||||
&mut stdout,
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": pending_call,
|
||||
"result": {"content": [{"type": "text", "text": "legacy approved"}]},
|
||||
}),
|
||||
)?;
|
||||
continue;
|
||||
};
|
||||
|
||||
// Some older helpers assume their first request is initialize without inspecting its method.
|
||||
let method = if mode == "legacy-init-first" && !initialized {
|
||||
"initialize"
|
||||
} else {
|
||||
method
|
||||
};
|
||||
match method {
|
||||
// Some legacy stdio servers exit if their first message is not initialize.
|
||||
"server/discover" if mode == "legacy" => {
|
||||
// Some wrappers print a banner before starting the protocol.
|
||||
writeln!(stdout, "starting server")?;
|
||||
write_message(
|
||||
&mut stdout,
|
||||
json!({"jsonrpc": "2.0", "id": "startup", "method": "ping"}),
|
||||
)?;
|
||||
return Ok(());
|
||||
}
|
||||
"server/discover" if mode == "legacy-late" => {
|
||||
late_discovery_id = Some(message["id"].clone());
|
||||
}
|
||||
// The first helper makes its version offer only after it receives initialize.
|
||||
"server/discover"
|
||||
if mode == "modern-late"
|
||||
&& !std::path::Path::new("retry-modern").try_exists()? => {}
|
||||
"initialize" if mode == "modern-late" => {
|
||||
std::fs::write("retry-modern", [])?;
|
||||
write_message(
|
||||
&mut stdout,
|
||||
json!({
|
||||
"jsonrpc": "2.0", "id": null,
|
||||
"error": {"code": -32022, "message": "unsupported protocol", "data": {"supported": [MODERN_VERSION]}},
|
||||
}),
|
||||
)?;
|
||||
return Ok(());
|
||||
}
|
||||
"server/discover" if mode == "legacy-silent" => {
|
||||
write_message(
|
||||
&mut stdout,
|
||||
json!({
|
||||
"jsonrpc": "2.0", "method": "notifications/message",
|
||||
"params": {"level": "info", "data": "starting server"},
|
||||
}),
|
||||
)?;
|
||||
}
|
||||
"server/discover" if mode == "legacy-versions" => {
|
||||
write_message(
|
||||
&mut stdout,
|
||||
json!({
|
||||
"jsonrpc": "2.0", "id": message["id"],
|
||||
"error": {"code": -32022, "message": "unsupported protocol", "data": {"supported": [LEGACY_VERSION]}},
|
||||
}),
|
||||
)?;
|
||||
}
|
||||
"server/discover" if is_legacy => {
|
||||
write_message(
|
||||
&mut stdout,
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": message["id"],
|
||||
"error": {"code": -32601, "message": "method not found"},
|
||||
}),
|
||||
)?;
|
||||
if mode == "legacy-reject-and-exit" {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
"server/discover" => {
|
||||
assert!(!initialized);
|
||||
assert_modern_metadata(&message);
|
||||
initialized = true;
|
||||
write_message(
|
||||
&mut stdout,
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": message["id"],
|
||||
"result": {
|
||||
"resultType": "complete",
|
||||
"supportedVersions": [MODERN_VERSION],
|
||||
"capabilities": {"tools": {}, "resources": {}},
|
||||
"_meta": {
|
||||
"io.modelcontextprotocol/serverInfo": {
|
||||
"name": "strict-stdio-test",
|
||||
"version": "1.0.0",
|
||||
},
|
||||
},
|
||||
"ttlMs": 0,
|
||||
"cacheScope": "private",
|
||||
},
|
||||
}),
|
||||
)?;
|
||||
}
|
||||
"initialize" if mode == "legacy-reject-late-initialize" && index != 0 => {
|
||||
write_message(
|
||||
&mut stdout,
|
||||
json!({"jsonrpc": "2.0", "id": message["id"], "error": {
|
||||
"code": -32600, "message": "initialize must be the first request"
|
||||
}}),
|
||||
)?;
|
||||
}
|
||||
"initialize" => {
|
||||
assert!(is_legacy);
|
||||
if mode == "legacy-late" {
|
||||
let id = late_discovery_id
|
||||
.take()
|
||||
.context("initialize must follow discover on the same pipe")?;
|
||||
write_message(
|
||||
&mut stdout,
|
||||
json!({"jsonrpc":"2.0","id":id,"error":{"code":-32601,"message":"Method not found"}}),
|
||||
)?;
|
||||
}
|
||||
if message["method"] == "initialize" {
|
||||
assert_eq!(message["params"]["protocolVersion"], LEGACY_VERSION);
|
||||
}
|
||||
initialized = true;
|
||||
write_message(
|
||||
&mut stdout,
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": message["id"],
|
||||
"result": {
|
||||
"protocolVersion": LEGACY_VERSION,
|
||||
"capabilities": {"tools": {}},
|
||||
"serverInfo": {"name": "legacy-stdio-test", "version": "1.0.0"},
|
||||
},
|
||||
}),
|
||||
)?;
|
||||
}
|
||||
"notifications/initialized" => assert!(is_legacy),
|
||||
"tools/list" => {
|
||||
assert!(initialized);
|
||||
if !is_legacy {
|
||||
assert_modern_metadata(&message);
|
||||
}
|
||||
if mode == "oversized-stdout-legacy" {
|
||||
write!(stdout, "\u{feff}")?;
|
||||
}
|
||||
let description = if oversized {
|
||||
"x".repeat(MAX_MESSAGE_BYTES + 1)
|
||||
} else {
|
||||
"echo a value".to_owned()
|
||||
};
|
||||
let mut result = json!({
|
||||
"tools": [{
|
||||
"name": "echo",
|
||||
"description": description,
|
||||
"inputSchema": {"type": "object"},
|
||||
}],
|
||||
});
|
||||
if !is_legacy {
|
||||
result["resultType"] = json!("complete");
|
||||
result["ttlMs"] = json!(0);
|
||||
result["cacheScope"] = json!("private");
|
||||
}
|
||||
write_message(
|
||||
&mut stdout,
|
||||
json!({"jsonrpc": "2.0", "id": message["id"], "result": result}),
|
||||
)?;
|
||||
}
|
||||
"tools/call" if is_legacy => {
|
||||
assert!(initialized);
|
||||
pending_legacy_call = Some(message["id"].clone());
|
||||
write_message(
|
||||
&mut stdout,
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": "legacy-approval",
|
||||
"method": "elicitation/create",
|
||||
"params": {
|
||||
"message": "Accept the schema defaults",
|
||||
"requestedSchema": {
|
||||
"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": [],
|
||||
},
|
||||
},
|
||||
}),
|
||||
)?;
|
||||
}
|
||||
"tools/call" => {
|
||||
assert!(initialized);
|
||||
assert_modern_metadata(&message);
|
||||
if message.pointer("/params/inputResponses").is_none() {
|
||||
write_message(
|
||||
&mut stdout,
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": message["id"],
|
||||
"result": {
|
||||
"resultType": "input_required",
|
||||
"inputRequests": {
|
||||
"approval": {
|
||||
"method": "elicitation/create",
|
||||
"params": {
|
||||
"mode": "form",
|
||||
"message": "Approve stdio call?",
|
||||
"requestedSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"approved": {"type": "boolean"},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"requestState": "stdio-state",
|
||||
"_meta": {
|
||||
"io.modelcontextprotocol/serverInfo": {
|
||||
"name": "strict-stdio-test",
|
||||
"version": "1.0.0",
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
)?;
|
||||
continue;
|
||||
}
|
||||
|
||||
assert_eq!(message["params"]["requestState"], "stdio-state");
|
||||
assert_eq!(
|
||||
message["params"]["inputResponses"]["approval"]["action"],
|
||||
"accept"
|
||||
);
|
||||
assert_eq!(
|
||||
message["params"]["inputResponses"]["approval"]["content"]["approved"],
|
||||
true
|
||||
);
|
||||
write_message(
|
||||
&mut stdout,
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": message["id"],
|
||||
"result": {
|
||||
"resultType": "complete",
|
||||
"content": [{"type": "text", "text": "modern approved"}],
|
||||
},
|
||||
}),
|
||||
)?;
|
||||
}
|
||||
other => anyhow::bail!("unexpected MCP method {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
1225
codex-rs/rmcp-client/src/bin/test_stdio_server.rs
Normal file
1225
codex-rs/rmcp-client/src/bin/test_stdio_server.rs
Normal file
File diff suppressed because it is too large
Load Diff
599
codex-rs/rmcp-client/src/bin/test_streamable_http_server.rs
Normal file
599
codex-rs/rmcp-client/src/bin/test_streamable_http_server.rs
Normal file
@@ -0,0 +1,599 @@
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::io::ErrorKind;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::Router;
|
||||
use axum::body::Body;
|
||||
use axum::body::to_bytes;
|
||||
use axum::extract::Json;
|
||||
use axum::extract::State;
|
||||
use axum::http::HeaderMap;
|
||||
use axum::http::HeaderValue;
|
||||
use axum::http::Method;
|
||||
use axum::http::Request;
|
||||
use axum::http::StatusCode;
|
||||
use axum::http::header::AUTHORIZATION;
|
||||
use axum::http::header::CONTENT_TYPE;
|
||||
use axum::http::header::HOST;
|
||||
use axum::http::header::WWW_AUTHENTICATE;
|
||||
use axum::middleware;
|
||||
use axum::middleware::Next;
|
||||
use axum::response::Response;
|
||||
use axum::routing::get;
|
||||
use axum::routing::post;
|
||||
use rmcp::ErrorData as McpError;
|
||||
use rmcp::handler::server::ServerHandler;
|
||||
use rmcp::model::CallToolRequestParams;
|
||||
use rmcp::model::CallToolResult;
|
||||
use rmcp::model::JsonObject;
|
||||
use rmcp::model::ListResourceTemplatesResult;
|
||||
use rmcp::model::ListResourcesResult;
|
||||
use rmcp::model::ListToolsResult;
|
||||
use rmcp::model::PaginatedRequestParams;
|
||||
use rmcp::model::ReadResourceRequestParams;
|
||||
use rmcp::model::ReadResourceResult;
|
||||
use rmcp::model::Resource;
|
||||
use rmcp::model::ResourceContents;
|
||||
use rmcp::model::ResourceTemplate;
|
||||
use rmcp::model::ServerCapabilities;
|
||||
use rmcp::model::ServerConfig;
|
||||
use rmcp::model::Tool;
|
||||
use rmcp::model::ToolAnnotations;
|
||||
use rmcp::transport::StreamableHttpServerConfig;
|
||||
use rmcp::transport::StreamableHttpService;
|
||||
use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::task;
|
||||
use tokio::time::sleep;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TestToolServer {
|
||||
tools: Arc<Vec<Tool>>,
|
||||
resources: Arc<Vec<Resource>>,
|
||||
resource_templates: Arc<Vec<ResourceTemplate>>,
|
||||
}
|
||||
|
||||
const MEMO_URI: &str = "memo://codex/example-note";
|
||||
const MEMO_CONTENT: &str = "This is a sample MCP resource served by the rmcp test server.";
|
||||
const MCP_SESSION_ID_HEADER: &str = "mcp-session-id";
|
||||
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";
|
||||
const MAX_MCP_POST_BODY_BYTES: usize = 1024 * 1024;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct PostFailureState {
|
||||
armed_failure: Arc<Mutex<Option<ArmedFailure>>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum ArmedFailureTarget {
|
||||
Initialize,
|
||||
InitializedNotification,
|
||||
Session,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct ArmedFailure {
|
||||
target: ArmedFailureTarget,
|
||||
status: StatusCode,
|
||||
remaining: usize,
|
||||
/// Raw `WWW-Authenticate` challenge header field values returned with the failure.
|
||||
www_authenticate_headers: Vec<HeaderValue>,
|
||||
content_type: Option<HeaderValue>,
|
||||
body: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ArmSessionPostFailureRequest {
|
||||
status: u16,
|
||||
remaining: usize,
|
||||
/// Raw `WWW-Authenticate` challenge header field values to add to the failure.
|
||||
#[serde(default)]
|
||||
www_authenticate_headers: Vec<String>,
|
||||
content_type: Option<String>,
|
||||
body: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct EchoArgs {
|
||||
message: String,
|
||||
#[allow(dead_code)]
|
||||
env_var: Option<String>,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut args = std::env::args_os().skip(1);
|
||||
match args.next().as_deref() {
|
||||
Some(value) if value == std::ffi::OsStr::new("--http-headers-helper") => {
|
||||
if std::env::var_os("MCP_TEST_AMBIENT_SECRET").is_some() {
|
||||
return Err("helper inherited ambient secret".into());
|
||||
}
|
||||
if let Some(invocations) = args.next() {
|
||||
let count = fs::read_to_string(&invocations).unwrap_or_default().len() + 1;
|
||||
fs::write(invocations, "x".repeat(count))?;
|
||||
let header =
|
||||
if args.next().as_deref() == Some(std::ffi::OsStr::new("--authorization")) {
|
||||
"Authorization"
|
||||
} else {
|
||||
"Proxy-Authorization"
|
||||
};
|
||||
println!(
|
||||
r#"{{"{header}":"Bearer gateway-token","X-Helper-Generation":"{count}"}}"#
|
||||
);
|
||||
} else {
|
||||
println!(r#"{{"Proxy-Authorization":"Bearer gateway-token"}}"#);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let bind_addr = parse_bind_addr()?;
|
||||
let post_failure_state = PostFailureState::default();
|
||||
const MAX_BIND_RETRIES: u32 = 20;
|
||||
const BIND_RETRY_DELAY: Duration = Duration::from_millis(50);
|
||||
|
||||
let mut bind_retries = 0;
|
||||
let listener = loop {
|
||||
match tokio::net::TcpListener::bind(&bind_addr).await {
|
||||
Ok(listener) => break listener,
|
||||
Err(err) if err.kind() == ErrorKind::PermissionDenied => {
|
||||
eprintln!(
|
||||
"failed to bind to {bind_addr}: {err}. make sure the process has network access"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
Err(err) if err.kind() == ErrorKind::AddrInUse && bind_retries < MAX_BIND_RETRIES => {
|
||||
bind_retries += 1;
|
||||
sleep(BIND_RETRY_DELAY).await;
|
||||
}
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
};
|
||||
let actual_bind_addr = listener.local_addr()?;
|
||||
if let Ok(bound_addr_file) = std::env::var("MCP_STREAMABLE_HTTP_BOUND_ADDR_FILE") {
|
||||
fs::write(bound_addr_file, actual_bind_addr.to_string())?;
|
||||
}
|
||||
eprintln!("starting rmcp streamable http test server on http://{actual_bind_addr}/mcp");
|
||||
|
||||
let mut transport_config = StreamableHttpServerConfig::default();
|
||||
if !actual_bind_addr.ip().is_loopback() {
|
||||
transport_config
|
||||
.allowed_hosts
|
||||
.push(actual_bind_addr.to_string());
|
||||
transport_config =
|
||||
transport_config.with_allowed_origins([format!("http://{actual_bind_addr}")]);
|
||||
}
|
||||
|
||||
let router = Router::new()
|
||||
.route(
|
||||
SESSION_POST_FAILURE_CONTROL_PATH,
|
||||
post(arm_session_post_failure),
|
||||
)
|
||||
.route(
|
||||
INITIALIZE_POST_FAILURE_CONTROL_PATH,
|
||||
post(arm_initialize_post_failure),
|
||||
)
|
||||
.route(
|
||||
INITIALIZED_NOTIFICATION_POST_FAILURE_CONTROL_PATH,
|
||||
post(arm_initialized_notification_post_failure),
|
||||
)
|
||||
.route(
|
||||
"/.well-known/oauth-authorization-server/mcp",
|
||||
get({
|
||||
move |headers: HeaderMap| async move {
|
||||
let metadata_base = headers
|
||||
.get(HOST)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(|host| format!("http://{host}"))
|
||||
.unwrap_or_else(|| format!("http://{actual_bind_addr}"));
|
||||
#[expect(clippy::expect_used)]
|
||||
Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(
|
||||
serde_json::to_vec(&json!({
|
||||
"issuer": format!("{metadata_base}/mcp"),
|
||||
"authorization_endpoint": format!("{metadata_base}/oauth/authorize"),
|
||||
"token_endpoint": format!("{metadata_base}/oauth/token"),
|
||||
"scopes_supported": [""],
|
||||
})).expect("failed to serialize metadata"),
|
||||
))
|
||||
.expect("valid metadata response")
|
||||
}
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/oauth/token",
|
||||
post(|| async {
|
||||
(
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(json!({
|
||||
"error": "invalid_grant",
|
||||
"error_description": "refresh token expired or revoked",
|
||||
})),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.nest_service(
|
||||
"/mcp",
|
||||
StreamableHttpService::new(
|
||||
|| Ok(TestToolServer::new()),
|
||||
Arc::new(LocalSessionManager::default()),
|
||||
transport_config,
|
||||
),
|
||||
)
|
||||
.layer(middleware::from_fn_with_state(
|
||||
post_failure_state.clone(),
|
||||
fail_mcp_post_when_armed,
|
||||
))
|
||||
.with_state(post_failure_state);
|
||||
|
||||
let router = if let Ok(token) = std::env::var("MCP_EXPECT_BEARER") {
|
||||
let expected = Arc::new(format!("Bearer {token}"));
|
||||
router.layer(middleware::from_fn_with_state(expected, require_bearer))
|
||||
} else {
|
||||
router
|
||||
};
|
||||
let router = if let Ok(token) = std::env::var("MCP_EXPECT_GATEWAY_BEARER") {
|
||||
let expected = Arc::new(format!("Bearer {token}"));
|
||||
router.layer(middleware::from_fn_with_state(
|
||||
expected,
|
||||
require_gateway_bearer,
|
||||
))
|
||||
} else {
|
||||
router
|
||||
};
|
||||
|
||||
axum::serve(listener, router).await?;
|
||||
task::yield_now().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl ServerHandler for TestToolServer {
|
||||
fn get_info(&self) -> ServerConfig {
|
||||
ServerConfig::new(
|
||||
ServerCapabilities::builder()
|
||||
.enable_tools()
|
||||
.enable_tool_list_changed()
|
||||
.enable_resources()
|
||||
.build(),
|
||||
)
|
||||
}
|
||||
|
||||
fn list_tools(
|
||||
&self,
|
||||
_request: Option<PaginatedRequestParams>,
|
||||
_context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
|
||||
) -> impl std::future::Future<Output = Result<ListToolsResult, McpError>> + Send + '_ {
|
||||
let tools = self.tools.clone();
|
||||
async move { Ok(ListToolsResult::with_all_items((*tools).clone())) }
|
||||
}
|
||||
|
||||
fn list_resources(
|
||||
&self,
|
||||
_request: Option<PaginatedRequestParams>,
|
||||
_context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
|
||||
) -> impl std::future::Future<Output = Result<ListResourcesResult, McpError>> + Send + '_ {
|
||||
let resources = self.resources.clone();
|
||||
async move { Ok(ListResourcesResult::with_all_items((*resources).clone())) }
|
||||
}
|
||||
|
||||
async fn list_resource_templates(
|
||||
&self,
|
||||
_request: Option<PaginatedRequestParams>,
|
||||
_context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
|
||||
) -> Result<ListResourceTemplatesResult, McpError> {
|
||||
Ok(ListResourceTemplatesResult::with_all_items(
|
||||
(*self.resource_templates).clone(),
|
||||
))
|
||||
}
|
||||
|
||||
async fn read_resource(
|
||||
&self,
|
||||
ReadResourceRequestParams { uri, .. }: ReadResourceRequestParams,
|
||||
_context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
|
||||
) -> Result<rmcp::model::ReadResourceResponse, McpError> {
|
||||
if uri == MEMO_URI {
|
||||
Ok(
|
||||
ReadResourceResult::new(vec![ResourceContents::TextResourceContents {
|
||||
uri,
|
||||
mime_type: Some("text/plain".to_string()),
|
||||
text: Self::memo_text().to_string(),
|
||||
meta: None,
|
||||
}])
|
||||
.into(),
|
||||
)
|
||||
} else {
|
||||
Err(McpError::resource_not_found(
|
||||
"resource_not_found",
|
||||
Some(json!({ "uri": uri })),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
async fn call_tool(
|
||||
&self,
|
||||
request: CallToolRequestParams,
|
||||
_context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
|
||||
) -> Result<rmcp::model::CallToolResponse, McpError> {
|
||||
match request.name.as_ref() {
|
||||
"echo" => {
|
||||
let args: EchoArgs = match request.arguments {
|
||||
Some(arguments) => serde_json::from_value(serde_json::Value::Object(
|
||||
arguments.into_iter().collect(),
|
||||
))
|
||||
.map_err(|err| McpError::invalid_params(err.to_string(), None))?,
|
||||
None => {
|
||||
return Err(McpError::invalid_params(
|
||||
"missing arguments for echo tool",
|
||||
None,
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let env_snapshot: HashMap<String, String> = std::env::vars().collect();
|
||||
let structured_content = json!({
|
||||
"echo": format!("ECHOING: {}", args.message),
|
||||
"env": env_snapshot.get("MCP_TEST_VALUE"),
|
||||
});
|
||||
|
||||
let mut result = CallToolResult::success(Vec::new());
|
||||
result.structured_content = Some(structured_content);
|
||||
Ok(result.into())
|
||||
}
|
||||
other => Err(McpError::invalid_params(
|
||||
format!("unknown tool: {other}"),
|
||||
None,
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TestToolServer {
|
||||
fn new() -> Self {
|
||||
let tools = vec![Self::echo_tool()];
|
||||
let resources = vec![Self::memo_resource()];
|
||||
let resource_templates = vec![Self::memo_template()];
|
||||
Self {
|
||||
tools: Arc::new(tools),
|
||||
resources: Arc::new(resources),
|
||||
resource_templates: Arc::new(resource_templates),
|
||||
}
|
||||
}
|
||||
|
||||
fn echo_tool() -> Tool {
|
||||
#[expect(clippy::expect_used)]
|
||||
let schema: JsonObject = serde_json::from_value(json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"message": { "type": "string" },
|
||||
"env_var": { "type": "string" }
|
||||
},
|
||||
"required": ["message"],
|
||||
"additionalProperties": false
|
||||
}))
|
||||
.expect("echo tool schema should deserialize");
|
||||
|
||||
let mut tool = Tool::new(
|
||||
Cow::Borrowed("echo"),
|
||||
Cow::Borrowed("Echo back the provided message and include environment data."),
|
||||
Arc::new(schema),
|
||||
);
|
||||
#[expect(clippy::expect_used)]
|
||||
let output_schema: JsonObject = serde_json::from_value(json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"echo": { "type": "string" },
|
||||
"env": {
|
||||
"anyOf": [
|
||||
{ "type": "string" },
|
||||
{ "type": "null" }
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": ["echo", "env"],
|
||||
"additionalProperties": false
|
||||
}))
|
||||
.expect("echo tool output schema should deserialize");
|
||||
tool.output_schema = Some(Arc::new(output_schema));
|
||||
tool.annotations = Some(ToolAnnotations::new().read_only(true));
|
||||
tool
|
||||
}
|
||||
|
||||
fn memo_resource() -> Resource {
|
||||
Resource::new(MEMO_URI, "example-note")
|
||||
.with_title("Example Note")
|
||||
.with_description("A sample MCP resource exposed for integration tests.")
|
||||
.with_mime_type("text/plain")
|
||||
}
|
||||
|
||||
fn memo_template() -> ResourceTemplate {
|
||||
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")
|
||||
}
|
||||
|
||||
fn memo_text() -> &'static str {
|
||||
MEMO_CONTENT
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_bind_addr() -> Result<SocketAddr, Box<dyn std::error::Error>> {
|
||||
let default_addr = "127.0.0.1:3920";
|
||||
let bind_addr = std::env::var("MCP_STREAMABLE_HTTP_BIND_ADDR")
|
||||
.or_else(|_| std::env::var("BIND_ADDR"))
|
||||
.unwrap_or_else(|_| default_addr.to_string());
|
||||
Ok(bind_addr.parse()?)
|
||||
}
|
||||
|
||||
async fn require_bearer(
|
||||
State(expected): State<Arc<String>>,
|
||||
request: Request<Body>,
|
||||
next: Next,
|
||||
) -> Result<Response, StatusCode> {
|
||||
if request.uri().path().contains("/.well-known/") || request.uri().path() == "/oauth/token" {
|
||||
return Ok(next.run(request).await);
|
||||
}
|
||||
if request
|
||||
.headers()
|
||||
.get(AUTHORIZATION)
|
||||
.is_some_and(|value| value.as_bytes() == expected.as_bytes())
|
||||
{
|
||||
Ok(next.run(request).await)
|
||||
} else {
|
||||
Err(StatusCode::UNAUTHORIZED)
|
||||
}
|
||||
}
|
||||
|
||||
async fn require_gateway_bearer(
|
||||
State(expected): State<Arc<String>>,
|
||||
request: Request<Body>,
|
||||
next: Next,
|
||||
) -> Result<Response, StatusCode> {
|
||||
if !request.uri().path().starts_with("/mcp") {
|
||||
return Ok(next.run(request).await);
|
||||
}
|
||||
if request
|
||||
.headers()
|
||||
.get("proxy-authorization")
|
||||
.is_some_and(|value| value.as_bytes() == expected.as_bytes())
|
||||
{
|
||||
Ok(next.run(request).await)
|
||||
} else {
|
||||
Err(StatusCode::UNAUTHORIZED)
|
||||
}
|
||||
}
|
||||
|
||||
async fn arm_session_post_failure(
|
||||
State(state): State<PostFailureState>,
|
||||
Json(request): Json<ArmSessionPostFailureRequest>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
arm_post_failure(state, request, ArmedFailureTarget::Session).await
|
||||
}
|
||||
|
||||
async fn arm_initialize_post_failure(
|
||||
State(state): State<PostFailureState>,
|
||||
Json(request): Json<ArmSessionPostFailureRequest>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
arm_post_failure(state, request, ArmedFailureTarget::Initialize).await
|
||||
}
|
||||
|
||||
async fn arm_initialized_notification_post_failure(
|
||||
State(state): State<PostFailureState>,
|
||||
Json(request): Json<ArmSessionPostFailureRequest>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
arm_post_failure(state, request, ArmedFailureTarget::InitializedNotification).await
|
||||
}
|
||||
|
||||
async fn arm_post_failure(
|
||||
state: PostFailureState,
|
||||
request: ArmSessionPostFailureRequest,
|
||||
target: ArmedFailureTarget,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let status = StatusCode::from_u16(request.status).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let www_authenticate_headers = request
|
||||
.www_authenticate_headers
|
||||
.into_iter()
|
||||
.map(|value| HeaderValue::from_str(&value).map_err(|_| StatusCode::BAD_REQUEST))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let content_type = request
|
||||
.content_type
|
||||
.map(|value| HeaderValue::from_str(&value).map_err(|_| StatusCode::BAD_REQUEST))
|
||||
.transpose()?;
|
||||
let armed_failure = if request.remaining == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(ArmedFailure {
|
||||
target,
|
||||
status,
|
||||
remaining: request.remaining,
|
||||
www_authenticate_headers,
|
||||
content_type,
|
||||
body: request.body,
|
||||
})
|
||||
};
|
||||
*state.armed_failure.lock().await = armed_failure;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn fail_mcp_post_when_armed(
|
||||
State(state): State<PostFailureState>,
|
||||
request: Request<Body>,
|
||||
next: Next,
|
||||
) -> Response {
|
||||
if request.uri().path() != "/mcp" || request.method() != Method::POST {
|
||||
return next.run(request).await;
|
||||
}
|
||||
let (parts, body) = request.into_parts();
|
||||
let body_bytes = match to_bytes(body, MAX_MCP_POST_BODY_BYTES).await {
|
||||
Ok(body_bytes) => body_bytes,
|
||||
Err(_) => {
|
||||
let mut response = Response::new(Body::from("failed to read request body"));
|
||||
*response.status_mut() = StatusCode::BAD_REQUEST;
|
||||
return response;
|
||||
}
|
||||
};
|
||||
let has_session_id = parts.headers.contains_key(MCP_SESSION_ID_HEADER);
|
||||
let mcp_method = request_mcp_method(&body_bytes);
|
||||
|
||||
{
|
||||
let mut armed_failure = state.armed_failure.lock().await;
|
||||
if let Some(failure) = armed_failure.as_mut()
|
||||
&& failure.remaining > 0
|
||||
&& match failure.target {
|
||||
ArmedFailureTarget::Initialize => !has_session_id,
|
||||
ArmedFailureTarget::InitializedNotification => {
|
||||
has_session_id && mcp_method.as_deref() == Some("notifications/initialized")
|
||||
}
|
||||
ArmedFailureTarget::Session => {
|
||||
has_session_id && mcp_method.as_deref() != Some("notifications/initialized")
|
||||
}
|
||||
}
|
||||
{
|
||||
failure.remaining -= 1;
|
||||
let status = failure.status;
|
||||
let www_authenticate_headers = failure.www_authenticate_headers.clone();
|
||||
let content_type = failure.content_type.clone();
|
||||
let body = failure
|
||||
.body
|
||||
.clone()
|
||||
.unwrap_or_else(|| format!("forced session failure with status {status}"));
|
||||
if failure.remaining == 0 {
|
||||
*armed_failure = None;
|
||||
}
|
||||
let mut response = Response::new(Body::from(body));
|
||||
*response.status_mut() = status;
|
||||
if let Some(content_type) = content_type {
|
||||
response.headers_mut().insert(CONTENT_TYPE, content_type);
|
||||
}
|
||||
for www_authenticate_header in www_authenticate_headers {
|
||||
response
|
||||
.headers_mut()
|
||||
.append(WWW_AUTHENTICATE, www_authenticate_header);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
next.run(Request::from_parts(parts, Body::from(body_bytes)))
|
||||
.await
|
||||
}
|
||||
|
||||
fn request_mcp_method(body: &[u8]) -> Option<String> {
|
||||
serde_json::from_slice::<Value>(body)
|
||||
.ok()?
|
||||
.get("method")?
|
||||
.as_str()
|
||||
.map(ToString::to_string)
|
||||
}
|
||||
Reference in New Issue
Block a user