From fb6e94fb5b612ff0d22dfba42bd9a5208b3b5408 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Sun, 1 Feb 2026 15:46:54 -0800 Subject: [PATCH] feat: replace custom mcp-types crate with equivalents from rmcp --- codex-rs/Cargo.lock | 24 +- codex-rs/Cargo.toml | 2 - codex-rs/app-server-protocol/Cargo.toml | 1 - .../app-server-protocol/src/protocol/v2.rs | 9 +- codex-rs/app-server-test-client/Cargo.lock | 11 - codex-rs/app-server/Cargo.toml | 2 - .../app-server/src/bespoke_event_handling.rs | 15 +- codex-rs/core/Cargo.toml | 7 +- codex-rs/core/src/codex.rs | 55 +- codex-rs/core/src/config/mod.rs | 32 +- codex-rs/core/src/mcp/mod.rs | 111 +- codex-rs/core/src/mcp_connection_manager.rs | 99 +- codex-rs/core/src/mcp_tool_call.rs | 9 +- codex-rs/core/src/tools/context.rs | 2 +- codex-rs/core/src/tools/handlers/mcp.rs | 12 +- .../core/src/tools/handlers/mcp_resource.rs | 66 +- codex-rs/core/src/tools/router.rs | 3 +- codex-rs/core/src/tools/spec.rs | 262 +- codex-rs/core/tests/suite/rmcp_client.rs | 13 +- codex-rs/exec/Cargo.toml | 3 +- .../src/event_processor_with_human_output.rs | 3 +- codex-rs/exec/src/exec_events.rs | 2 +- .../tests/event_processor_with_json_output.rs | 19 +- codex-rs/mcp-server/Cargo.toml | 2 +- codex-rs/mcp-server/src/codex_tool_config.rs | 77 +- codex-rs/mcp-server/src/codex_tool_runner.rs | 33 +- codex-rs/mcp-server/src/error_code.rs | 2 - codex-rs/mcp-server/src/exec_approval.rs | 37 +- codex-rs/mcp-server/src/lib.rs | 27 +- codex-rs/mcp-server/src/message_processor.rs | 529 ++-- codex-rs/mcp-server/src/outgoing_message.rs | 83 +- codex-rs/mcp-server/src/patch_approval.rs | 32 +- codex-rs/mcp-server/tests/common/Cargo.toml | 2 +- codex-rs/mcp-server/tests/common/lib.rs | 6 +- .../mcp-server/tests/common/mcp_process.rs | 168 +- codex-rs/mcp-server/tests/suite/codex_tool.rs | 159 +- codex-rs/mcp-types/BUILD.bazel | 6 - codex-rs/mcp-types/Cargo.toml | 14 - codex-rs/mcp-types/README.md | 8 - codex-rs/mcp-types/check_lib_rs.py | 21 - codex-rs/mcp-types/generate_mcp_types.py | 780 ----- .../mcp-types/schema/2025-03-26/schema.json | 2138 -------------- .../mcp-types/schema/2025-06-18/schema.json | 2516 ----------------- codex-rs/mcp-types/src/lib.rs | 1714 ----------- codex-rs/mcp-types/tests/all.rs | 3 - codex-rs/mcp-types/tests/suite/initialize.rs | 70 - codex-rs/mcp-types/tests/suite/mod.rs | 3 - .../tests/suite/progress_notification.rs | 43 - codex-rs/protocol/Cargo.toml | 1 - codex-rs/protocol/src/approvals.rs | 3 +- codex-rs/protocol/src/lib.rs | 1 + codex-rs/protocol/src/mcp.rs | 115 + codex-rs/protocol/src/models.rs | 77 +- codex-rs/protocol/src/protocol.rs | 10 +- codex-rs/rmcp-client/Cargo.toml | 1 - .../rmcp-client/src/logging_client_handler.rs | 7 +- codex-rs/rmcp-client/src/rmcp_client.rs | 101 +- codex-rs/rmcp-client/src/utils.rs | 84 - codex-rs/rmcp-client/tests/resources.rs | 79 +- codex-rs/tui/Cargo.toml | 2 +- .../tui/src/bottom_pane/approval_overlay.rs | 2 +- ...et__tests__binary_size_ideal_response.snap | 2 +- codex-rs/tui/src/history_cell.rs | 185 +- codex-rs/tui/src/lib.rs | 20 + .../tui/tests/suite/no_panic_on_startup.rs | 5 +- 65 files changed, 1280 insertions(+), 8650 deletions(-) delete mode 100644 codex-rs/mcp-server/src/error_code.rs delete mode 100644 codex-rs/mcp-types/BUILD.bazel delete mode 100644 codex-rs/mcp-types/Cargo.toml delete mode 100644 codex-rs/mcp-types/README.md delete mode 100755 codex-rs/mcp-types/check_lib_rs.py delete mode 100755 codex-rs/mcp-types/generate_mcp_types.py delete mode 100644 codex-rs/mcp-types/schema/2025-03-26/schema.json delete mode 100644 codex-rs/mcp-types/schema/2025-06-18/schema.json delete mode 100644 codex-rs/mcp-types/src/lib.rs delete mode 100644 codex-rs/mcp-types/tests/all.rs delete mode 100644 codex-rs/mcp-types/tests/suite/initialize.rs delete mode 100644 codex-rs/mcp-types/tests/suite/mod.rs delete mode 100644 codex-rs/mcp-types/tests/suite/progress_notification.rs create mode 100644 codex-rs/protocol/src/mcp.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index cbe8aa6937..bf93e45415 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1100,7 +1100,6 @@ dependencies = [ "codex-utils-absolute-path", "codex-utils-json-to-toml", "core_test_support", - "mcp-types", "os_info", "pretty_assertions", "rmcp", @@ -1126,7 +1125,6 @@ dependencies = [ "clap", "codex-protocol", "codex-utils-absolute-path", - "mcp-types", "pretty_assertions", "schemars 0.8.22", "serde", @@ -1423,7 +1421,6 @@ dependencies = [ "landlock", "libc", "maplit", - "mcp-types", "multimap", "once_cell", "openssl-sys", @@ -1435,6 +1432,7 @@ dependencies = [ "regex", "regex-lite", "reqwest", + "rmcp", "schemars 0.8.22", "seccompiler", "serde", @@ -1498,10 +1496,10 @@ dependencies = [ "codex-utils-cargo-bin", "core_test_support", "libc", - "mcp-types", "owo-colors", "predicates", "pretty_assertions", + "rmcp", "serde", "serde_json", "shlex", @@ -1694,10 +1692,10 @@ dependencies = [ "codex-protocol", "codex-utils-json-to-toml", "core_test_support", - "mcp-types", "mcp_test_support", "os_info", "pretty_assertions", + "rmcp", "schemars 0.8.22", "serde", "serde_json", @@ -1806,7 +1804,6 @@ dependencies = [ "icu_decimal", "icu_locale_core", "icu_provider", - "mcp-types", "mime_guess", "pretty_assertions", "schemars 0.8.22", @@ -1850,7 +1847,6 @@ dependencies = [ "codex-utils-home-dir", "futures", "keyring", - "mcp-types", "oauth2", "pretty_assertions", "reqwest", @@ -1942,7 +1938,6 @@ dependencies = [ "itertools 0.14.0", "lazy_static", "libc", - "mcp-types", "pathdiff", "pretty_assertions", "pulldown-cmark", @@ -1951,6 +1946,7 @@ dependencies = [ "ratatui-macros", "regex-lite", "reqwest", + "rmcp", "serde", "serde_json", "serial_test", @@ -4662,16 +4658,6 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b3eede3bdf92f3b4f9dc04072a9ce5ab557d5ec9038773bf9ffcd5588b3cc05b" -[[package]] -name = "mcp-types" -version = "0.0.0" -dependencies = [ - "schemars 0.8.22", - "serde", - "serde_json", - "ts-rs", -] - [[package]] name = "mcp_test_support" version = "0.0.0" @@ -4681,9 +4667,9 @@ dependencies = [ "codex-mcp-server", "codex-utils-cargo-bin", "core_test_support", - "mcp-types", "os_info", "pretty_assertions", + "rmcp", "serde", "serde_json", "shlex", diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 84210838fc..24ad845b17 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -27,7 +27,6 @@ members = [ "lmstudio", "login", "mcp-server", - "mcp-types", "network-proxy", "ollama", "process-hardening", @@ -110,7 +109,6 @@ codex-utils-string = { path = "utils/string" } codex-windows-sandbox = { path = "windows-sandbox-rs" } core_test_support = { path = "core/tests/common" } exec_server_test_support = { path = "exec-server/tests/common" } -mcp-types = { path = "mcp-types" } mcp_test_support = { path = "mcp-server/tests/common" } # External diff --git a/codex-rs/app-server-protocol/Cargo.toml b/codex-rs/app-server-protocol/Cargo.toml index 1c21bd6ea0..b3ccfee47c 100644 --- a/codex-rs/app-server-protocol/Cargo.toml +++ b/codex-rs/app-server-protocol/Cargo.toml @@ -16,7 +16,6 @@ anyhow = { workspace = true } clap = { workspace = true, features = ["derive"] } codex-protocol = { workspace = true } codex-utils-absolute-path = { workspace = true } -mcp-types = { workspace = true } schemars = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index f99659cd4d..0fdfb3a8b5 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -14,6 +14,9 @@ use codex_protocol::config_types::Verbosity; use codex_protocol::config_types::WebSearchMode; use codex_protocol::items::AgentMessageContent as CoreAgentMessageContent; use codex_protocol::items::TurnItem as CoreTurnItem; +use codex_protocol::mcp::Resource as McpResource; +use codex_protocol::mcp::ResourceTemplate as McpResourceTemplate; +use codex_protocol::mcp::Tool as McpTool; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::parse_command::ParsedCommand as CoreParsedCommand; @@ -40,10 +43,6 @@ use codex_protocol::user_input::ByteRange as CoreByteRange; use codex_protocol::user_input::TextElement as CoreTextElement; use codex_protocol::user_input::UserInput as CoreUserInput; use codex_utils_absolute_path::AbsolutePathBuf; -use mcp_types::ContentBlock as McpContentBlock; -use mcp_types::Resource as McpResource; -use mcp_types::ResourceTemplate as McpResourceTemplate; -use mcp_types::Tool as McpTool; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; @@ -2336,7 +2335,7 @@ impl From for CollabAgentState { #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] pub struct McpToolCallResult { - pub content: Vec, + pub content: Vec, pub structured_content: Option, } diff --git a/codex-rs/app-server-test-client/Cargo.lock b/codex-rs/app-server-test-client/Cargo.lock index 1720850cd2..c6e4241d2c 100644 --- a/codex-rs/app-server-test-client/Cargo.lock +++ b/codex-rs/app-server-test-client/Cargo.lock @@ -175,7 +175,6 @@ dependencies = [ "base64", "icu_decimal", "icu_locale_core", - "mcp-types", "mime_guess", "serde", "serde_json", @@ -521,16 +520,6 @@ version = "0.4.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432" -[[package]] -name = "mcp-types" -version = "0.45.0" -source = "git+https://github.com/openai/codex.git?tag=rust-v0.45.0#a7c7869c23f88f6c468281e6f438ba4a91b81f26" -dependencies = [ - "serde", - "serde_json", - "ts-rs", -] - [[package]] name = "memchr" version = "2.7.6" diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index 11c57ebbc8..778d57bab0 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -35,7 +35,6 @@ codex-utils-json-to-toml = { workspace = true } chrono = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } -mcp-types = { workspace = true } tempfile = { workspace = true } time = { workspace = true } toml = { workspace = true } @@ -60,7 +59,6 @@ axum = { workspace = true, default-features = false, features = [ base64 = { workspace = true } codex-execpolicy = { workspace = true } core_test_support = { workspace = true } -mcp-types = { workspace = true } os_info = { workspace = true } pretty_assertions = { workspace = true } rmcp = { workspace = true, default-features = false, features = [ diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index bf8fad3a9c..55b185e5a8 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -1841,12 +1841,11 @@ mod tests { use codex_core::protocol::RateLimitWindow; use codex_core::protocol::TokenUsage; use codex_core::protocol::TokenUsageInfo; + use codex_protocol::mcp::CallToolResult; use codex_protocol::plan_tool::PlanItemArg; use codex_protocol::plan_tool::StepStatus; - use mcp_types::CallToolResult; - use mcp_types::ContentBlock; - use mcp_types::TextContent; use pretty_assertions::assert_eq; + use rmcp::model::Content; use serde_json::Value as JsonValue; use std::collections::HashMap; use std::time::Duration; @@ -2374,15 +2373,15 @@ mod tests { #[tokio::test] async fn test_construct_mcp_tool_call_end_notification_success() { - let content = vec![ContentBlock::TextContent(TextContent { - annotations: None, - text: "{\"resources\":[]}".to_string(), - r#type: "text".to_string(), - })]; + let content = vec![ + serde_json::to_value(Content::text("{\"resources\":[]}")) + .expect("content should serialize"), + ]; let result = CallToolResult { content: content.clone(), is_error: Some(false), structured_content: None, + meta: None, }; let end_event = McpToolCallEndEvent { diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index 66ed20a435..b1c7abf245 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -55,7 +55,6 @@ indexmap = { workspace = true } indoc = { workspace = true } keyring = { workspace = true, features = ["crypto-rust"] } libc = { workspace = true } -mcp-types = { workspace = true } multimap = { workspace = true } once_cell = { workspace = true } os_info = { workspace = true } @@ -63,6 +62,12 @@ rand = { workspace = true } regex = { workspace = true } regex-lite = { workspace = true } reqwest = { workspace = true, features = ["json", "stream"] } +rmcp = { workspace = true, default-features = false, features = [ + "base64", + "macros", + "schemars", + "server", +] } schemars = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 29b02c006a..7b4777ad23 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -50,6 +50,7 @@ use codex_protocol::dynamic_tools::DynamicToolSpec; use codex_protocol::items::PlanItem; use codex_protocol::items::TurnItem; use codex_protocol::items::UserMessageItem; +use codex_protocol::mcp::CallToolResult; use codex_protocol::models::BaseInstructions; use codex_protocol::openai_models::ModelInfo; use codex_protocol::protocol::FileChange; @@ -71,14 +72,12 @@ use codex_rmcp_client::OAuthCredentialsStoreMode; use futures::future::BoxFuture; use futures::prelude::*; use futures::stream::FuturesOrdered; -use mcp_types::CallToolResult; -use mcp_types::ListResourceTemplatesRequestParams; -use mcp_types::ListResourceTemplatesResult; -use mcp_types::ListResourcesRequestParams; -use mcp_types::ListResourcesResult; -use mcp_types::ReadResourceRequestParams; -use mcp_types::ReadResourceResult; -use mcp_types::RequestId; +use rmcp::model::ListResourceTemplatesResult; +use rmcp::model::ListResourcesResult; +use rmcp::model::PaginatedRequestParam; +use rmcp::model::ReadResourceRequestParam; +use rmcp::model::ReadResourceResult; +use rmcp::model::RequestId; use serde_json; use serde_json::Value; use tokio::sync::Mutex; @@ -2202,7 +2201,7 @@ impl Session { pub async fn list_resources( &self, server: &str, - params: Option, + params: Option, ) -> anyhow::Result { self.services .mcp_connection_manager @@ -2215,7 +2214,7 @@ impl Session { pub async fn list_resource_templates( &self, server: &str, - params: Option, + params: Option, ) -> anyhow::Result { self.services .mcp_connection_manager @@ -2228,7 +2227,7 @@ impl Session { pub async fn read_resource( &self, server: &str, - params: ReadResourceRequestParams, + params: ReadResourceRequestParam, ) -> anyhow::Result { self.services .mcp_connection_manager @@ -2555,10 +2554,10 @@ mod handlers { use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::Settings; use codex_protocol::dynamic_tools::DynamicToolResponse; + use codex_protocol::mcp::RequestId as ProtocolRequestId; use codex_protocol::user_input::UserInput; use codex_rmcp_client::ElicitationAction; use codex_rmcp_client::ElicitationResponse; - use mcp_types::RequestId; use std::path::PathBuf; use std::sync::Arc; use tracing::info; @@ -2729,7 +2728,7 @@ mod handlers { pub async fn resolve_elicitation( sess: &Arc, server_name: String, - request_id: RequestId, + request_id: ProtocolRequestId, decision: codex_protocol::approvals::ElicitationAction, ) { let action = match decision { @@ -2744,6 +2743,12 @@ mod handlers { ElicitationAction::Decline | ElicitationAction::Cancel => None, }; let response = ElicitationResponse { action, content }; + let request_id = match request_id { + ProtocolRequestId::String(value) => { + rmcp::model::NumberOrString::String(std::sync::Arc::from(value)) + } + ProtocolRequestId::Integer(value) => rmcp::model::NumberOrString::Number(value), + }; if let Err(err) = sess .resolve_elicitation(server_name, request_id, response) .await @@ -4536,8 +4541,7 @@ mod tests { use std::time::Duration; use tokio::time::sleep; - use mcp_types::ContentBlock; - use mcp_types::TextContent; + use codex_protocol::mcp::CallToolResult as McpCallToolResult; use pretty_assertions::assert_eq; use serde::Deserialize; use serde_json::json; @@ -5121,7 +5125,7 @@ mod tests { #[test] fn prefers_structured_content_when_present() { - let ctr = CallToolResult { + let ctr = McpCallToolResult { // Content present but should be ignored because structured_content is set. content: vec![text_block("ignored")], is_error: None, @@ -5129,6 +5133,7 @@ mod tests { "ok": true, "value": 42 })), + meta: None, }; let got = FunctionCallOutputPayload::from(&ctr); @@ -5167,10 +5172,11 @@ mod tests { #[test] fn falls_back_to_content_when_structured_is_null() { - let ctr = CallToolResult { + let ctr = McpCallToolResult { content: vec![text_block("hello"), text_block("world")], is_error: None, structured_content: Some(serde_json::Value::Null), + meta: None, }; let got = FunctionCallOutputPayload::from(&ctr); @@ -5186,10 +5192,11 @@ mod tests { #[test] fn success_flag_reflects_is_error_true() { - let ctr = CallToolResult { + let ctr = McpCallToolResult { content: vec![text_block("unused")], is_error: Some(true), structured_content: Some(json!({ "message": "bad" })), + meta: None, }; let got = FunctionCallOutputPayload::from(&ctr); @@ -5204,10 +5211,11 @@ mod tests { #[test] fn success_flag_true_with_no_error_and_content_used() { - let ctr = CallToolResult { + let ctr = McpCallToolResult { content: vec![text_block("alpha")], is_error: Some(false), structured_content: None, + meta: None, }; let got = FunctionCallOutputPayload::from(&ctr); @@ -5258,11 +5266,10 @@ mod tests { } } - fn text_block(s: &str) -> ContentBlock { - ContentBlock::TextContent(TextContent { - annotations: None, - text: s.to_string(), - r#type: "text".to_string(), + fn text_block(s: &str) -> serde_json::Value { + json!({ + "type": "text", + "text": s, }) } diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 8a53f388b9..6fef8cff11 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -417,7 +417,7 @@ impl ConfigBuilder { fallback_cwd, } = self; let codex_home = codex_home.map_or_else(find_codex_home, std::io::Result::Ok)?; - let cli_overrides = cli_overrides.unwrap_or_default(); + let mut cli_overrides = cli_overrides.unwrap_or_default(); let mut harness_overrides = harness_overrides.unwrap_or_default(); let loader_overrides = loader_overrides.unwrap_or_default(); let cwd_override = harness_overrides.cwd.as_deref().or(fallback_cwd.as_deref()); @@ -426,6 +426,36 @@ impl ConfigBuilder { None => AbsolutePathBuf::current_dir()?, }; harness_overrides.cwd = Some(cwd.to_path_buf()); + + // Support `-c model_instructions_file=...` by eagerly reading the file + // and translating it into a `base_instructions` override. This keeps + // the behavior consistent across all entrypoints that use + // `ConfigBuilder`. + if harness_overrides.base_instructions.is_none() { + let mut model_instructions_file_override = None; + for (key, value) in &cli_overrides { + if key == "model_instructions_file" { + model_instructions_file_override = Some(value.clone()); + } + } + + if let Some(value) = model_instructions_file_override { + cli_overrides.retain(|(key, _)| key != "model_instructions_file"); + let TomlValue::String(path) = value else { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "model_instructions_file override must be a string", + )); + }; + + let path = AbsolutePathBuf::resolve_path_against_base(path, cwd.as_path())?; + if let Some(contents) = + Config::try_read_non_empty_file(Some(&path), "model instructions file")? + { + harness_overrides.base_instructions = Some(contents); + } + } + } let config_layer_stack = load_config_layers_state( &codex_home, Some(cwd), diff --git a/codex-rs/core/src/mcp/mod.rs b/codex-rs/core/src/mcp/mod.rs index 12c61ddaf1..42001ec11c 100644 --- a/codex-rs/core/src/mcp/mod.rs +++ b/codex-rs/core/src/mcp/mod.rs @@ -9,9 +9,12 @@ use std::path::PathBuf; use std::time::Duration; use async_channel::unbounded; +use codex_protocol::mcp::Resource; +use codex_protocol::mcp::ResourceTemplate; +use codex_protocol::mcp::Tool; use codex_protocol::protocol::McpListToolsResponseEvent; use codex_protocol::protocol::SandboxPolicy; -use mcp_types::Tool as McpTool; +use serde_json::Value; use tokio_util::sync::CancellationToken; use crate::AuthManager; @@ -201,8 +204,8 @@ pub fn split_qualified_tool_name(qualified_name: &str) -> Option<(String, String } pub fn group_tools_by_server( - tools: &HashMap, -) -> HashMap> { + tools: &HashMap, +) -> HashMap> { let mut grouped = HashMap::new(); for (qualified_name, tool) in tools { if let Some((server_name, tool_name)) = split_qualified_tool_name(qualified_name) { @@ -230,11 +233,85 @@ pub(crate) async fn collect_mcp_snapshot_from_manager( .map(|(name, entry)| (name.clone(), entry.auth_status)) .collect(); + let tools = tools + .into_iter() + .filter_map(|(name, tool)| { + let tool_value = serde_json::to_value(tool.tool).ok()?; + let tool = serde_json::from_value::(tool_value).ok()?; + Some((name, tool)) + }) + .collect(); + + let resources = resources + .into_iter() + .map(|(name, resources)| { + let resources = resources + .into_iter() + .filter_map(|resource| match serde_json::to_value(resource) { + Ok(value) => match serde_json::from_value::(value.clone()) { + Ok(resource) => Some(resource), + Err(err) => { + let (uri, resource_name) = match value { + Value::Object(mut obj) => ( + obj.remove("uri").and_then(|v| v.as_str().map(ToString::to_string)), + obj.remove("name").and_then(|v| v.as_str().map(ToString::to_string)), + ), + _ => (None, None), + }; + + tracing::warn!( + "Failed to deserialize MCP resource (uri={uri:?}, name={resource_name:?}): {err}" + ); + None + } + }, + Err(err) => { + tracing::warn!("Failed to serialize MCP resource: {err}"); + None + } + }) + .collect::>(); + (name, resources) + }) + .collect(); + + let resource_templates = resource_templates + .into_iter() + .map(|(name, templates)| { + let templates = templates + .into_iter() + .filter_map(|template| match serde_json::to_value(template) { + Ok(value) => match serde_json::from_value::(value.clone()) { + Ok(template) => Some(template), + Err(err) => { + let (uri_template, template_name) = match value { + Value::Object(mut obj) => ( + obj.remove("uriTemplate") + .or_else(|| obj.remove("uri_template")) + .and_then(|v| v.as_str().map(ToString::to_string)), + obj.remove("name").and_then(|v| v.as_str().map(ToString::to_string)), + ), + _ => (None, None), + }; + + tracing::warn!( + "Failed to deserialize MCP resource template (uri_template={uri_template:?}, name={template_name:?}): {err}" + ); + None + } + }, + Err(err) => { + tracing::warn!("Failed to serialize MCP resource template: {err}"); + None + } + }) + .collect::>(); + (name, templates) + }) + .collect(); + McpListToolsResponseEvent { - tools: tools - .into_iter() - .map(|(name, tool)| (name, tool.tool)) - .collect(), + tools, resources, resource_templates, auth_statuses, @@ -244,21 +321,17 @@ pub(crate) async fn collect_mcp_snapshot_from_manager( #[cfg(test)] mod tests { use super::*; - use mcp_types::ToolInputSchema; use pretty_assertions::assert_eq; - - fn make_tool(name: &str) -> McpTool { - McpTool { - annotations: None, - description: None, - input_schema: ToolInputSchema { - properties: None, - required: None, - r#type: "object".to_string(), - }, + fn make_tool(name: &str) -> Tool { + Tool { name: name.to_string(), - output_schema: None, title: None, + description: None, + input_schema: serde_json::json!({"type": "object", "properties": {}}), + output_schema: None, + annotations: None, + icons: None, + meta: None, } } diff --git a/codex-rs/core/src/mcp_connection_manager.rs b/codex-rs/core/src/mcp_connection_manager.rs index 1b5048ab0c..16637211ba 100644 --- a/codex-rs/core/src/mcp_connection_manager.rs +++ b/codex-rs/core/src/mcp_connection_manager.rs @@ -23,6 +23,8 @@ use async_channel::Sender; use codex_async_utils::CancelErr; use codex_async_utils::OrCancelExt; use codex_protocol::approvals::ElicitationRequestEvent; +use codex_protocol::mcp::CallToolResult; +use codex_protocol::mcp::RequestId as ProtocolRequestId; use codex_protocol::protocol::Event; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::McpStartupCompleteEvent; @@ -37,22 +39,23 @@ use codex_rmcp_client::SendElicitation; use futures::future::BoxFuture; use futures::future::FutureExt; use futures::future::Shared; -use mcp_types::ClientCapabilities; -use mcp_types::Implementation; -use mcp_types::ListResourceTemplatesRequestParams; -use mcp_types::ListResourceTemplatesResult; -use mcp_types::ListResourcesRequestParams; -use mcp_types::ListResourcesResult; -use mcp_types::ReadResourceRequestParams; -use mcp_types::ReadResourceResult; -use mcp_types::RequestId; -use mcp_types::Resource; -use mcp_types::ResourceTemplate; -use mcp_types::Tool; +use rmcp::model::ClientCapabilities; +use rmcp::model::ElicitationCapability; +use rmcp::model::Implementation; +use rmcp::model::InitializeRequestParam; +use rmcp::model::ListResourceTemplatesResult; +use rmcp::model::ListResourcesResult; +use rmcp::model::PaginatedRequestParam; +use rmcp::model::ProtocolVersion; +use rmcp::model::ReadResourceRequestParam; +use rmcp::model::ReadResourceResult; +use rmcp::model::RequestId; +use rmcp::model::Resource; +use rmcp::model::ResourceTemplate; +use rmcp::model::Tool; use serde::Deserialize; use serde::Serialize; -use serde_json::json; use sha1::Digest; use sha1::Sha1; use tokio::sync::Mutex; @@ -198,7 +201,14 @@ impl ElicitationRequestManager { id: "mcp_elicitation_request".to_string(), msg: EventMsg::ElicitationRequest(ElicitationRequestEvent { server_name, - id, + id: match id.clone() { + rmcp::model::NumberOrString::String(value) => { + ProtocolRequestId::String(value.to_string()) + } + rmcp::model::NumberOrString::Number(value) => { + ProtocolRequestId::Integer(value) + } + }, message: elicitation.message, }), }) @@ -493,7 +503,7 @@ impl McpConnectionManager { let mut cursor: Option = None; loop { - let params = cursor.as_ref().map(|next| ListResourcesRequestParams { + let params = cursor.as_ref().map(|next| PaginatedRequestParam { cursor: Some(next.clone()), }); let response = match client.list_resources(params, timeout).await { @@ -558,11 +568,9 @@ impl McpConnectionManager { let mut cursor: Option = None; loop { - let params = cursor - .as_ref() - .map(|next| ListResourceTemplatesRequestParams { - cursor: Some(next.clone()), - }); + let params = cursor.as_ref().map(|next| PaginatedRequestParam { + cursor: Some(next.clone()), + }); let response = match client.list_resource_templates(params, timeout).await { Ok(result) => result, Err(err) => return (server_name_cloned, Err(err)), @@ -615,7 +623,7 @@ impl McpConnectionManager { server: &str, tool: &str, arguments: Option, - ) -> Result { + ) -> Result { let client = self.client_by_name(server).await?; if !client.tool_filter.allows(tool) { return Err(anyhow!( @@ -623,18 +631,22 @@ impl McpConnectionManager { )); } - client + let result = client .client .call_tool(tool.to_string(), arguments, client.tool_timeout) .await - .with_context(|| format!("tool call failed for `{server}/{tool}`")) + .with_context(|| format!("tool call failed for `{server}/{tool}`"))?; + + serde_json::to_value(result) + .and_then(serde_json::from_value) + .context("failed to convert MCP tool result") } /// List resources from the specified server. pub async fn list_resources( &self, server: &str, - params: Option, + params: Option, ) -> Result { let managed = self.client_by_name(server).await?; let timeout = managed.tool_timeout; @@ -650,7 +662,7 @@ impl McpConnectionManager { pub async fn list_resource_templates( &self, server: &str, - params: Option, + params: Option, ) -> Result { let managed = self.client_by_name(server).await?; let client = managed.client.clone(); @@ -666,7 +678,7 @@ impl McpConnectionManager { pub async fn read_resource( &self, server: &str, - params: ReadResourceRequestParams, + params: ReadResourceRequestParam, ) -> Result { let managed = self.client_by_name(server).await?; let client = managed.client.clone(); @@ -849,25 +861,25 @@ async fn start_server_task( tx_event: Sender, elicitation_requests: ElicitationRequestManager, ) -> Result { - let params = mcp_types::InitializeRequestParams { + let params = InitializeRequestParam { capabilities: ClientCapabilities { experimental: None, roots: None, sampling: None, // https://modelcontextprotocol.io/specification/2025-06-18/client/elicitation#capabilities // indicates this should be an empty object. - elicitation: Some(json!({})), + elicitation: Some(ElicitationCapability { + schema_validation: None, + }), }, client_info: Implementation { name: "codex-mcp-client".to_owned(), version: env!("CARGO_PKG_VERSION").to_owned(), title: Some("Codex".into()), - // This field is used by Codex when it is an MCP - // server: it should not be used when Codex is - // an MCP client. - user_agent: None, + icons: None, + website_url: None, }, - protocol_version: mcp_types::MCP_SCHEMA_VERSION.to_owned(), + protocol_version: ProtocolVersion::V_2025_06_18, }; let send_elicitation = elicitation_requests.make_sender(server_name.clone(), tx_event); @@ -964,7 +976,7 @@ async fn list_tools_for_client( } ToolInfo { server_name: server_name.to_owned(), - tool_name: tool_def.name.clone(), + tool_name: tool_def.name.to_string(), tool: tool_def, connector_id: tool.connector_id, connector_name, @@ -1047,24 +1059,23 @@ mod mcp_init_error_display_tests {} mod tests { use super::*; use codex_protocol::protocol::McpAuthStatus; - use mcp_types::ToolInputSchema; + use rmcp::model::JsonObject; use std::collections::HashSet; + use std::sync::Arc; fn create_test_tool(server_name: &str, tool_name: &str) -> ToolInfo { ToolInfo { server_name: server_name.to_string(), tool_name: tool_name.to_string(), tool: Tool { - annotations: None, - description: Some(format!("Test tool: {tool_name}")), - input_schema: ToolInputSchema { - properties: None, - required: None, - r#type: "object".to_string(), - }, - name: tool_name.to_string(), - output_schema: None, + name: tool_name.to_string().into(), title: None, + description: Some(format!("Test tool: {tool_name}").into()), + input_schema: Arc::new(JsonObject::default()), + output_schema: None, + annotations: None, + icons: None, + meta: None, }, connector_id: None, connector_name: None, diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index 6425392fb5..75248f34cc 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -10,6 +10,7 @@ use crate::protocol::EventMsg; use crate::protocol::McpInvocation; use crate::protocol::McpToolCallBeginEvent; use crate::protocol::McpToolCallEndEvent; +use codex_protocol::mcp::CallToolResult; use codex_protocol::models::FunctionCallOutputPayload; use codex_protocol::models::ResponseInputItem; use codex_protocol::protocol::AskForApproval; @@ -18,7 +19,7 @@ use codex_protocol::request_user_input::RequestUserInputArgs; use codex_protocol::request_user_input::RequestUserInputQuestion; use codex_protocol::request_user_input::RequestUserInputQuestionOption; use codex_protocol::request_user_input::RequestUserInputResponse; -use mcp_types::ToolAnnotations; +use rmcp::model::ToolAnnotations; use std::sync::Arc; /// Handles the specified tool call dispatches the appropriate @@ -72,7 +73,7 @@ pub(crate) async fn handle_mcp_tool_call( .await; let start = Instant::now(); - let result = sess + let result: Result = sess .call_tool(&server, &tool_name, arguments_value.clone()) .await .map_err(|e| format!("tool call error: {e:?}")); @@ -134,7 +135,7 @@ pub(crate) async fn handle_mcp_tool_call( let start = Instant::now(); // Perform the tool call. - let result = sess + let result: Result = sess .call_tool(&server, &tool_name, arguments_value.clone()) .await .map_err(|e| format!("tool call error: {e:?}")); @@ -341,7 +342,7 @@ async fn notify_mcp_tool_call_skip( call_id: &str, invocation: McpInvocation, message: String, -) -> Result { +) -> Result { let tool_call_begin_event = EventMsg::McpToolCallBegin(McpToolCallBeginEvent { call_id: call_id.to_string(), invocation: invocation.clone(), diff --git a/codex-rs/core/src/tools/context.rs b/codex-rs/core/src/tools/context.rs index abe488681e..f0bbb158f5 100644 --- a/codex-rs/core/src/tools/context.rs +++ b/codex-rs/core/src/tools/context.rs @@ -4,12 +4,12 @@ use crate::tools::TELEMETRY_PREVIEW_MAX_BYTES; use crate::tools::TELEMETRY_PREVIEW_MAX_LINES; use crate::tools::TELEMETRY_PREVIEW_TRUNCATION_NOTICE; use crate::turn_diff_tracker::TurnDiffTracker; +use codex_protocol::mcp::CallToolResult; use codex_protocol::models::FunctionCallOutputContentItem; use codex_protocol::models::FunctionCallOutputPayload; use codex_protocol::models::ResponseInputItem; use codex_protocol::models::ShellToolCallParams; use codex_utils_string::take_bytes_at_char_boundary; -use mcp_types::CallToolResult; use std::borrow::Cow; use std::sync::Arc; use tokio::sync::Mutex; diff --git a/codex-rs/core/src/tools/handlers/mcp.rs b/codex-rs/core/src/tools/handlers/mcp.rs index 5138b3cd0d..15e0fbacfd 100644 --- a/codex-rs/core/src/tools/handlers/mcp.rs +++ b/codex-rs/core/src/tools/handlers/mcp.rs @@ -8,6 +8,7 @@ use crate::tools::context::ToolOutput; use crate::tools::context::ToolPayload; use crate::tools::registry::ToolHandler; use crate::tools::registry::ToolKind; +use codex_protocol::mcp::CallToolResult; pub struct McpHandler; @@ -54,7 +55,16 @@ impl ToolHandler for McpHandler { match response { codex_protocol::models::ResponseInputItem::McpToolCallOutput { result, .. } => { - Ok(ToolOutput::Mcp { result }) + Ok(ToolOutput::Mcp { + result: result.and_then(|result| { + serde_json::to_value(result) + .map_err(|err| err.to_string()) + .and_then(|value| { + serde_json::from_value::(value) + .map_err(|err| err.to_string()) + }) + }), + }) } codex_protocol::models::ResponseInputItem::FunctionCallOutput { output, .. } => { let codex_protocol::models::FunctionCallOutputPayload { diff --git a/codex-rs/core/src/tools/handlers/mcp_resource.rs b/codex-rs/core/src/tools/handlers/mcp_resource.rs index 62f7a83e1a..df421bd6d3 100644 --- a/codex-rs/core/src/tools/handlers/mcp_resource.rs +++ b/codex-rs/core/src/tools/handlers/mcp_resource.rs @@ -4,17 +4,14 @@ use std::time::Duration; use std::time::Instant; use async_trait::async_trait; -use mcp_types::CallToolResult; -use mcp_types::ContentBlock; -use mcp_types::ListResourceTemplatesRequestParams; -use mcp_types::ListResourceTemplatesResult; -use mcp_types::ListResourcesRequestParams; -use mcp_types::ListResourcesResult; -use mcp_types::ReadResourceRequestParams; -use mcp_types::ReadResourceResult; -use mcp_types::Resource; -use mcp_types::ResourceTemplate; -use mcp_types::TextContent; +use codex_protocol::mcp::CallToolResult; +use rmcp::model::ListResourceTemplatesResult; +use rmcp::model::ListResourcesResult; +use rmcp::model::PaginatedRequestParam; +use rmcp::model::ReadResourceRequestParam; +use rmcp::model::ReadResourceResult; +use rmcp::model::Resource; +use rmcp::model::ResourceTemplate; use serde::Deserialize; use serde::Serialize; use serde::de::DeserializeOwned; @@ -264,7 +261,7 @@ async fn handle_list_resources( let payload_result: Result = async { if let Some(server_name) = server.clone() { - let params = cursor.clone().map(|value| ListResourcesRequestParams { + let params = cursor.clone().map(|value| PaginatedRequestParam { cursor: Some(value), }); let result = session @@ -371,11 +368,9 @@ async fn handle_list_resource_templates( let payload_result: Result = async { if let Some(server_name) = server.clone() { - let params = cursor - .clone() - .map(|value| ListResourceTemplatesRequestParams { - cursor: Some(value), - }); + let params = cursor.clone().map(|value| PaginatedRequestParam { + cursor: Some(value), + }); let result = session .list_resource_templates(&server_name, params) .await @@ -482,7 +477,7 @@ async fn handle_read_resource( let payload_result: Result = async { let result = session - .read_resource(&server, ReadResourceRequestParams { uri: uri.clone() }) + .read_resource(&server, ReadResourceRequestParam { uri: uri.clone() }) .await .map_err(|err| { FunctionCallError::RespondToModel(format!("resources/read failed: {err:#}")) @@ -551,13 +546,10 @@ async fn handle_read_resource( fn call_tool_result_from_content(content: &str, success: Option) -> CallToolResult { CallToolResult { - content: vec![ContentBlock::TextContent(TextContent { - annotations: None, - text: content.to_string(), - r#type: "text".to_string(), - })], - is_error: success.map(|value| !value), + content: vec![serde_json::json!({"type": "text", "text": content})], structured_content: None, + is_error: success.map(|value| !value), + meta: None, } } @@ -678,32 +670,33 @@ where #[cfg(test)] mod tests { use super::*; - use mcp_types::ListResourcesResult; - use mcp_types::ResourceTemplate; use pretty_assertions::assert_eq; + use rmcp::model::AnnotateAble; use serde_json::json; fn resource(uri: &str, name: &str) -> Resource { - Resource { - annotations: None, + rmcp::model::RawResource { + uri: uri.to_string(), + name: name.to_string(), + title: None, description: None, mime_type: None, - name: name.to_string(), size: None, - title: None, - uri: uri.to_string(), + icons: None, + meta: None, } + .no_annotation() } fn template(uri_template: &str, name: &str) -> ResourceTemplate { - ResourceTemplate { - annotations: None, - description: None, - mime_type: None, + rmcp::model::RawResourceTemplate { + uri_template: uri_template.to_string(), name: name.to_string(), title: None, - uri_template: uri_template.to_string(), + description: None, + mime_type: None, } + .no_annotation() } #[test] @@ -719,6 +712,7 @@ mod tests { #[test] fn list_resources_payload_from_single_server_copies_next_cursor() { let result = ListResourcesResult { + meta: None, next_cursor: Some("cursor-1".to_string()), resources: vec![resource("memo://id", "memo")], }; diff --git a/codex-rs/core/src/tools/router.rs b/codex-rs/core/src/tools/router.rs index d3ff84a2b0..18be51f1e6 100644 --- a/codex-rs/core/src/tools/router.rs +++ b/codex-rs/core/src/tools/router.rs @@ -15,6 +15,7 @@ use codex_protocol::models::LocalShellAction; use codex_protocol::models::ResponseInputItem; use codex_protocol::models::ResponseItem; use codex_protocol::models::ShellToolCallParams; +use rmcp::model::Tool as McpTool; use std::collections::HashMap; use std::sync::Arc; use tracing::instrument; @@ -34,7 +35,7 @@ pub struct ToolRouter { impl ToolRouter { pub fn from_config( config: &ToolsConfig, - mcp_tools: Option>, + mcp_tools: Option>, dynamic_tools: &[DynamicToolSpec], ) -> Self { let builder = build_specs(config, mcp_tools, dynamic_tools); diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index a51372b9b3..3cf96ca2d9 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -1087,34 +1087,27 @@ pub(crate) fn create_tools_json_for_chat_completions_api( pub(crate) fn mcp_tool_to_openai_tool( fully_qualified_name: String, - tool: mcp_types::Tool, + tool: rmcp::model::Tool, ) -> Result { - let mcp_types::Tool { + let rmcp::model::Tool { description, - mut input_schema, + input_schema, .. } = tool; - // OpenAI models mandate the "properties" field in the schema. The Agents - // SDK fixed this by inserting an empty object for "properties" if it is not - // already present https://github.com/openai/openai-agents-python/issues/449 - // so here we do the same. - if input_schema.properties.is_none() { - input_schema.properties = Some(serde_json::Value::Object(serde_json::Map::new())); - } + let mut serialized_input_schema = serde_json::Value::Object(input_schema.as_ref().clone()); // Serialize to a raw JSON value so we can sanitize schemas coming from MCP // servers. Some servers omit the top-level or nested `type` in JSON // Schemas (e.g. using enum/anyOf), or use unsupported variants like // `integer`. Our internal JsonSchema is a small subset and requires // `type`, so we coerce/sanitize here for compatibility. - let mut serialized_input_schema = serde_json::to_value(input_schema)?; sanitize_json_schema(&mut serialized_input_schema); let input_schema = serde_json::from_value::(serialized_input_schema)?; Ok(ResponsesApiTool { name: fully_qualified_name, - description: description.unwrap_or_default(), + description: description.map(Into::into).unwrap_or_default(), strict: false, parameters: input_schema, }) @@ -1254,7 +1247,7 @@ fn sanitize_json_schema(value: &mut JsonValue) { /// Builds the tool registry builder while collecting tool specs for later serialization. pub(crate) fn build_specs( config: &ToolsConfig, - mcp_tools: Option>, + mcp_tools: Option>, dynamic_tools: &[DynamicToolSpec], ) -> ToolRegistryBuilder { use crate::tools::handlers::ApplyPatchHandler; @@ -1410,7 +1403,7 @@ pub(crate) fn build_specs( } if let Some(mcp_tools) = mcp_tools { - let mut entries: Vec<(String, mcp_types::Tool)> = mcp_tools.into_iter().collect(); + let mut entries: Vec<(String, rmcp::model::Tool)> = mcp_tools.into_iter().collect(); entries.sort_by(|a, b| a.0.cmp(&b.0)); for (name, tool) in entries.into_iter() { @@ -1452,11 +1445,27 @@ mod tests { use crate::config::test_config; use crate::models_manager::manager::ModelsManager; use crate::tools::registry::ConfiguredToolSpec; - use mcp_types::ToolInputSchema; use pretty_assertions::assert_eq; use super::*; + fn mcp_tool( + name: &str, + description: &str, + input_schema: serde_json::Value, + ) -> rmcp::model::Tool { + rmcp::model::Tool { + name: name.to_string().into(), + title: None, + description: Some(description.to_string().into()), + input_schema: std::sync::Arc::new(rmcp::model::object(input_schema)), + output_schema: None, + annotations: None, + icons: None, + meta: None, + } + } + fn tool_name(tool: &ToolSpec) -> &str { match tool { ToolSpec::Function(ResponsesApiTool { name, .. }) => name, @@ -2026,37 +2035,26 @@ mod tests { &tools_config, Some(HashMap::from([( "test_server/do_something_cool".to_string(), - mcp_types::Tool { - name: "do_something_cool".to_string(), - input_schema: ToolInputSchema { - properties: Some(serde_json::json!({ - "string_argument": { - "type": "string", - }, - "number_argument": { - "type": "number", - }, + mcp_tool( + "do_something_cool", + "Do something cool", + serde_json::json!({ + "type": "object", + "properties": { + "string_argument": { "type": "string" }, + "number_argument": { "type": "number" }, "object_argument": { "type": "object", "properties": { "string_property": { "type": "string" }, "number_property": { "type": "number" }, }, - "required": [ - "string_property", - "number_property", - ], - "additionalProperties": Some(false), + "required": ["string_property", "number_property"], + "additionalProperties": false, }, - })), - required: None, - r#type: "object".to_string(), - }, - output_schema: None, - title: None, - annotations: None, - description: Some("Do something cool".to_string()), - }, + }, + }), + ), )])), &[], ) @@ -2120,51 +2118,18 @@ mod tests { }); // Intentionally construct a map with keys that would sort alphabetically. - let tools_map: HashMap = HashMap::from([ + let tools_map: HashMap = HashMap::from([ ( "test_server/do".to_string(), - mcp_types::Tool { - name: "a".to_string(), - input_schema: ToolInputSchema { - properties: Some(serde_json::json!({})), - required: None, - r#type: "object".to_string(), - }, - output_schema: None, - title: None, - annotations: None, - description: Some("a".to_string()), - }, + mcp_tool("a", "a", serde_json::json!({"type": "object"})), ), ( "test_server/something".to_string(), - mcp_types::Tool { - name: "b".to_string(), - input_schema: ToolInputSchema { - properties: Some(serde_json::json!({})), - required: None, - r#type: "object".to_string(), - }, - output_schema: None, - title: None, - annotations: None, - description: Some("b".to_string()), - }, + mcp_tool("b", "b", serde_json::json!({"type": "object"})), ), ( "test_server/cool".to_string(), - mcp_types::Tool { - name: "c".to_string(), - input_schema: ToolInputSchema { - properties: Some(serde_json::json!({})), - required: None, - r#type: "object".to_string(), - }, - output_schema: None, - title: None, - annotations: None, - description: Some("c".to_string()), - }, + mcp_tool("c", "c", serde_json::json!({"type": "object"})), ), ]); @@ -2200,22 +2165,16 @@ mod tests { &tools_config, Some(HashMap::from([( "dash/search".to_string(), - mcp_types::Tool { - name: "search".to_string(), - input_schema: ToolInputSchema { - properties: Some(serde_json::json!({ - "query": { - "description": "search query" - } - })), - required: None, - r#type: "object".to_string(), - }, - output_schema: None, - title: None, - annotations: None, - description: Some("Search docs".to_string()), - }, + mcp_tool( + "search", + "Search docs", + serde_json::json!({ + "type": "object", + "properties": { + "query": {"description": "search query"} + } + }), + ), )])), &[], ) @@ -2258,20 +2217,14 @@ mod tests { &tools_config, Some(HashMap::from([( "dash/paginate".to_string(), - mcp_types::Tool { - name: "paginate".to_string(), - input_schema: ToolInputSchema { - properties: Some(serde_json::json!({ - "page": { "type": "integer" } - })), - required: None, - r#type: "object".to_string(), - }, - output_schema: None, - title: None, - annotations: None, - description: Some("Pagination".to_string()), - }, + mcp_tool( + "paginate", + "Pagination", + serde_json::json!({ + "type": "object", + "properties": {"page": {"type": "integer"}} + }), + ), )])), &[], ) @@ -2313,20 +2266,14 @@ mod tests { &tools_config, Some(HashMap::from([( "dash/tags".to_string(), - mcp_types::Tool { - name: "tags".to_string(), - input_schema: ToolInputSchema { - properties: Some(serde_json::json!({ - "tags": { "type": "array" } - })), - required: None, - r#type: "object".to_string(), - }, - output_schema: None, - title: None, - annotations: None, - description: Some("Tags".to_string()), - }, + mcp_tool( + "tags", + "Tags", + serde_json::json!({ + "type": "object", + "properties": {"tags": {"type": "array"}} + }), + ), )])), &[], ) @@ -2370,20 +2317,16 @@ mod tests { &tools_config, Some(HashMap::from([( "dash/value".to_string(), - mcp_types::Tool { - name: "value".to_string(), - input_schema: ToolInputSchema { - properties: Some(serde_json::json!({ - "value": { "anyOf": [ { "type": "string" }, { "type": "number" } ] } - })), - required: None, - r#type: "object".to_string(), - }, - output_schema: None, - title: None, - annotations: None, - description: Some("AnyOf Value".to_string()), - }, + mcp_tool( + "value", + "AnyOf Value", + serde_json::json!({ + "type": "object", + "properties": { + "value": {"anyOf": [{"type": "string"}, {"type": "number"}]} + } + }), + ), )])), &[], ) @@ -2482,46 +2425,33 @@ Examples of valid command strings: &tools_config, Some(HashMap::from([( "test_server/do_something_cool".to_string(), - mcp_types::Tool { - name: "do_something_cool".to_string(), - input_schema: ToolInputSchema { - properties: Some(serde_json::json!({ - "string_argument": { - "type": "string", - }, - "number_argument": { - "type": "number", - }, + mcp_tool( + "do_something_cool", + "Do something cool", + serde_json::json!({ + "type": "object", + "properties": { + "string_argument": {"type": "string"}, + "number_argument": {"type": "number"}, "object_argument": { "type": "object", "properties": { - "string_property": { "type": "string" }, - "number_property": { "type": "number" }, + "string_property": {"type": "string"}, + "number_property": {"type": "number"} }, - "required": [ - "string_property", - "number_property", - ], + "required": ["string_property", "number_property"], "additionalProperties": { "type": "object", "properties": { - "addtl_prop": { "type": "string" }, + "addtl_prop": {"type": "string"} }, - "required": [ - "addtl_prop", - ], - "additionalProperties": false, - }, - }, - })), - required: None, - r#type: "object".to_string(), - }, - output_schema: None, - title: None, - annotations: None, - description: Some("Do something cool".to_string()), - }, + "required": ["addtl_prop"], + "additionalProperties": false + } + } + } + }), + ), )])), &[], ) diff --git a/codex-rs/core/tests/suite/rmcp_client.rs b/codex-rs/core/tests/suite/rmcp_client.rs index 7eaeef6590..cdf6a1adc5 100644 --- a/codex-rs/core/tests/suite/rmcp_client.rs +++ b/codex-rs/core/tests/suite/rmcp_client.rs @@ -26,7 +26,6 @@ use core_test_support::skip_if_no_network; use core_test_support::stdio_server_bin; use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; -use mcp_types::ContentBlock; use serde_json::Value; use serde_json::json; use serial_test::serial; @@ -307,14 +306,10 @@ async fn stdio_image_responses_round_trip() -> anyhow::Result<()> { let base64_only = OPENAI_PNG .strip_prefix("data:image/png;base64,") .expect("data url prefix"); - match &result.content[0] { - ContentBlock::ImageContent(img) => { - assert_eq!(img.mime_type, "image/png"); - assert_eq!(img.r#type, "image"); - assert_eq!(img.data, base64_only); - } - other => panic!("expected image content, got {other:?}"), - } + let entry = result.content[0].as_object().expect("content object"); + assert_eq!(entry.get("type"), Some(&json!("image"))); + assert_eq!(entry.get("mimeType"), Some(&json!("image/png"))); + assert_eq!(entry.get("data"), Some(&json!(base64_only))); wait_for_event(&fixture.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; diff --git a/codex-rs/exec/Cargo.toml b/codex-rs/exec/Cargo.toml index 862d8d1694..860f4034be 100644 --- a/codex-rs/exec/Cargo.toml +++ b/codex-rs/exec/Cargo.toml @@ -28,7 +28,6 @@ codex-common = { workspace = true, features = [ codex-core = { workspace = true } codex-protocol = { workspace = true } codex-utils-absolute-path = { workspace = true } -mcp-types = { workspace = true } owo-colors = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } @@ -56,9 +55,9 @@ assert_cmd = { workspace = true } codex-utils-cargo-bin = { workspace = true } core_test_support = { workspace = true } libc = { workspace = true } -mcp-types = { workspace = true } predicates = { workspace = true } pretty_assertions = { workspace = true } +rmcp = { workspace = true } tempfile = { workspace = true } uuid = { workspace = true } walkdir = { workspace = true } diff --git a/codex-rs/exec/src/event_processor_with_human_output.rs b/codex-rs/exec/src/event_processor_with_human_output.rs index 8469dc42ed..3b4a3bf86b 100644 --- a/codex-rs/exec/src/event_processor_with_human_output.rs +++ b/codex-rs/exec/src/event_processor_with_human_output.rs @@ -375,7 +375,8 @@ impl EventProcessor for EventProcessorWithHumanOutput { ts_msg!(self, "{}", title.style(title_style)); if let Ok(res) = result { - let val: serde_json::Value = res.into(); + let val = serde_json::to_value(res) + .unwrap_or_else(|_| serde_json::Value::String("".to_string())); let pretty = serde_json::to_string_pretty(&val).unwrap_or_else(|_| val.to_string()); diff --git a/codex-rs/exec/src/exec_events.rs b/codex-rs/exec/src/exec_events.rs index 47c67a6dca..3adafa6e14 100644 --- a/codex-rs/exec/src/exec_events.rs +++ b/codex-rs/exec/src/exec_events.rs @@ -1,5 +1,5 @@ use codex_protocol::models::WebSearchAction; -use mcp_types::ContentBlock as McpContentBlock; +type McpContentBlock = serde_json::Value; use serde::Deserialize; use serde::Serialize; use serde_json::Value as JsonValue; diff --git a/codex-rs/exec/tests/event_processor_with_json_output.rs b/codex-rs/exec/tests/event_processor_with_json_output.rs index 47b7a9f331..6a853857da 100644 --- a/codex-rs/exec/tests/event_processor_with_json_output.rs +++ b/codex-rs/exec/tests/event_processor_with_json_output.rs @@ -56,6 +56,7 @@ use codex_exec::exec_events::Usage; use codex_exec::exec_events::WebSearchItem; use codex_protocol::ThreadId; use codex_protocol::config_types::ModeKind; +use codex_protocol::mcp::CallToolResult; use codex_protocol::models::WebSearchAction; use codex_protocol::plan_tool::PlanItemArg; use codex_protocol::plan_tool::StepStatus; @@ -63,10 +64,8 @@ use codex_protocol::plan_tool::UpdatePlanArgs; use codex_protocol::protocol::CodexErrorInfo; use codex_protocol::protocol::ExecCommandOutputDeltaEvent; use codex_protocol::protocol::ExecOutputStream; -use mcp_types::CallToolResult; -use mcp_types::ContentBlock; -use mcp_types::TextContent; use pretty_assertions::assert_eq; +use rmcp::model::Content; use serde_json::json; use std::path::PathBuf; use std::time::Duration; @@ -385,6 +384,7 @@ fn mcp_tool_call_begin_and_end_emit_item_events() { content: Vec::new(), is_error: None, structured_content: None, + meta: None, }), }), ); @@ -499,13 +499,10 @@ fn mcp_tool_call_defaults_arguments_and_preserves_structured_content() { invocation, duration: Duration::from_millis(10), result: Ok(CallToolResult { - content: vec![ContentBlock::TextContent(TextContent { - annotations: None, - text: "done".to_string(), - r#type: "text".to_string(), - })], + content: vec![serde_json::to_value(Content::text("done")).unwrap()], is_error: None, structured_content: Some(json!({ "status": "ok" })), + meta: None, }), }), ); @@ -520,11 +517,7 @@ fn mcp_tool_call_defaults_arguments_and_preserves_structured_content() { tool: "tool_z".to_string(), arguments: serde_json::Value::Null, result: Some(McpToolCallItemResult { - content: vec![ContentBlock::TextContent(TextContent { - annotations: None, - text: "done".to_string(), - r#type: "text".to_string(), - })], + content: vec![serde_json::to_value(Content::text("done")).unwrap()], structured_content: Some(json!({ "status": "ok" })), }), error: None, diff --git a/codex-rs/mcp-server/Cargo.toml b/codex-rs/mcp-server/Cargo.toml index 6236384c95..7a952342de 100644 --- a/codex-rs/mcp-server/Cargo.toml +++ b/codex-rs/mcp-server/Cargo.toml @@ -22,7 +22,7 @@ codex-common = { workspace = true, features = ["cli"] } codex-core = { workspace = true } codex-protocol = { workspace = true } codex-utils-json-to-toml = { workspace = true } -mcp-types = { workspace = true } +rmcp = { workspace = true } schemars = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } diff --git a/codex-rs/mcp-server/src/codex_tool_config.rs b/codex-rs/mcp-server/src/codex_tool_config.rs index 8131d7da52..c56f794d79 100644 --- a/codex-rs/mcp-server/src/codex_tool_config.rs +++ b/codex-rs/mcp-server/src/codex_tool_config.rs @@ -6,15 +6,15 @@ use codex_core::protocol::AskForApproval; use codex_protocol::ThreadId; use codex_protocol::config_types::SandboxMode; use codex_utils_json_to_toml::json_to_toml; -use mcp_types::Tool; -use mcp_types::ToolInputSchema; -use mcp_types::ToolOutputSchema; +use rmcp::model::JsonObject; +use rmcp::model::Tool; use schemars::JsonSchema; use schemars::r#gen::SchemaSettings; use serde::Deserialize; use serde::Serialize; use std::collections::HashMap; use std::path::PathBuf; +use std::sync::Arc; /// Client-supplied configuration for a `codex` tool-call. #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)] @@ -115,35 +115,35 @@ pub(crate) fn create_tool_for_codex_tool_call_param() -> Tool { .into_generator() .into_root_schema_for::(); - #[expect(clippy::expect_used)] - let schema_value = - serde_json::to_value(&schema).expect("Codex tool schema should serialise to JSON"); - - let tool_input_schema = - serde_json::from_value::(schema_value).unwrap_or_else(|e| { - panic!("failed to create Tool from schema: {e}"); - }); + let input_schema = create_tool_input_schema(schema, "Codex tool schema should serialize"); Tool { - name: "codex".to_string(), + name: "codex".into(), title: Some("Codex".to_string()), - input_schema: tool_input_schema, + input_schema, output_schema: Some(codex_tool_output_schema()), description: Some( - "Run a Codex session. Accepts configuration parameters matching the Codex Config struct.".to_string(), + "Run a Codex session. Accepts configuration parameters matching the Codex Config struct." + .into(), ), annotations: None, + icons: None, + meta: None, } } -fn codex_tool_output_schema() -> ToolOutputSchema { - ToolOutputSchema { - properties: Some(serde_json::json!({ +fn codex_tool_output_schema() -> Arc { + let schema = serde_json::json!({ + "type": "object", + "properties": { "threadId": { "type": "string" }, "content": { "type": "string" } - })), - required: Some(vec!["threadId".to_string(), "content".to_string()]), - r#type: "object".to_string(), + }, + "required": ["threadId", "content"], + }); + match schema { + serde_json::Value::Object(map) => Arc::new(map), + _ => unreachable!("json literal must be an object"), } } @@ -237,27 +237,42 @@ pub(crate) fn create_tool_for_codex_tool_call_reply_param() -> Tool { .into_generator() .into_root_schema_for::(); - #[expect(clippy::expect_used)] - let schema_value = - serde_json::to_value(&schema).expect("Codex reply tool schema should serialise to JSON"); - - let tool_input_schema = - serde_json::from_value::(schema_value).unwrap_or_else(|e| { - panic!("failed to create Tool from schema: {e}"); - }); + let input_schema = create_tool_input_schema(schema, "Codex reply tool schema should serialize"); Tool { - name: "codex-reply".to_string(), + name: "codex-reply".into(), title: Some("Codex Reply".to_string()), - input_schema: tool_input_schema, + input_schema, output_schema: Some(codex_tool_output_schema()), description: Some( - "Continue a Codex conversation by providing the thread id and prompt.".to_string(), + "Continue a Codex conversation by providing the thread id and prompt.".into(), ), annotations: None, + icons: None, + meta: None, } } +fn create_tool_input_schema( + schema: schemars::schema::RootSchema, + panic_message: &str, +) -> Arc { + #[expect(clippy::expect_used)] + let schema_value = serde_json::to_value(&schema).expect(panic_message); + let mut schema_object = match schema_value { + serde_json::Value::Object(object) => object, + _ => panic!("tool schema should serialize to a JSON object"), + }; + + let mut input_schema = JsonObject::new(); + for key in ["properties", "required", "type"] { + if let Some(value) = schema_object.remove(key) { + input_schema.insert(key.to_string(), value); + } + } + Arc::new(input_schema) +} + #[cfg(test)] mod tests { use super::*; diff --git a/codex-rs/mcp-server/src/codex_tool_runner.rs b/codex-rs/mcp-server/src/codex_tool_runner.rs index 1dbdbc767b..6273607a22 100644 --- a/codex-rs/mcp-server/src/codex_tool_runner.rs +++ b/codex-rs/mcp-server/src/codex_tool_runner.rs @@ -23,15 +23,12 @@ use codex_core::protocol::Submission; use codex_core::protocol::TurnCompleteEvent; use codex_protocol::ThreadId; use codex_protocol::user_input::UserInput; -use mcp_types::CallToolResult; -use mcp_types::ContentBlock; -use mcp_types::RequestId; -use mcp_types::TextContent; +use rmcp::model::CallToolResult; +use rmcp::model::Content; +use rmcp::model::RequestId; use serde_json::json; use tokio::sync::Mutex; -pub(crate) const INVALID_PARAMS_ERROR_CODE: i64 = -32602; - /// To adhere to MCP `tools/call` response format, include the Codex /// `threadId` in the `structured_content` field of the response. /// Some MCP clients ignore `content` when `structuredContent` is present, so @@ -42,11 +39,7 @@ pub(crate) fn create_call_tool_result_with_thread_id( is_error: Option, ) -> CallToolResult { let content_text = text; - let content = vec![ContentBlock::TextContent(TextContent { - r#type: "text".to_string(), - text: content_text.clone(), - annotations: None, - })]; + let content = vec![Content::text(content_text.clone())]; let structured_content = json!({ "threadId": thread_id, "content": content_text, @@ -55,6 +48,7 @@ pub(crate) fn create_call_tool_result_with_thread_id( content, is_error, structured_content: Some(structured_content), + meta: None, } } @@ -78,13 +72,10 @@ pub async fn run_codex_tool_session( Ok(res) => res, Err(e) => { let result = CallToolResult { - content: vec![ContentBlock::TextContent(TextContent { - r#type: "text".to_string(), - text: format!("Failed to start Codex session: {e}"), - annotations: None, - })], + content: vec![Content::text(format!("Failed to start Codex session: {e}"))], is_error: Some(true), structured_content: None, + meta: None, }; outgoing.send_response(id.clone(), result).await; return; @@ -109,10 +100,7 @@ pub async fn run_codex_tool_session( // Use the original MCP request ID as the `sub_id` for the Codex submission so that // any events emitted for this tool-call can be correlated with the // originating `tools/call` request. - let sub_id = match &id { - RequestId::String(s) => s.clone(), - RequestId::Integer(n) => n.to_string(), - }; + let sub_id = id.to_string(); running_requests_id_to_codex_uuid .lock() .await @@ -207,10 +195,7 @@ async fn run_codex_tool_session_inner( request_id: RequestId, running_requests_id_to_codex_uuid: Arc>>, ) { - let request_id_str = match &request_id { - RequestId::String(s) => s.clone(), - RequestId::Integer(n) => n.to_string(), - }; + let request_id_str = request_id.to_string(); // Stream events until the task needs to pause for user interaction or // completes. diff --git a/codex-rs/mcp-server/src/error_code.rs b/codex-rs/mcp-server/src/error_code.rs deleted file mode 100644 index 1ffd889d40..0000000000 --- a/codex-rs/mcp-server/src/error_code.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub(crate) const INVALID_REQUEST_ERROR_CODE: i64 = -32600; -pub(crate) const INTERNAL_ERROR_CODE: i64 = -32603; diff --git a/codex-rs/mcp-server/src/exec_approval.rs b/codex-rs/mcp-server/src/exec_approval.rs index a98099dcf2..3a48481c88 100644 --- a/codex-rs/mcp-server/src/exec_approval.rs +++ b/codex-rs/mcp-server/src/exec_approval.rs @@ -6,20 +6,16 @@ use codex_core::protocol::Op; use codex_core::protocol::ReviewDecision; use codex_protocol::ThreadId; use codex_protocol::parse_command::ParsedCommand; -use mcp_types::ElicitRequest; -use mcp_types::ElicitRequestParamsRequestedSchema; -use mcp_types::JSONRPCErrorError; -use mcp_types::ModelContextProtocolRequest; -use mcp_types::RequestId; +use rmcp::model::ElicitationSchema; +use rmcp::model::ErrorData; +use rmcp::model::RequestId; use serde::Deserialize; use serde::Serialize; -use serde_json::json; +use std::collections::BTreeMap; use tracing::error; -use crate::codex_tool_runner::INVALID_PARAMS_ERROR_CODE; - -/// Conforms to [`mcp_types::ElicitRequestParams`] so that it can be used as the -/// `params` field of an [`ElicitRequest`]. +/// Conforms to the MCP elicitation request params shape, so it can be used as +/// the `params` field of an `elicitation/create` request. #[derive(Debug, Deserialize, Serialize)] pub struct ExecApprovalElicitRequestParams { // These fields are required so that `params` @@ -27,7 +23,7 @@ pub struct ExecApprovalElicitRequestParams { pub message: String, #[serde(rename = "requestedSchema")] - pub requested_schema: ElicitRequestParamsRequestedSchema, + pub requested_schema: ElicitationSchema, // These are additional fields the client can use to // correlate the request with the codex tool call. @@ -73,11 +69,7 @@ pub(crate) async fn handle_exec_approval_request( let params = ExecApprovalElicitRequestParams { message, - requested_schema: ElicitRequestParamsRequestedSchema { - r#type: "object".to_string(), - properties: json!({}), - required: None, - }, + requested_schema: ElicitationSchema::new(BTreeMap::new()), thread_id, codex_elicitation: "exec-approval".to_string(), codex_mcp_tool_call_id: tool_call_id.clone(), @@ -94,14 +86,7 @@ pub(crate) async fn handle_exec_approval_request( error!("{message}"); outgoing - .send_error( - request_id.clone(), - JSONRPCErrorError { - code: INVALID_PARAMS_ERROR_CODE, - message, - data: None, - }, - ) + .send_error(request_id.clone(), ErrorData::invalid_params(message, None)) .await; return; @@ -109,7 +94,7 @@ pub(crate) async fn handle_exec_approval_request( }; let on_response = outgoing - .send_request(ElicitRequest::METHOD, Some(params_json)) + .send_request("elicitation/create", Some(params_json)) .await; // Listen for the response on a separate task so we don't block the main agent loop. @@ -124,7 +109,7 @@ pub(crate) async fn handle_exec_approval_request( async fn on_exec_approval_response( event_id: String, - receiver: tokio::sync::oneshot::Receiver, + receiver: tokio::sync::oneshot::Receiver, codex: Arc, ) { let response = receiver.await; diff --git a/codex-rs/mcp-server/src/lib.rs b/codex-rs/mcp-server/src/lib.rs index dabd7cca0f..eed176c575 100644 --- a/codex-rs/mcp-server/src/lib.rs +++ b/codex-rs/mcp-server/src/lib.rs @@ -8,7 +8,10 @@ use std::path::PathBuf; use codex_common::CliConfigOverrides; use codex_core::config::Config; -use mcp_types::JSONRPCMessage; +use rmcp::model::ClientNotification; +use rmcp::model::ClientRequest; +use rmcp::model::JsonRpcMessage; +use serde_json::Value; use tokio::io::AsyncBufReadExt; use tokio::io::AsyncWriteExt; use tokio::io::BufReader; @@ -21,13 +24,13 @@ use tracing_subscriber::EnvFilter; mod codex_tool_config; mod codex_tool_runner; -mod error_code; mod exec_approval; pub(crate) mod message_processor; mod outgoing_message; mod patch_approval; use crate::message_processor::MessageProcessor; +use crate::outgoing_message::OutgoingJsonRpcMessage; use crate::outgoing_message::OutgoingMessage; use crate::outgoing_message::OutgoingMessageSender; @@ -43,6 +46,8 @@ pub use crate::patch_approval::PatchApprovalResponse; /// plenty for an interactive CLI. const CHANNEL_CAPACITY: usize = 128; +type IncomingMessage = JsonRpcMessage; + pub async fn run_main( codex_linux_sandbox_exe: Option, cli_config_overrides: CliConfigOverrides, @@ -55,7 +60,7 @@ pub async fn run_main( .init(); // Set up channels. - let (incoming_tx, mut incoming_rx) = mpsc::channel::(CHANNEL_CAPACITY); + let (incoming_tx, mut incoming_rx) = mpsc::channel::(CHANNEL_CAPACITY); let (outgoing_tx, mut outgoing_rx) = mpsc::unbounded_channel::(); // Task: read from stdin, push to `incoming_tx`. @@ -66,14 +71,14 @@ pub async fn run_main( let mut lines = reader.lines(); while let Some(line) = lines.next_line().await.unwrap_or_default() { - match serde_json::from_str::(&line) { + match serde_json::from_str::(&line) { Ok(msg) => { if incoming_tx.send(msg).await.is_err() { // Receiver gone – nothing left to do. break; } } - Err(e) => error!("Failed to deserialize JSONRPCMessage: {e}"), + Err(e) => error!("Failed to deserialize JSON-RPC message: {e}"), } } @@ -106,10 +111,10 @@ pub async fn run_main( async move { while let Some(msg) = incoming_rx.recv().await { match msg { - JSONRPCMessage::Request(r) => processor.process_request(r).await, - JSONRPCMessage::Response(r) => processor.process_response(r).await, - JSONRPCMessage::Notification(n) => processor.process_notification(n).await, - JSONRPCMessage::Error(e) => processor.process_error(e), + JsonRpcMessage::Request(r) => processor.process_request(r).await, + JsonRpcMessage::Response(r) => processor.process_response(r).await, + JsonRpcMessage::Notification(n) => processor.process_notification(n).await, + JsonRpcMessage::Error(e) => processor.process_error(e), } } @@ -121,7 +126,7 @@ pub async fn run_main( let stdout_writer_handle = tokio::spawn(async move { let mut stdout = io::stdout(); while let Some(outgoing_message) = outgoing_rx.recv().await { - let msg: JSONRPCMessage = outgoing_message.into(); + let msg: OutgoingJsonRpcMessage = outgoing_message.into(); match serde_json::to_string(&msg) { Ok(json) => { if let Err(e) = stdout.write_all(json.as_bytes()).await { @@ -133,7 +138,7 @@ pub async fn run_main( break; } } - Err(e) => error!("Failed to serialize JSONRPCMessage: {e}"), + Err(e) => error!("Failed to serialize JSON-RPC message: {e}"), } } diff --git a/codex-rs/mcp-server/src/message_processor.rs b/codex-rs/mcp-server/src/message_processor.rs index 9d947cda3f..494ea11305 100644 --- a/codex-rs/mcp-server/src/message_processor.rs +++ b/codex-rs/mcp-server/src/message_processor.rs @@ -1,41 +1,40 @@ use std::collections::HashMap; use std::path::PathBuf; -use crate::codex_tool_config::CodexToolCallParam; -use crate::codex_tool_config::CodexToolCallReplyParam; -use crate::codex_tool_config::create_tool_for_codex_tool_call_param; -use crate::codex_tool_config::create_tool_for_codex_tool_call_reply_param; -use crate::error_code::INVALID_REQUEST_ERROR_CODE; -use crate::outgoing_message::OutgoingMessageSender; -use codex_protocol::ThreadId; -use codex_protocol::protocol::SessionSource; - use codex_core::AuthManager; use codex_core::ThreadManager; use codex_core::config::Config; use codex_core::default_client::USER_AGENT_SUFFIX; use codex_core::default_client::get_codex_user_agent; use codex_core::protocol::Submission; -use mcp_types::CallToolRequestParams; -use mcp_types::CallToolResult; -use mcp_types::ClientRequest as McpClientRequest; -use mcp_types::ContentBlock; -use mcp_types::JSONRPCError; -use mcp_types::JSONRPCErrorError; -use mcp_types::JSONRPCNotification; -use mcp_types::JSONRPCRequest; -use mcp_types::JSONRPCResponse; -use mcp_types::ListToolsResult; -use mcp_types::ModelContextProtocolRequest; -use mcp_types::RequestId; -use mcp_types::ServerCapabilitiesTools; -use mcp_types::ServerNotification; -use mcp_types::TextContent; +use codex_protocol::ThreadId; +use codex_protocol::protocol::SessionSource; +use rmcp::model::CallToolRequestParam; +use rmcp::model::CallToolResult; +use rmcp::model::ClientNotification; +use rmcp::model::ClientRequest; +use rmcp::model::ErrorCode; +use rmcp::model::ErrorData; +use rmcp::model::Implementation; +use rmcp::model::InitializeResult; +use rmcp::model::JsonRpcError; +use rmcp::model::JsonRpcNotification; +use rmcp::model::JsonRpcRequest; +use rmcp::model::JsonRpcResponse; +use rmcp::model::RequestId; +use rmcp::model::ServerCapabilities; +use rmcp::model::ToolsCapability; use serde_json::json; use std::sync::Arc; use tokio::sync::Mutex; use tokio::task; +use crate::codex_tool_config::CodexToolCallParam; +use crate::codex_tool_config::CodexToolCallReplyParam; +use crate::codex_tool_config::create_tool_for_codex_tool_call_param; +use crate::codex_tool_config::create_tool_for_codex_tool_call_reply_param; +use crate::outgoing_message::OutgoingMessageSender; + pub(crate) struct MessageProcessor { outgoing: Arc, initialized: bool, @@ -72,126 +71,108 @@ impl MessageProcessor { } } - pub(crate) async fn process_request(&mut self, request: JSONRPCRequest) { - // Hold on to the ID so we can respond. + pub(crate) async fn process_request(&mut self, request: JsonRpcRequest) { let request_id = request.id.clone(); + let client_request = request.request; - let client_request = match McpClientRequest::try_from(request) { - Ok(client_request) => client_request, - Err(e) => { - tracing::warn!("Failed to convert request: {e}"); - return; - } - }; - - // Dispatch to a dedicated handler for each request type. match client_request { - McpClientRequest::InitializeRequest(params) => { - self.handle_initialize(request_id, params).await; + ClientRequest::InitializeRequest(params) => { + self.handle_initialize(request_id, params.params).await; } - McpClientRequest::PingRequest(params) => { - self.handle_ping(request_id, params).await; + ClientRequest::PingRequest(_params) => { + self.handle_ping(request_id).await; } - McpClientRequest::ListResourcesRequest(params) => { - self.handle_list_resources(params); + ClientRequest::ListResourcesRequest(params) => { + self.handle_list_resources(params.params); } - McpClientRequest::ListResourceTemplatesRequest(params) => { - self.handle_list_resource_templates(params); + ClientRequest::ListResourceTemplatesRequest(params) => { + self.handle_list_resource_templates(params.params); } - McpClientRequest::ReadResourceRequest(params) => { - self.handle_read_resource(params); + ClientRequest::ReadResourceRequest(params) => { + self.handle_read_resource(params.params); } - McpClientRequest::SubscribeRequest(params) => { - self.handle_subscribe(params); + ClientRequest::SubscribeRequest(params) => { + self.handle_subscribe(params.params); } - McpClientRequest::UnsubscribeRequest(params) => { - self.handle_unsubscribe(params); + ClientRequest::UnsubscribeRequest(params) => { + self.handle_unsubscribe(params.params); } - McpClientRequest::ListPromptsRequest(params) => { - self.handle_list_prompts(params); + ClientRequest::ListPromptsRequest(params) => { + self.handle_list_prompts(params.params); } - McpClientRequest::GetPromptRequest(params) => { - self.handle_get_prompt(params); + ClientRequest::GetPromptRequest(params) => { + self.handle_get_prompt(params.params); } - McpClientRequest::ListToolsRequest(params) => { - self.handle_list_tools(request_id, params).await; + ClientRequest::ListToolsRequest(params) => { + self.handle_list_tools(request_id, params.params).await; } - McpClientRequest::CallToolRequest(params) => { - self.handle_call_tool(request_id, params).await; + ClientRequest::CallToolRequest(params) => { + self.handle_call_tool(request_id, params.params).await; } - McpClientRequest::SetLevelRequest(params) => { - self.handle_set_level(params); + ClientRequest::SetLevelRequest(params) => { + self.handle_set_level(params.params); } - McpClientRequest::CompleteRequest(params) => { - self.handle_complete(params); + ClientRequest::CompleteRequest(params) => { + self.handle_complete(params.params); + } + ClientRequest::CustomRequest(custom) => { + self.outgoing + .send_error( + request_id, + ErrorData::new(ErrorCode::METHOD_NOT_FOUND, custom.method, None), + ) + .await; } } } - /// Handle a standalone JSON-RPC response originating from the peer. - pub(crate) async fn process_response(&mut self, response: JSONRPCResponse) { + pub(crate) async fn process_response(&mut self, response: JsonRpcResponse) { tracing::info!("<- response: {:?}", response); - let JSONRPCResponse { id, result, .. } = response; + let JsonRpcResponse { id, result, .. } = response; self.outgoing.notify_client_response(id, result).await } - /// Handle a fire-and-forget JSON-RPC notification. - pub(crate) async fn process_notification(&mut self, notification: JSONRPCNotification) { - let server_notification = match ServerNotification::try_from(notification) { - Ok(n) => n, - Err(e) => { - tracing::warn!("Failed to convert notification: {e}"); - return; + pub(crate) async fn process_notification( + &mut self, + notification: JsonRpcNotification, + ) { + match notification.notification { + ClientNotification::CancelledNotification(params) => { + self.handle_cancelled_notification(params.params).await; } - }; - - // Similar to requests, route each notification type to its own stub - // handler so additional logic can be implemented incrementally. - match server_notification { - ServerNotification::CancelledNotification(params) => { - self.handle_cancelled_notification(params).await; + ClientNotification::ProgressNotification(params) => { + self.handle_progress_notification(params.params); } - ServerNotification::ProgressNotification(params) => { - self.handle_progress_notification(params); + ClientNotification::RootsListChangedNotification(_params) => { + self.handle_roots_list_changed(); } - ServerNotification::ResourceListChangedNotification(params) => { - self.handle_resource_list_changed(params); + ClientNotification::InitializedNotification(_) => { + self.handle_initialized_notification(); } - ServerNotification::ResourceUpdatedNotification(params) => { - self.handle_resource_updated(params); - } - ServerNotification::PromptListChangedNotification(params) => { - self.handle_prompt_list_changed(params); - } - ServerNotification::ToolListChangedNotification(params) => { - self.handle_tool_list_changed(params); - } - ServerNotification::LoggingMessageNotification(params) => { - self.handle_logging_message(params); + ClientNotification::CustomNotification(_) => { + tracing::warn!("ignoring custom client notification"); } } } - /// Handle an error object received from the peer. - pub(crate) fn process_error(&mut self, err: JSONRPCError) { + pub(crate) fn process_error(&mut self, err: JsonRpcError) { tracing::error!("<- error: {:?}", err); } async fn handle_initialize( &mut self, id: RequestId, - params: ::Params, + params: rmcp::model::InitializeRequestParam, ) { tracing::info!("initialize -> params: {:?}", params); if self.initialized { - // Already initialised: send JSON-RPC error response. - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: "initialize called more than once".to_string(), - data: None, - }; - self.outgoing.send_error(id, error).await; + self.outgoing + .send_error( + id, + ErrorData::invalid_request("initialize called more than once", None), + ) + .await; return; } @@ -203,109 +184,108 @@ impl MessageProcessor { *suffix = Some(user_agent_suffix); } - self.initialized = true; + let server_info = Implementation { + name: "codex-mcp-server".to_string(), + title: Some("Codex".to_string()), + version: env!("CARGO_PKG_VERSION").to_string(), + icons: None, + website_url: None, + }; - // Build a minimal InitializeResult. Fill with placeholders. - let result = mcp_types::InitializeResult { - capabilities: mcp_types::ServerCapabilities { - completions: None, - experimental: None, - logging: None, - prompts: None, - resources: None, - tools: Some(ServerCapabilitiesTools { + // Preserve Codex's existing non-spec `serverInfo.user_agent` field. + let mut server_info_value = match serde_json::to_value(&server_info) { + Ok(value) => value, + Err(err) => { + self.outgoing + .send_error( + id, + ErrorData::internal_error( + format!("failed to serialize server info: {err}"), + None, + ), + ) + .await; + return; + } + }; + if let serde_json::Value::Object(ref mut obj) = server_info_value { + obj.insert("user_agent".to_string(), json!(get_codex_user_agent())); + } + + let mut result_value = match serde_json::to_value(InitializeResult { + capabilities: ServerCapabilities { + tools: Some(ToolsCapability { list_changed: Some(true), }), + ..Default::default() }, instructions: None, protocol_version: params.protocol_version.clone(), - server_info: mcp_types::Implementation { - name: "codex-mcp-server".to_string(), - version: env!("CARGO_PKG_VERSION").to_string(), - title: Some("Codex".to_string()), - user_agent: Some(get_codex_user_agent()), - }, + server_info, + }) { + Ok(value) => value, + Err(err) => { + self.outgoing + .send_error( + id, + ErrorData::internal_error( + format!("failed to serialize initialize response: {err}"), + None, + ), + ) + .await; + return; + } }; - self.send_response::(id, result) - .await; + if let serde_json::Value::Object(ref mut obj) = result_value { + obj.insert("serverInfo".to_string(), server_info_value); + } + + self.initialized = true; + self.outgoing.send_response(id, result_value).await; } - async fn send_response(&self, id: RequestId, result: T::Result) - where - T: ModelContextProtocolRequest, - { - self.outgoing.send_response(id, result).await; + async fn handle_ping(&self, id: RequestId) { + tracing::info!("ping"); + self.outgoing.send_response(id, json!({})).await; } - async fn handle_ping( - &self, - id: RequestId, - params: ::Params, - ) { - tracing::info!("ping -> params: {:?}", params); - let result = json!({}); - self.send_response::(id, result) - .await; - } - - fn handle_list_resources( - &self, - params: ::Params, - ) { + fn handle_list_resources(&self, params: Option) { tracing::info!("resources/list -> params: {:?}", params); } - fn handle_list_resource_templates( - &self, - params: - ::Params, - ) { + fn handle_list_resource_templates(&self, params: Option) { tracing::info!("resources/templates/list -> params: {:?}", params); } - fn handle_read_resource( - &self, - params: ::Params, - ) { + fn handle_read_resource(&self, params: rmcp::model::ReadResourceRequestParam) { tracing::info!("resources/read -> params: {:?}", params); } - fn handle_subscribe( - &self, - params: ::Params, - ) { + fn handle_subscribe(&self, params: rmcp::model::SubscribeRequestParam) { tracing::info!("resources/subscribe -> params: {:?}", params); } - fn handle_unsubscribe( - &self, - params: ::Params, - ) { + fn handle_unsubscribe(&self, params: rmcp::model::UnsubscribeRequestParam) { tracing::info!("resources/unsubscribe -> params: {:?}", params); } - fn handle_list_prompts( - &self, - params: ::Params, - ) { + fn handle_list_prompts(&self, params: Option) { tracing::info!("prompts/list -> params: {:?}", params); } - fn handle_get_prompt( - &self, - params: ::Params, - ) { + fn handle_get_prompt(&self, params: rmcp::model::GetPromptRequestParam) { tracing::info!("prompts/get -> params: {:?}", params); } async fn handle_list_tools( &self, id: RequestId, - params: ::Params, + _params: Option, ) { - tracing::trace!("tools/list -> {params:?}"); - let result = ListToolsResult { + let result = rmcp::model::ListToolsResult { + meta: None, tools: vec![ create_tool_for_codex_tool_call_param(), create_tool_for_codex_tool_call_reply_param(), @@ -313,19 +293,14 @@ impl MessageProcessor { next_cursor: None, }; - self.send_response::(id, result) - .await; + self.outgoing.send_response(id, result).await; } - async fn handle_call_tool( - &self, - id: RequestId, - params: ::Params, - ) { + async fn handle_call_tool(&self, id: RequestId, params: CallToolRequestParam) { tracing::info!("tools/call -> params: {:?}", params); - let CallToolRequestParams { name, arguments } = params; + let CallToolRequestParam { name, arguments } = params; - match name.as_str() { + match name.as_ref() { "codex" => self.handle_tool_call_codex(id, arguments).await, "codex-reply" => { self.handle_tool_call_codex_session_reply(id, arguments) @@ -333,20 +308,22 @@ impl MessageProcessor { } _ => { let result = CallToolResult { - content: vec![ContentBlock::TextContent(TextContent { - r#type: "text".to_string(), - text: format!("Unknown tool '{name}'"), - annotations: None, - })], - is_error: Some(true), + content: vec![rmcp::model::Content::text(format!("Unknown tool '{name}'"))], structured_content: None, + is_error: Some(true), + meta: None, }; - self.send_response::(id, result) - .await; + self.outgoing.send_response(id, result).await; } } } - async fn handle_tool_call_codex(&self, id: RequestId, arguments: Option) { + + async fn handle_tool_call_codex( + &self, + id: RequestId, + arguments: Option, + ) { + let arguments = arguments.map(serde_json::Value::Object); let (initial_prompt, config): (String, Config) = match arguments { Some(json_val) => match serde_json::from_value::(json_val) { Ok(tool_cfg) => match tool_cfg @@ -356,63 +333,49 @@ impl MessageProcessor { Ok(cfg) => cfg, Err(e) => { let result = CallToolResult { - content: vec![ContentBlock::TextContent(TextContent { - r#type: "text".to_owned(), - text: format!( - "Failed to load Codex configuration from overrides: {e}" - ), - annotations: None, - })], - is_error: Some(true), + content: vec![rmcp::model::Content::text(format!( + "Failed to load Codex configuration from overrides: {e}" + ))], structured_content: None, + is_error: Some(true), + meta: None, }; - self.send_response::(id, result) - .await; + self.outgoing.send_response(id, result).await; return; } }, Err(e) => { let result = CallToolResult { - content: vec![ContentBlock::TextContent(TextContent { - r#type: "text".to_owned(), - text: format!("Failed to parse configuration for Codex tool: {e}"), - annotations: None, - })], - is_error: Some(true), + content: vec![rmcp::model::Content::text(format!( + "Failed to parse configuration for Codex tool: {e}" + ))], structured_content: None, + is_error: Some(true), + meta: None, }; - self.send_response::(id, result) - .await; + self.outgoing.send_response(id, result).await; return; } }, None => { let result = CallToolResult { - content: vec![ContentBlock::TextContent(TextContent { - r#type: "text".to_string(), - text: - "Missing arguments for codex tool-call; the `prompt` field is required." - .to_string(), - annotations: None, - })], - is_error: Some(true), + content: vec![rmcp::model::Content::text( + "Missing arguments for codex tool-call; the `prompt` field is required.", + )], structured_content: None, + is_error: Some(true), + meta: None, }; - self.send_response::(id, result) - .await; + self.outgoing.send_response(id, result).await; return; } }; - // Clone outgoing and server to move into async task. let outgoing = self.outgoing.clone(); let thread_manager = self.thread_manager.clone(); let running_requests_id_to_codex_uuid = self.running_requests_id_to_codex_uuid.clone(); - // Spawn an async task to handle the Codex session so that we do not - // block the synchronous message-processing loop. task::spawn(async move { - // Run the Codex session and stream events back to the client. crate::codex_tool_runner::run_codex_tool_session( id, initial_prompt, @@ -428,27 +391,25 @@ impl MessageProcessor { async fn handle_tool_call_codex_session_reply( &self, request_id: RequestId, - arguments: Option, + arguments: Option, ) { + let arguments = arguments.map(serde_json::Value::Object); tracing::info!("tools/call -> params: {:?}", arguments); - // parse arguments let codex_tool_call_reply_param: CodexToolCallReplyParam = match arguments { Some(json_val) => match serde_json::from_value::(json_val) { Ok(params) => params, Err(e) => { tracing::error!("Failed to parse Codex tool call reply parameters: {e}"); let result = CallToolResult { - content: vec![ContentBlock::TextContent(TextContent { - r#type: "text".to_owned(), - text: format!("Failed to parse configuration for Codex tool: {e}"), - annotations: None, - })], - is_error: Some(true), + content: vec![rmcp::model::Content::text(format!( + "Failed to parse configuration for Codex tool: {e}" + ))], structured_content: None, + is_error: Some(true), + meta: None, }; - self.send_response::(request_id, result) - .await; + self.outgoing.send_response(request_id, result).await; return; } }, @@ -457,16 +418,14 @@ impl MessageProcessor { "Missing arguments for codex-reply tool-call; the `thread_id` and `prompt` fields are required." ); let result = CallToolResult { - content: vec![ContentBlock::TextContent(TextContent { - r#type: "text".to_owned(), - text: "Missing arguments for codex-reply tool-call; the `thread_id` and `prompt` fields are required.".to_owned(), - annotations: None, - })], - is_error: Some(true), + content: vec![rmcp::model::Content::text( + "Missing arguments for codex-reply tool-call; the `thread_id` and `prompt` fields are required.", + )], structured_content: None, + is_error: Some(true), + meta: None, }; - self.send_response::(request_id, result) - .await; + self.outgoing.send_response(request_id, result).await; return; } }; @@ -476,21 +435,18 @@ impl MessageProcessor { Err(e) => { tracing::error!("Failed to parse thread_id: {e}"); let result = CallToolResult { - content: vec![ContentBlock::TextContent(TextContent { - r#type: "text".to_owned(), - text: format!("Failed to parse thread_id: {e}"), - annotations: None, - })], - is_error: Some(true), + content: vec![rmcp::model::Content::text(format!( + "Failed to parse thread_id: {e}" + ))], structured_content: None, + is_error: Some(true), + meta: None, }; - self.send_response::(request_id, result) - .await; + self.outgoing.send_response(request_id, result).await; return; } }; - // Clone outgoing to move into async task. let outgoing = self.outgoing.clone(); let running_requests_id_to_codex_uuid = self.running_requests_id_to_codex_uuid.clone(); @@ -508,7 +464,6 @@ impl MessageProcessor { } }; - // Spawn the long-running reply handler. let prompt = codex_tool_call_reply_param.prompt.clone(); tokio::spawn({ let outgoing = outgoing.clone(); @@ -528,49 +483,30 @@ impl MessageProcessor { }); } - fn handle_set_level( - &self, - params: ::Params, - ) { + fn handle_set_level(&self, params: rmcp::model::SetLevelRequestParam) { tracing::info!("logging/setLevel -> params: {:?}", params); } - fn handle_complete( - &self, - params: ::Params, - ) { + fn handle_complete(&self, params: rmcp::model::CompleteRequestParam) { tracing::info!("completion/complete -> params: {:?}", params); } - // --------------------------------------------------------------------- - // Notification handlers - // --------------------------------------------------------------------- - - async fn handle_cancelled_notification( - &self, - params: ::Params, - ) { + async fn handle_cancelled_notification(&self, params: rmcp::model::CancelledNotificationParam) { let request_id = params.request_id; - // Create a stable string form early for logging and submission id. - let request_id_string = match &request_id { - RequestId::String(s) => s.clone(), - RequestId::Integer(i) => i.to_string(), - }; + let request_id_string = request_id.to_string(); - // Obtain the thread id while holding the first lock, then release. let thread_id = { let map_guard = self.running_requests_id_to_codex_uuid.lock().await; match map_guard.get(&request_id) { Some(id) => *id, None => { - tracing::warn!("Session not found for request_id: {}", request_id_string); + tracing::warn!("Session not found for request_id: {request_id_string}"); return; } } }; tracing::info!("thread_id: {thread_id}"); - // Obtain the Codex thread from the server. let codex_arc = match self.thread_manager.get_thread(thread_id).await { Ok(c) => c, Err(_) => { @@ -579,66 +515,31 @@ impl MessageProcessor { } }; - // Submit interrupt to Codex. - let err = codex_arc + if let Err(e) = codex_arc .submit_with_id(Submission { id: request_id_string, op: codex_core::protocol::Op::Interrupt, }) - .await; - if let Err(e) = err { + .await + { tracing::error!("Failed to submit interrupt to Codex: {e}"); return; } - // unregister the id so we don't keep it in the map self.running_requests_id_to_codex_uuid .lock() .await .remove(&request_id); } - fn handle_progress_notification( - &self, - params: ::Params, - ) { + fn handle_progress_notification(&self, params: rmcp::model::ProgressNotificationParam) { tracing::info!("notifications/progress -> params: {:?}", params); } - fn handle_resource_list_changed( - &self, - params: ::Params, - ) { - tracing::info!( - "notifications/resources/list_changed -> params: {:?}", - params - ); + fn handle_roots_list_changed(&self) { + tracing::info!("notifications/roots/list_changed"); } - fn handle_resource_updated( - &self, - params: ::Params, - ) { - tracing::info!("notifications/resources/updated -> params: {:?}", params); - } - - fn handle_prompt_list_changed( - &self, - params: ::Params, - ) { - tracing::info!("notifications/prompts/list_changed -> params: {:?}", params); - } - - fn handle_tool_list_changed( - &self, - params: ::Params, - ) { - tracing::info!("notifications/tools/list_changed -> params: {:?}", params); - } - - fn handle_logging_message( - &self, - params: ::Params, - ) { - tracing::info!("notifications/message -> params: {:?}", params); + fn handle_initialized_notification(&self) { + tracing::info!("notifications/initialized"); } } diff --git a/codex-rs/mcp-server/src/outgoing_message.rs b/codex-rs/mcp-server/src/outgoing_message.rs index 954e50d9de..8dd5a1c4bc 100644 --- a/codex-rs/mcp-server/src/outgoing_message.rs +++ b/codex-rs/mcp-server/src/outgoing_message.rs @@ -4,28 +4,30 @@ use std::sync::atomic::Ordering; use codex_core::protocol::Event; use codex_protocol::ThreadId; -use mcp_types::JSONRPC_VERSION; -use mcp_types::JSONRPCError; -use mcp_types::JSONRPCErrorError; -use mcp_types::JSONRPCMessage; -use mcp_types::JSONRPCNotification; -use mcp_types::JSONRPCRequest; -use mcp_types::JSONRPCResponse; -use mcp_types::RequestId; -use mcp_types::Result; +use rmcp::model::CustomNotification; +use rmcp::model::CustomRequest; +use rmcp::model::ErrorData; +use rmcp::model::JsonRpcError; +use rmcp::model::JsonRpcMessage; +use rmcp::model::JsonRpcNotification; +use rmcp::model::JsonRpcRequest; +use rmcp::model::JsonRpcResponse; +use rmcp::model::JsonRpcVersion2_0; +use rmcp::model::RequestId; use serde::Serialize; +use serde_json::Value; use tokio::sync::Mutex; use tokio::sync::mpsc; use tokio::sync::oneshot; use tracing::warn; -use crate::error_code::INTERNAL_ERROR_CODE; +pub(crate) type OutgoingJsonRpcMessage = JsonRpcMessage; /// Sends messages to the client and manages request callbacks. pub(crate) struct OutgoingMessageSender { next_request_id: AtomicI64, sender: mpsc::UnboundedSender, - request_id_to_callback: Mutex>>, + request_id_to_callback: Mutex>>, } impl OutgoingMessageSender { @@ -41,8 +43,8 @@ impl OutgoingMessageSender { &self, method: &str, params: Option, - ) -> oneshot::Receiver { - let id = RequestId::Integer(self.next_request_id.fetch_add(1, Ordering::Relaxed)); + ) -> oneshot::Receiver { + let id = RequestId::Number(self.next_request_id.fetch_add(1, Ordering::Relaxed)); let outgoing_message_id = id.clone(); let (tx_approve, rx_approve) = oneshot::channel(); { @@ -59,7 +61,7 @@ impl OutgoingMessageSender { rx_approve } - pub(crate) async fn notify_client_response(&self, id: RequestId, result: Result) { + pub(crate) async fn notify_client_response(&self, id: RequestId, result: Value) { let entry = { let mut request_id_to_callback = self.request_id_to_callback.lock().await; request_id_to_callback.remove_entry(&id) @@ -78,23 +80,20 @@ impl OutgoingMessageSender { } pub(crate) async fn send_response(&self, id: RequestId, response: T) { - match serde_json::to_value(response) { - Ok(result) => { - let outgoing_message = OutgoingMessage::Response(OutgoingResponse { id, result }); - let _ = self.sender.send(outgoing_message); - } + let result = match serde_json::to_value(response) { + Ok(result) => result, Err(err) => { self.send_error( id, - JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("failed to serialize response: {err}"), - data: None, - }, + ErrorData::internal_error(format!("failed to serialize response: {err}"), None), ) .await; + return; } - } + }; + + let outgoing_message = OutgoingMessage::Response(OutgoingResponse { id, result }); + let _ = self.sender.send(outgoing_message); } /// This is used with the MCP server, but not the more general JSON-RPC app @@ -130,7 +129,7 @@ impl OutgoingMessageSender { let _ = self.sender.send(outgoing_message); } - pub(crate) async fn send_error(&self, id: RequestId, error: JSONRPCErrorError) { + pub(crate) async fn send_error(&self, id: RequestId, error: ErrorData) { let outgoing_message = OutgoingMessage::Error(OutgoingError { id, error }); let _ = self.sender.send(outgoing_message); } @@ -144,34 +143,32 @@ pub(crate) enum OutgoingMessage { Error(OutgoingError), } -impl From for JSONRPCMessage { +impl From for OutgoingJsonRpcMessage { fn from(val: OutgoingMessage) -> Self { use OutgoingMessage::*; match val { Request(OutgoingRequest { id, method, params }) => { - JSONRPCMessage::Request(JSONRPCRequest { - jsonrpc: JSONRPC_VERSION.into(), + JsonRpcMessage::Request(JsonRpcRequest { + jsonrpc: JsonRpcVersion2_0, id, - method, - params, + request: CustomRequest::new(method, params), }) } Notification(OutgoingNotification { method, params }) => { - JSONRPCMessage::Notification(JSONRPCNotification { - jsonrpc: JSONRPC_VERSION.into(), - method, - params, + JsonRpcMessage::Notification(JsonRpcNotification { + jsonrpc: JsonRpcVersion2_0, + notification: CustomNotification::new(method, params), }) } Response(OutgoingResponse { id, result }) => { - JSONRPCMessage::Response(JSONRPCResponse { - jsonrpc: JSONRPC_VERSION.into(), + JsonRpcMessage::Response(JsonRpcResponse { + jsonrpc: JsonRpcVersion2_0, id, result, }) } - Error(OutgoingError { id, error }) => JSONRPCMessage::Error(JSONRPCError { - jsonrpc: JSONRPC_VERSION.into(), + Error(OutgoingError { id, error }) => JsonRpcMessage::Error(JsonRpcError { + jsonrpc: JsonRpcVersion2_0, id, error, }), @@ -220,12 +217,12 @@ pub(crate) struct OutgoingNotificationMeta { #[derive(Debug, Clone, PartialEq, Serialize)] pub(crate) struct OutgoingResponse { pub id: RequestId, - pub result: Result, + pub result: Value, } #[derive(Debug, Clone, PartialEq, Serialize)] pub(crate) struct OutgoingError { - pub error: JSONRPCErrorError, + pub error: ErrorData, pub id: RequestId, } @@ -316,7 +313,7 @@ mod tests { msg: EventMsg::SessionConfigured(session_configured_event.clone()), }; let meta = OutgoingNotificationMeta { - request_id: Some(RequestId::String("123".to_string())), + request_id: Some(RequestId::String("123".into())), thread_id: None, }; @@ -381,7 +378,7 @@ mod tests { msg: EventMsg::SessionConfigured(session_configured_event.clone()), }; let meta = OutgoingNotificationMeta { - request_id: Some(RequestId::String("123".to_string())), + request_id: Some(RequestId::String("123".into())), thread_id: Some(thread_id), }; diff --git a/codex-rs/mcp-server/src/patch_approval.rs b/codex-rs/mcp-server/src/patch_approval.rs index 5c3073959d..fc9b449da6 100644 --- a/codex-rs/mcp-server/src/patch_approval.rs +++ b/codex-rs/mcp-server/src/patch_approval.rs @@ -7,24 +7,21 @@ use codex_core::protocol::FileChange; use codex_core::protocol::Op; use codex_core::protocol::ReviewDecision; use codex_protocol::ThreadId; -use mcp_types::ElicitRequest; -use mcp_types::ElicitRequestParamsRequestedSchema; -use mcp_types::JSONRPCErrorError; -use mcp_types::ModelContextProtocolRequest; -use mcp_types::RequestId; +use rmcp::model::ElicitationSchema; +use rmcp::model::ErrorData; +use rmcp::model::RequestId; use serde::Deserialize; use serde::Serialize; -use serde_json::json; use tracing::error; -use crate::codex_tool_runner::INVALID_PARAMS_ERROR_CODE; use crate::outgoing_message::OutgoingMessageSender; +use std::collections::BTreeMap; #[derive(Debug, Deserialize, Serialize)] pub struct PatchApprovalElicitRequestParams { pub message: String, #[serde(rename = "requestedSchema")] - pub requested_schema: ElicitRequestParamsRequestedSchema, + pub requested_schema: ElicitationSchema, #[serde(rename = "threadId")] pub thread_id: ThreadId, pub codex_elicitation: String, @@ -64,11 +61,7 @@ pub(crate) async fn handle_patch_approval_request( let params = PatchApprovalElicitRequestParams { message: message_lines.join("\n"), - requested_schema: ElicitRequestParamsRequestedSchema { - r#type: "object".to_string(), - properties: json!({}), - required: None, - }, + requested_schema: ElicitationSchema::new(BTreeMap::new()), thread_id, codex_elicitation: "patch-approval".to_string(), codex_mcp_tool_call_id: tool_call_id.clone(), @@ -85,14 +78,7 @@ pub(crate) async fn handle_patch_approval_request( error!("{message}"); outgoing - .send_error( - request_id.clone(), - JSONRPCErrorError { - code: INVALID_PARAMS_ERROR_CODE, - message, - data: None, - }, - ) + .send_error(request_id.clone(), ErrorData::invalid_params(message, None)) .await; return; @@ -100,7 +86,7 @@ pub(crate) async fn handle_patch_approval_request( }; let on_response = outgoing - .send_request(ElicitRequest::METHOD, Some(params_json)) + .send_request("elicitation/create", Some(params_json)) .await; // Listen for the response on a separate task so we don't block the main agent loop. @@ -115,7 +101,7 @@ pub(crate) async fn handle_patch_approval_request( pub(crate) async fn on_patch_approval_response( event_id: String, - receiver: tokio::sync::oneshot::Receiver, + receiver: tokio::sync::oneshot::Receiver, codex: Arc, ) { let response = receiver.await; diff --git a/codex-rs/mcp-server/tests/common/Cargo.toml b/codex-rs/mcp-server/tests/common/Cargo.toml index aba984edab..1dec2d09ac 100644 --- a/codex-rs/mcp-server/tests/common/Cargo.toml +++ b/codex-rs/mcp-server/tests/common/Cargo.toml @@ -12,7 +12,7 @@ anyhow = { workspace = true } codex-core = { workspace = true } codex-mcp-server = { workspace = true } codex-utils-cargo-bin = { workspace = true } -mcp-types = { workspace = true } +rmcp = { workspace = true } os_info = { workspace = true } pretty_assertions = { workspace = true } serde = { workspace = true } diff --git a/codex-rs/mcp-server/tests/common/lib.rs b/codex-rs/mcp-server/tests/common/lib.rs index 364c708651..c2c3757efc 100644 --- a/codex-rs/mcp-server/tests/common/lib.rs +++ b/codex-rs/mcp-server/tests/common/lib.rs @@ -6,14 +6,16 @@ pub use core_test_support::format_with_current_shell; pub use core_test_support::format_with_current_shell_display_non_login; pub use core_test_support::format_with_current_shell_non_login; pub use mcp_process::McpProcess; -use mcp_types::JSONRPCResponse; pub use mock_model_server::create_mock_chat_completions_server; pub use responses::create_apply_patch_sse_response; pub use responses::create_final_assistant_message_sse_response; pub use responses::create_shell_command_sse_response; +use rmcp::model::JsonRpcResponse; use serde::de::DeserializeOwned; -pub fn to_response(response: JSONRPCResponse) -> anyhow::Result { +pub fn to_response( + response: JsonRpcResponse, +) -> anyhow::Result { let value = serde_json::to_value(response.result)?; let codex_response = serde_json::from_value(value)?; Ok(codex_response) diff --git a/codex-rs/mcp-server/tests/common/mcp_process.rs b/codex-rs/mcp-server/tests/common/mcp_process.rs index 9a3f076fb1..c019120282 100644 --- a/codex-rs/mcp-server/tests/common/mcp_process.rs +++ b/codex-rs/mcp-server/tests/common/mcp_process.rs @@ -12,19 +12,21 @@ use tokio::process::ChildStdout; use anyhow::Context; use codex_mcp_server::CodexToolCallParam; -use mcp_types::CallToolRequestParams; -use mcp_types::ClientCapabilities; -use mcp_types::Implementation; -use mcp_types::InitializeRequestParams; -use mcp_types::JSONRPC_VERSION; -use mcp_types::JSONRPCMessage; -use mcp_types::JSONRPCNotification; -use mcp_types::JSONRPCRequest; -use mcp_types::JSONRPCResponse; -use mcp_types::ModelContextProtocolNotification; -use mcp_types::ModelContextProtocolRequest; -use mcp_types::RequestId; use pretty_assertions::assert_eq; +use rmcp::model::CallToolRequestParam; +use rmcp::model::ClientCapabilities; +use rmcp::model::CustomNotification; +use rmcp::model::CustomRequest; +use rmcp::model::ElicitationCapability; +use rmcp::model::Implementation; +use rmcp::model::InitializeRequestParam; +use rmcp::model::JsonRpcMessage; +use rmcp::model::JsonRpcNotification; +use rmcp::model::JsonRpcRequest; +use rmcp::model::JsonRpcResponse; +use rmcp::model::JsonRpcVersion2_0; +use rmcp::model::ProtocolVersion; +use rmcp::model::RequestId; use serde_json::json; use tokio::process::Command; @@ -110,9 +112,11 @@ impl McpProcess { pub async fn initialize(&mut self) -> anyhow::Result<()> { let request_id = self.next_request_id.fetch_add(1, Ordering::Relaxed); - let params = InitializeRequestParams { + let params = InitializeRequestParam { capabilities: ClientCapabilities { - elicitation: Some(json!({})), + elicitation: Some(ElicitationCapability { + schema_validation: None, + }), experimental: None, roots: None, sampling: None, @@ -121,17 +125,17 @@ impl McpProcess { name: "elicitation test".into(), title: Some("Elicitation Test".into()), version: "0.0.0".into(), - user_agent: None, + icons: None, + website_url: None, }, - protocol_version: mcp_types::MCP_SCHEMA_VERSION.into(), + protocol_version: ProtocolVersion::V_2025_03_26, }; let params_value = serde_json::to_value(params)?; - self.send_jsonrpc_message(JSONRPCMessage::Request(JSONRPCRequest { - jsonrpc: JSONRPC_VERSION.into(), - id: RequestId::Integer(request_id), - method: mcp_types::InitializeRequest::METHOD.into(), - params: Some(params_value), + self.send_jsonrpc_message(JsonRpcMessage::Request(JsonRpcRequest { + jsonrpc: JsonRpcVersion2_0, + id: RequestId::Number(request_id), + request: CustomRequest::new("initialize", Some(params_value)), })) .await?; @@ -146,33 +150,38 @@ impl McpProcess { os_info.architecture().unwrap_or("unknown"), codex_core::terminal::user_agent() ); + let JsonRpcMessage::Response(JsonRpcResponse { + jsonrpc, + id, + result, + }) = initialized + else { + anyhow::bail!("expected initialize response message, got: {initialized:?}") + }; + assert_eq!(jsonrpc, JsonRpcVersion2_0); + assert_eq!(id, RequestId::Number(request_id)); assert_eq!( - JSONRPCMessage::Response(JSONRPCResponse { - jsonrpc: JSONRPC_VERSION.into(), - id: RequestId::Integer(request_id), - result: json!({ - "capabilities": { - "tools": { - "listChanged": true - }, + result, + json!({ + "capabilities": { + "tools": { + "listChanged": true }, - "serverInfo": { - "name": "codex-mcp-server", - "title": "Codex", - "version": "0.0.0", - "user_agent": user_agent - }, - "protocolVersion": mcp_types::MCP_SCHEMA_VERSION - }) - }), - initialized + }, + "serverInfo": { + "name": "codex-mcp-server", + "title": "Codex", + "version": "0.0.0", + "user_agent": user_agent + }, + "protocolVersion": ProtocolVersion::V_2025_03_26 + }) ); // Send notifications/initialized to ack the response. - self.send_jsonrpc_message(JSONRPCMessage::Notification(JSONRPCNotification { - jsonrpc: JSONRPC_VERSION.into(), - method: mcp_types::InitializedNotification::METHOD.into(), - params: None, + self.send_jsonrpc_message(JsonRpcMessage::Notification(JsonRpcNotification { + jsonrpc: JsonRpcVersion2_0, + notification: CustomNotification::new("notifications/initialized", None), })) .await?; @@ -185,12 +194,15 @@ impl McpProcess { &mut self, params: CodexToolCallParam, ) -> anyhow::Result { - let codex_tool_call_params = CallToolRequestParams { - name: "codex".to_string(), - arguments: Some(serde_json::to_value(params)?), + let codex_tool_call_params = CallToolRequestParam { + name: "codex".into(), + arguments: Some(match serde_json::to_value(params)? { + serde_json::Value::Object(map) => map, + _ => unreachable!("params serialize to object"), + }), }; self.send_request( - mcp_types::CallToolRequest::METHOD, + "tools/call", Some(serde_json::to_value(codex_tool_call_params)?), ) .await @@ -203,11 +215,10 @@ impl McpProcess { ) -> anyhow::Result { let request_id = self.next_request_id.fetch_add(1, Ordering::Relaxed); - let message = JSONRPCMessage::Request(JSONRPCRequest { - jsonrpc: JSONRPC_VERSION.into(), - id: RequestId::Integer(request_id), - method: method.to_string(), - params, + let message = JsonRpcMessage::Request(JsonRpcRequest { + jsonrpc: JsonRpcVersion2_0, + id: RequestId::Number(request_id), + request: CustomRequest::new(method, params), }); self.send_jsonrpc_message(message).await?; Ok(request_id) @@ -218,15 +229,18 @@ impl McpProcess { id: RequestId, result: serde_json::Value, ) -> anyhow::Result<()> { - self.send_jsonrpc_message(JSONRPCMessage::Response(JSONRPCResponse { - jsonrpc: JSONRPC_VERSION.into(), + self.send_jsonrpc_message(JsonRpcMessage::Response(JsonRpcResponse { + jsonrpc: JsonRpcVersion2_0, id, result, })) .await } - async fn send_jsonrpc_message(&mut self, message: JSONRPCMessage) -> anyhow::Result<()> { + async fn send_jsonrpc_message( + &mut self, + message: JsonRpcMessage, + ) -> anyhow::Result<()> { eprintln!("writing message to stdin: {message:?}"); let payload = serde_json::to_string(&message)?; self.stdin.write_all(payload.as_bytes()).await?; @@ -235,31 +249,37 @@ impl McpProcess { Ok(()) } - async fn read_jsonrpc_message(&mut self) -> anyhow::Result { + async fn read_jsonrpc_message( + &mut self, + ) -> anyhow::Result> { let mut line = String::new(); self.stdout.read_line(&mut line).await?; - let message = serde_json::from_str::(&line)?; + let message = serde_json::from_str::< + JsonRpcMessage, + >(&line)?; eprintln!("read message from stdout: {message:?}"); Ok(message) } - pub async fn read_stream_until_request_message(&mut self) -> anyhow::Result { + pub async fn read_stream_until_request_message( + &mut self, + ) -> anyhow::Result> { eprintln!("in read_stream_until_request_message()"); loop { let message = self.read_jsonrpc_message().await?; match message { - JSONRPCMessage::Notification(_) => { + JsonRpcMessage::Notification(_) => { eprintln!("notification: {message:?}"); } - JSONRPCMessage::Request(jsonrpc_request) => { + JsonRpcMessage::Request(jsonrpc_request) => { return Ok(jsonrpc_request); } - JSONRPCMessage::Error(_) => { + JsonRpcMessage::Error(_) => { anyhow::bail!("unexpected JSONRPCMessage::Error: {message:?}"); } - JSONRPCMessage::Response(_) => { + JsonRpcMessage::Response(_) => { anyhow::bail!("unexpected JSONRPCMessage::Response: {message:?}"); } } @@ -269,22 +289,22 @@ impl McpProcess { pub async fn read_stream_until_response_message( &mut self, request_id: RequestId, - ) -> anyhow::Result { + ) -> anyhow::Result> { eprintln!("in read_stream_until_response_message({request_id:?})"); loop { let message = self.read_jsonrpc_message().await?; match message { - JSONRPCMessage::Notification(_) => { + JsonRpcMessage::Notification(_) => { eprintln!("notification: {message:?}"); } - JSONRPCMessage::Request(_) => { + JsonRpcMessage::Request(_) => { anyhow::bail!("unexpected JSONRPCMessage::Request: {message:?}"); } - JSONRPCMessage::Error(_) => { + JsonRpcMessage::Error(_) => { anyhow::bail!("unexpected JSONRPCMessage::Error: {message:?}"); } - JSONRPCMessage::Response(jsonrpc_response) => { + JsonRpcMessage::Response(jsonrpc_response) => { if jsonrpc_response.id == request_id { return Ok(jsonrpc_response); } @@ -297,15 +317,15 @@ impl McpProcess { /// Method "codex/event" with params.msg.type == "task_complete". pub async fn read_stream_until_legacy_task_complete_notification( &mut self, - ) -> anyhow::Result { + ) -> anyhow::Result> { eprintln!("in read_stream_until_legacy_task_complete_notification()"); loop { let message = self.read_jsonrpc_message().await?; match message { - JSONRPCMessage::Notification(notification) => { - let is_match = if notification.method == "codex/event" { - if let Some(params) = ¬ification.params { + JsonRpcMessage::Notification(notification) => { + let is_match = if notification.notification.method == "codex/event" { + if let Some(params) = ¬ification.notification.params { params .get("msg") .and_then(|m| m.get("type")) @@ -324,13 +344,13 @@ impl McpProcess { eprintln!("ignoring notification: {notification:?}"); } } - JSONRPCMessage::Request(_) => { + JsonRpcMessage::Request(_) => { anyhow::bail!("unexpected JSONRPCMessage::Request: {message:?}"); } - JSONRPCMessage::Error(_) => { + JsonRpcMessage::Error(_) => { anyhow::bail!("unexpected JSONRPCMessage::Error: {message:?}"); } - JSONRPCMessage::Response(_) => { + JsonRpcMessage::Response(_) => { anyhow::bail!("unexpected JSONRPCMessage::Response: {message:?}"); } } diff --git a/codex-rs/mcp-server/tests/suite/codex_tool.rs b/codex-rs/mcp-server/tests/suite/codex_tool.rs index 31c451d24f..b69806cc0b 100644 --- a/codex-rs/mcp-server/tests/suite/codex_tool.rs +++ b/codex-rs/mcp-server/tests/suite/codex_tool.rs @@ -12,14 +12,11 @@ use codex_mcp_server::ExecApprovalElicitRequestParams; use codex_mcp_server::ExecApprovalResponse; use codex_mcp_server::PatchApprovalElicitRequestParams; use codex_mcp_server::PatchApprovalResponse; -use mcp_types::ElicitRequest; -use mcp_types::ElicitRequestParamsRequestedSchema; -use mcp_types::JSONRPC_VERSION; -use mcp_types::JSONRPCRequest; -use mcp_types::JSONRPCResponse; -use mcp_types::ModelContextProtocolRequest; -use mcp_types::RequestId; use pretty_assertions::assert_eq; +use rmcp::model::ElicitationSchema; +use rmcp::model::JsonRpcResponse; +use rmcp::model::JsonRpcVersion2_0; +use rmcp::model::RequestId; use serde_json::json; use tempfile::TempDir; use tokio::time::timeout; @@ -106,22 +103,27 @@ async fn shell_command_approval_triggers_elicitation() -> anyhow::Result<()> { ) .await??; + assert_eq!(elicitation_request.jsonrpc, JsonRpcVersion2_0); + assert_eq!(elicitation_request.request.method, "elicitation/create"); + let elicitation_request_id = elicitation_request.id.clone(); let params = serde_json::from_value::( elicitation_request + .request .params .clone() .ok_or_else(|| anyhow::anyhow!("elicitation_request.params must be set"))?, )?; - let expected_elicitation_request = create_expected_elicitation_request( - elicitation_request_id.clone(), - expected_shell_command, - workdir_for_shell_function_call.path(), - codex_request_id.to_string(), - params.codex_event_id.clone(), - params.thread_id, - )?; - assert_eq!(expected_elicitation_request, elicitation_request); + assert_eq!( + elicitation_request.request.params, + Some(create_expected_elicitation_request_params( + expected_shell_command, + workdir_for_shell_function_call.path(), + codex_request_id.to_string(), + params.codex_event_id.clone(), + params.thread_id, + )?) + ); // Accept the `git init` request by responding to the elicitation. mcp_process @@ -146,13 +148,13 @@ async fn shell_command_approval_triggers_elicitation() -> anyhow::Result<()> { // Verify the original `codex` tool call completes and that the file was created. let codex_response = timeout( DEFAULT_READ_TIMEOUT, - mcp_process.read_stream_until_response_message(RequestId::Integer(codex_request_id)), + mcp_process.read_stream_until_response_message(RequestId::Number(codex_request_id)), ) .await??; assert_eq!( - JSONRPCResponse { - jsonrpc: JSONRPC_VERSION.into(), - id: RequestId::Integer(codex_request_id), + JsonRpcResponse { + jsonrpc: JsonRpcVersion2_0, + id: RequestId::Number(codex_request_id), result: json!({ "content": [ { @@ -174,41 +176,32 @@ async fn shell_command_approval_triggers_elicitation() -> anyhow::Result<()> { Ok(()) } -fn create_expected_elicitation_request( - elicitation_request_id: RequestId, +fn create_expected_elicitation_request_params( command: Vec, workdir: &Path, codex_mcp_tool_call_id: String, codex_event_id: String, thread_id: codex_protocol::ThreadId, -) -> anyhow::Result { +) -> anyhow::Result { let expected_message = format!( "Allow Codex to run `{}` in `{}`?", shlex::try_join(command.iter().map(std::convert::AsRef::as_ref))?, workdir.to_string_lossy() ); let codex_parsed_cmd = parse_command::parse_command(&command); - Ok(JSONRPCRequest { - jsonrpc: JSONRPC_VERSION.into(), - id: elicitation_request_id, - method: ElicitRequest::METHOD.to_string(), - params: Some(serde_json::to_value(&ExecApprovalElicitRequestParams { - message: expected_message, - requested_schema: ElicitRequestParamsRequestedSchema { - r#type: "object".to_string(), - properties: json!({}), - required: None, - }, - thread_id, - codex_elicitation: "exec-approval".to_string(), - codex_mcp_tool_call_id, - codex_event_id, - codex_command: command, - codex_cwd: workdir.to_path_buf(), - codex_call_id: "call1234".to_string(), - codex_parsed_cmd, - })?), - }) + let params_json = serde_json::to_value(ExecApprovalElicitRequestParams { + message: expected_message, + requested_schema: ElicitationSchema::new(std::collections::BTreeMap::new()), + thread_id, + codex_elicitation: "exec-approval".to_string(), + codex_mcp_tool_call_id, + codex_event_id, + codex_command: command, + codex_cwd: workdir.to_path_buf(), + codex_call_id: "call1234".to_string(), + codex_parsed_cmd, + })?; + Ok(params_json) } /// Test that patch approval triggers an elicitation request to the MCP and that @@ -267,9 +260,13 @@ async fn patch_approval_triggers_elicitation() -> anyhow::Result<()> { ) .await??; + assert_eq!(elicitation_request.jsonrpc, JsonRpcVersion2_0); + assert_eq!(elicitation_request.request.method, "elicitation/create"); + let elicitation_request_id = elicitation_request.id.clone(); let params = serde_json::from_value::( elicitation_request + .request .params .clone() .ok_or_else(|| anyhow::anyhow!("elicitation_request.params must be set"))?, @@ -284,16 +281,17 @@ async fn patch_approval_triggers_elicitation() -> anyhow::Result<()> { }, ); - let expected_elicitation_request = create_expected_patch_approval_elicitation_request( - elicitation_request_id.clone(), - expected_changes, - None, // No grant_root expected - None, // No reason expected - codex_request_id.to_string(), - params.codex_event_id.clone(), - params.thread_id, - )?; - assert_eq!(expected_elicitation_request, elicitation_request); + assert_eq!( + elicitation_request.request.params, + Some(create_expected_patch_approval_elicitation_request_params( + expected_changes, + None, // No grant_root expected + None, // No reason expected + codex_request_id.to_string(), + params.codex_event_id.clone(), + params.thread_id, + )?) + ); // Accept the patch approval request by responding to the elicitation mcp_process @@ -308,13 +306,13 @@ async fn patch_approval_triggers_elicitation() -> anyhow::Result<()> { // Verify the original `codex` tool call completes let codex_response = timeout( DEFAULT_READ_TIMEOUT, - mcp_process.read_stream_until_response_message(RequestId::Integer(codex_request_id)), + mcp_process.read_stream_until_response_message(RequestId::Number(codex_request_id)), ) .await??; assert_eq!( - JSONRPCResponse { - jsonrpc: JSONRPC_VERSION.into(), - id: RequestId::Integer(codex_request_id), + JsonRpcResponse { + jsonrpc: JsonRpcVersion2_0, + id: RequestId::Number(codex_request_id), result: json!({ "content": [ { @@ -375,11 +373,11 @@ async fn codex_tool_passes_base_instructions() -> anyhow::Result<()> { let codex_response = timeout( DEFAULT_READ_TIMEOUT, - mcp_process.read_stream_until_response_message(RequestId::Integer(codex_request_id)), + mcp_process.read_stream_until_response_message(RequestId::Number(codex_request_id)), ) .await??; - assert_eq!(codex_response.jsonrpc, JSONRPC_VERSION); - assert_eq!(codex_response.id, RequestId::Integer(codex_request_id)); + assert_eq!(codex_response.jsonrpc, JsonRpcVersion2_0); + assert_eq!(codex_response.id, RequestId::Number(codex_request_id)); assert_eq!( codex_response.result, json!({ @@ -430,42 +428,33 @@ async fn codex_tool_passes_base_instructions() -> anyhow::Result<()> { Ok(()) } -fn create_expected_patch_approval_elicitation_request( - elicitation_request_id: RequestId, +fn create_expected_patch_approval_elicitation_request_params( changes: HashMap, grant_root: Option, reason: Option, codex_mcp_tool_call_id: String, codex_event_id: String, thread_id: codex_protocol::ThreadId, -) -> anyhow::Result { +) -> anyhow::Result { let mut message_lines = Vec::new(); if let Some(r) = &reason { message_lines.push(r.clone()); } message_lines.push("Allow Codex to apply proposed code changes?".to_string()); + let params_json = serde_json::to_value(PatchApprovalElicitRequestParams { + message: message_lines.join("\n"), + requested_schema: ElicitationSchema::new(std::collections::BTreeMap::new()), + thread_id, + codex_elicitation: "patch-approval".to_string(), + codex_mcp_tool_call_id, + codex_event_id, + codex_reason: reason, + codex_grant_root: grant_root, + codex_changes: changes, + codex_call_id: "call1234".to_string(), + })?; - Ok(JSONRPCRequest { - jsonrpc: JSONRPC_VERSION.into(), - id: elicitation_request_id, - method: ElicitRequest::METHOD.to_string(), - params: Some(serde_json::to_value(&PatchApprovalElicitRequestParams { - message: message_lines.join("\n"), - requested_schema: ElicitRequestParamsRequestedSchema { - r#type: "object".to_string(), - properties: json!({}), - required: None, - }, - thread_id, - codex_elicitation: "patch-approval".to_string(), - codex_mcp_tool_call_id, - codex_event_id, - codex_reason: reason, - codex_grant_root: grant_root, - codex_changes: changes, - codex_call_id: "call1234".to_string(), - })?), - }) + Ok(params_json) } /// This handle is used to ensure that the MockServer and TempDir are not dropped while diff --git a/codex-rs/mcp-types/BUILD.bazel b/codex-rs/mcp-types/BUILD.bazel deleted file mode 100644 index 6286bda4d2..0000000000 --- a/codex-rs/mcp-types/BUILD.bazel +++ /dev/null @@ -1,6 +0,0 @@ -load("//:defs.bzl", "codex_rust_crate") - -codex_rust_crate( - name = "mcp-types", - crate_name = "mcp_types", -) diff --git a/codex-rs/mcp-types/Cargo.toml b/codex-rs/mcp-types/Cargo.toml deleted file mode 100644 index 92cf539611..0000000000 --- a/codex-rs/mcp-types/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "mcp-types" -version.workspace = true -edition.workspace = true -license.workspace = true - -[lints] -workspace = true - -[dependencies] -serde = { workspace = true, features = ["derive"] } -serde_json = { workspace = true } -ts-rs = { workspace = true, features = ["serde-json-impl", "no-serde-warnings"] } -schemars = { workspace = true } diff --git a/codex-rs/mcp-types/README.md b/codex-rs/mcp-types/README.md deleted file mode 100644 index 66ea540cc4..0000000000 --- a/codex-rs/mcp-types/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# mcp-types - -Types for Model Context Protocol. Inspired by https://crates.io/crates/lsp-types. - -As documented on https://modelcontextprotocol.io/specification/2025-06-18/basic: - -- TypeScript schema is the source of truth: https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/schema/2025-06-18/schema.ts -- JSON schema is amenable to automated tooling: https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/schema/2025-06-18/schema.json diff --git a/codex-rs/mcp-types/check_lib_rs.py b/codex-rs/mcp-types/check_lib_rs.py deleted file mode 100755 index 37b623a260..0000000000 --- a/codex-rs/mcp-types/check_lib_rs.py +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env python3 - -import subprocess -import sys -from pathlib import Path - - -def main() -> int: - crate_dir = Path(__file__).resolve().parent - generator = crate_dir / "generate_mcp_types.py" - - result = subprocess.run( - [sys.executable, str(generator), "--check"], - cwd=crate_dir, - check=False, - ) - return result.returncode - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/codex-rs/mcp-types/generate_mcp_types.py b/codex-rs/mcp-types/generate_mcp_types.py deleted file mode 100755 index 5aaac81cd7..0000000000 --- a/codex-rs/mcp-types/generate_mcp_types.py +++ /dev/null @@ -1,780 +0,0 @@ -#!/usr/bin/env python3 -# flake8: noqa: E501 - -import argparse -import json -import subprocess -import sys -import tempfile - -from dataclasses import ( - dataclass, -) -from difflib import unified_diff -from pathlib import Path -from shutil import copy2 - -# Helper first so it is defined when other functions call it. -from typing import Any, Literal - - -SCHEMA_VERSION = "2025-06-18" -JSONRPC_VERSION = "2.0" - -STANDARD_DERIVE = "#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)]\n" -STANDARD_HASHABLE_DERIVE = ( - "#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Hash, Eq, JsonSchema, TS)]\n" -) - -# Will be populated with the schema's `definitions` map in `main()` so that -# helper functions (for example `define_any_of`) can perform look-ups while -# generating code. -DEFINITIONS: dict[str, Any] = {} -# Names of the concrete *Request types that make up the ClientRequest enum. -CLIENT_REQUEST_TYPE_NAMES: list[str] = [] -# Concrete *Notification types that make up the ServerNotification enum. -SERVER_NOTIFICATION_TYPE_NAMES: list[str] = [] -# Enum types that will need a `allow(clippy::large_enum_variant)` annotation in -# order to compile without warnings. -LARGE_ENUMS = {"ServerResult"} - -# some types need setting a default value for `r#type` -# ref: [#7417](https://github.com/openai/codex/pull/7417) -default_type_values: dict[str, str] = { - "ToolInputSchema": "object", - "ToolOutputSchema": "object", -} - - -def main() -> int: - parser = argparse.ArgumentParser( - description="Embed, cluster and analyse text prompts via the OpenAI API.", - ) - - default_schema_file = ( - Path(__file__).resolve().parent / "schema" / SCHEMA_VERSION / "schema.json" - ) - default_lib_rs = Path(__file__).resolve().parent / "src/lib.rs" - parser.add_argument( - "schema_file", - nargs="?", - default=default_schema_file, - help="schema.json file to process", - ) - parser.add_argument( - "--check", - action="store_true", - help="Regenerate lib.rs in a sandbox and ensure the checked-in file matches", - ) - args = parser.parse_args() - schema_file = Path(args.schema_file) - crate_dir = Path(__file__).resolve().parent - - if args.check: - return run_check(schema_file, crate_dir, default_lib_rs) - - generate_lib_rs(schema_file, default_lib_rs, fmt=True) - return 0 - - -def generate_lib_rs(schema_file: Path, lib_rs: Path, fmt: bool) -> None: - lib_rs.parent.mkdir(parents=True, exist_ok=True) - - global DEFINITIONS # Allow helper functions to access the schema. - - with schema_file.open(encoding="utf-8") as f: - schema_json = json.load(f) - - DEFINITIONS = schema_json["definitions"] - - out = [ - f""" -// @generated -// DO NOT EDIT THIS FILE DIRECTLY. -// Run the following in the crate root to regenerate this file: -// -// ```shell -// ./generate_mcp_types.py -// ``` -use serde::Deserialize; -use serde::Serialize; -use serde::de::DeserializeOwned; -use std::convert::TryFrom; - -use schemars::JsonSchema; -use ts_rs::TS; - -pub const MCP_SCHEMA_VERSION: &str = "{SCHEMA_VERSION}"; -pub const JSONRPC_VERSION: &str = "{JSONRPC_VERSION}"; - -/// Paired request/response types for the Model Context Protocol (MCP). -pub trait ModelContextProtocolRequest {{ - const METHOD: &'static str; - type Params: DeserializeOwned + Serialize + Send + Sync + 'static; - type Result: DeserializeOwned + Serialize + Send + Sync + 'static; -}} - -/// One-way message in the Model Context Protocol (MCP). -pub trait ModelContextProtocolNotification {{ - const METHOD: &'static str; - type Params: DeserializeOwned + Serialize + Send + Sync + 'static; -}} - -fn default_jsonrpc() -> String {{ JSONRPC_VERSION.to_owned() }} - -""" - ] - definitions = schema_json["definitions"] - # Keep track of every *Request type so we can generate the TryFrom impl at - # the end. - # The concrete *Request types referenced by the ClientRequest enum will be - # captured dynamically while we are processing that definition. - for name, definition in definitions.items(): - add_definition(name, definition, out) - # No-op: list collected via define_any_of("ClientRequest"). - - # Generate TryFrom impl string and append to out before writing to file. - try_from_impl_lines: list[str] = [] - try_from_impl_lines.append("impl TryFrom for ClientRequest {\n") - try_from_impl_lines.append(" type Error = serde_json::Error;\n") - try_from_impl_lines.append( - " fn try_from(req: JSONRPCRequest) -> std::result::Result {\n" - ) - try_from_impl_lines.append(" match req.method.as_str() {\n") - - for req_name in CLIENT_REQUEST_TYPE_NAMES: - defn = definitions[req_name] - method_const = defn.get("properties", {}).get("method", {}).get("const", req_name) - payload_type = f"<{req_name} as ModelContextProtocolRequest>::Params" - try_from_impl_lines.append(f' "{method_const}" => {{\n') - try_from_impl_lines.append( - " let params_json = req.params.unwrap_or(serde_json::Value::Null);\n" - ) - try_from_impl_lines.append( - f" let params: {payload_type} = serde_json::from_value(params_json)?;\n" - ) - try_from_impl_lines.append(f" Ok(ClientRequest::{req_name}(params))\n") - try_from_impl_lines.append(" },\n") - - try_from_impl_lines.append( - ' _ => Err(serde_json::Error::io(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("Unknown method: {}", req.method)))),\n' - ) - try_from_impl_lines.append(" }\n") - try_from_impl_lines.append(" }\n") - try_from_impl_lines.append("}\n\n") - - out.extend(try_from_impl_lines) - - # Generate TryFrom for ServerNotification - notif_impl_lines: list[str] = [] - notif_impl_lines.append("impl TryFrom for ServerNotification {\n") - notif_impl_lines.append(" type Error = serde_json::Error;\n") - notif_impl_lines.append( - " fn try_from(n: JSONRPCNotification) -> std::result::Result {\n" - ) - notif_impl_lines.append(" match n.method.as_str() {\n") - - for notif_name in SERVER_NOTIFICATION_TYPE_NAMES: - n_def = definitions[notif_name] - method_const = n_def.get("properties", {}).get("method", {}).get("const", notif_name) - payload_type = f"<{notif_name} as ModelContextProtocolNotification>::Params" - notif_impl_lines.append(f' "{method_const}" => {{\n') - # params may be optional - notif_impl_lines.append( - " let params_json = n.params.unwrap_or(serde_json::Value::Null);\n" - ) - notif_impl_lines.append( - f" let params: {payload_type} = serde_json::from_value(params_json)?;\n" - ) - notif_impl_lines.append(f" Ok(ServerNotification::{notif_name}(params))\n") - notif_impl_lines.append(" },\n") - - notif_impl_lines.append( - ' _ => Err(serde_json::Error::io(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("Unknown method: {}", n.method)))),\n' - ) - notif_impl_lines.append(" }\n") - notif_impl_lines.append(" }\n") - notif_impl_lines.append("}\n") - - out.extend(notif_impl_lines) - - with open(lib_rs, "w", encoding="utf-8") as f: - for chunk in out: - f.write(chunk) - - if fmt: - subprocess.check_call( - ["cargo", "fmt", "--", "--config", "imports_granularity=Item"], - cwd=lib_rs.parent.parent, - stderr=subprocess.DEVNULL, - ) - - -def run_check(schema_file: Path, crate_dir: Path, checked_in_lib: Path) -> int: - config_path = crate_dir.parent / "rustfmt.toml" - eprint(f"Running --check with schema {schema_file}") - - with tempfile.TemporaryDirectory() as tmp_dir: - tmp_path = Path(tmp_dir) - eprint(f"Created temporary workspace at {tmp_path}") - manifest_path = tmp_path / "Cargo.toml" - eprint(f"Copying Cargo.toml into {manifest_path}") - copy2(crate_dir / "Cargo.toml", manifest_path) - manifest_text = manifest_path.read_text(encoding="utf-8") - manifest_text = manifest_text.replace( - "version = { workspace = true }", - 'version = "0.0.0"', - ) - manifest_text = manifest_text.replace("\n[lints]\nworkspace = true\n", "\n") - manifest_path.write_text(manifest_text, encoding="utf-8") - src_dir = tmp_path / "src" - src_dir.mkdir(parents=True, exist_ok=True) - eprint(f"Generating lib.rs into {src_dir}") - generated_lib = src_dir / "lib.rs" - - generate_lib_rs(schema_file, generated_lib, fmt=False) - - eprint("Formatting generated lib.rs with rustfmt") - subprocess.check_call( - [ - "rustfmt", - "--config-path", - str(config_path), - str(generated_lib), - ], - cwd=tmp_path, - stderr=subprocess.DEVNULL, - ) - - eprint("Comparing generated lib.rs with checked-in version") - checked_in_contents = checked_in_lib.read_text(encoding="utf-8") - generated_contents = generated_lib.read_text(encoding="utf-8") - - if checked_in_contents == generated_contents: - eprint("lib.rs matches checked-in version") - return 0 - - diff = unified_diff( - checked_in_contents.splitlines(keepends=True), - generated_contents.splitlines(keepends=True), - fromfile=str(checked_in_lib), - tofile=str(generated_lib), - ) - diff_text = "".join(diff) - eprint("Generated lib.rs does not match the checked-in version. Diff:") - if diff_text: - eprint(diff_text, end="") - eprint("Re-run generate_mcp_types.py without --check to update src/lib.rs.") - return 1 - - -def add_definition(name: str, definition: dict[str, Any], out: list[str]) -> None: - if name == "Result": - out.append("pub type Result = serde_json::Value;\n\n") - return - - # Capture description - description = definition.get("description") - - properties = definition.get("properties", {}) - if properties: - required_props = set(definition.get("required", [])) - out.extend(define_struct(name, properties, required_props, description)) - - # Special carve-out for Result types: - if name.endswith("Result"): - out.extend(f"impl From<{name}> for serde_json::Value {{\n") - out.append(f" fn from(value: {name}) -> Self {{\n") - out.append(" // Leave this as it should never fail\n") - out.append(" #[expect(clippy::unwrap_used)]\n") - out.append(" serde_json::to_value(value).unwrap()\n") - out.append(" }\n") - out.append("}\n\n") - return - - enum_values = definition.get("enum", []) - if enum_values: - assert definition.get("type") == "string" - define_string_enum(name, enum_values, out, description) - return - - any_of = definition.get("anyOf", []) - if any_of: - assert isinstance(any_of, list) - out.extend(define_any_of(name, any_of, description)) - return - - type_prop = definition.get("type", None) - if type_prop: - if type_prop == "string": - # Newtype pattern - out.append(STANDARD_DERIVE) - out.append(f"pub struct {name}(String);\n\n") - return - elif types := check_string_list(type_prop): - define_untagged_enum(name, types, out) - return - elif type_prop == "array": - item_name = name + "Item" - out.extend(define_any_of(item_name, definition["items"]["anyOf"])) - out.append(f"pub type {name} = Vec<{item_name}>;\n\n") - return - raise ValueError(f"Unknown type: {type_prop} in {name}") - - ref_prop = definition.get("$ref", None) - if ref_prop: - ref = type_from_ref(ref_prop) - out.extend(f"pub type {name} = {ref};\n\n") - return - - raise ValueError(f"Definition for {name} could not be processed.") - - -extra_defs = [] - - -@dataclass -class StructField: - viz: Literal["pub"] | Literal["const"] - name: str - type_name: str - serde: str | None = None - ts: str | None = None - comment: str | None = None - - def append(self, out: list[str], supports_const: bool) -> None: - if self.comment: - out.append(f" // {self.comment}\n") - if self.serde: - out.append(f" {self.serde}\n") - if self.ts: - out.append(f" {self.ts}\n") - if self.viz == "const": - if supports_const: - out.append(f" const {self.name}: {self.type_name};\n") - else: - out.append(f" pub {self.name}: String, // {self.type_name}\n") - else: - out.append(f" pub {self.name}: {self.type_name},\n") - - -def append_serde_attr(existing: str | None, fragment: str) -> str: - if existing is None: - return f"#[serde({fragment})]" - assert existing.startswith("#[serde(") and existing.endswith(")]"), existing - body = existing[len("#[serde(") : -2] - return f"#[serde({body}, {fragment})]" - - -def define_struct( - name: str, - properties: dict[str, Any], - required_props: set[str], - description: str | None, -) -> list[str]: - out: list[str] = [] - - type_default_fn: str | None = None - if name in default_type_values: - snake_name = to_snake_case(name) or name - type_default_fn = f"{snake_name}_type_default_str" - out.append(f"fn {type_default_fn}() -> String {{\n") - out.append(f' "{default_type_values[name]}".to_string()\n') - out.append("}\n\n") - - fields: list[StructField] = [] - for prop_name, prop in properties.items(): - if prop_name == "_meta": - # TODO? - continue - elif prop_name == "jsonrpc": - fields.append( - StructField( - "pub", - "jsonrpc", - "String", # cannot use `&'static str` because of Deserialize - '#[serde(rename = "jsonrpc", default = "default_jsonrpc")]', - ) - ) - continue - - prop_type = map_type(prop, prop_name, name) - is_optional = prop_name not in required_props - if is_optional: - prop_type = f"Option<{prop_type}>" - rs_prop = rust_prop_name(prop_name, is_optional) - - if prop_name == "type" and type_default_fn: - rs_prop.serde = append_serde_attr(rs_prop.serde, f'default = "{type_default_fn}"') - - if prop_type.startswith("&'static str"): - fields.append(StructField("const", rs_prop.name, prop_type, rs_prop.serde, rs_prop.ts)) - else: - fields.append(StructField("pub", rs_prop.name, prop_type, rs_prop.serde, rs_prop.ts)) - - # Special-case: add Codex-specific user_agent to Implementation - if name == "Implementation": - fields.append( - StructField( - "pub", - "user_agent", - "Option", - '#[serde(default, skip_serializing_if = "Option::is_none")]', - '#[ts(optional)]', - "This is an extra field that the Codex MCP server sends as part of InitializeResult.", - ) - ) - - if implements_request_trait(name): - add_trait_impl(name, "ModelContextProtocolRequest", fields, out) - elif implements_notification_trait(name): - add_trait_impl(name, "ModelContextProtocolNotification", fields, out) - else: - # Add doc comment if available. - emit_doc_comment(description, out) - out.append(STANDARD_DERIVE) - out.append(f"pub struct {name} {{\n") - for field in fields: - field.append(out, supports_const=False) - out.append("}\n\n") - - # Declare any extra structs after the main struct. - if extra_defs: - out.extend(extra_defs) - # Clear the extra structs for the next definition. - extra_defs.clear() - return out - - -def infer_result_type(request_type_name: str) -> str: - """Return the corresponding Result type name for a given *Request name.""" - if not request_type_name.endswith("Request"): - return "Result" # fallback - candidate = request_type_name[:-7] + "Result" - if candidate in DEFINITIONS: - return candidate - # Fallback to generic Result if specific one missing. - return "Result" - - -def implements_request_trait(name: str) -> bool: - return name.endswith("Request") and name not in ( - "Request", - "JSONRPCRequest", - "PaginatedRequest", - ) - - -def implements_notification_trait(name: str) -> bool: - return name.endswith("Notification") and name not in ( - "Notification", - "JSONRPCNotification", - ) - - -def add_trait_impl( - type_name: str, trait_name: str, fields: list[StructField], out: list[str] -) -> None: - out.append(STANDARD_DERIVE) - out.append(f"pub enum {type_name} {{}}\n\n") - - out.append(f"impl {trait_name} for {type_name} {{\n") - for field in fields: - if field.name == "method": - field.name = "METHOD" - field.append(out, supports_const=True) - elif field.name == "params": - out.append(f" type Params = {field.type_name};\n") - else: - print(f"Warning: {type_name} has unexpected field {field.name}.") - if trait_name == "ModelContextProtocolRequest": - result_type = infer_result_type(type_name) - out.append(f" type Result = {result_type};\n") - out.append("}\n\n") - - -def define_string_enum( - name: str, enum_values: Any, out: list[str], description: str | None -) -> None: - emit_doc_comment(description, out) - out.append(STANDARD_DERIVE) - out.append(f"pub enum {name} {{\n") - for value in enum_values: - assert isinstance(value, str) - out.append(f' #[serde(rename = "{value}")]\n') - out.append(f" {capitalize(value)},\n") - - out.append("}\n\n") - - -def define_untagged_enum(name: str, type_list: list[str], out: list[str]) -> None: - out.append(STANDARD_HASHABLE_DERIVE) - out.append("#[serde(untagged)]\n") - out.append(f"pub enum {name} {{\n") - for simple_type in type_list: - match simple_type: - case "string": - out.append(" String(String),\n") - case "integer": - out.append(" Integer(i64),\n") - case _: - raise ValueError(f"Unknown type in untagged enum: {simple_type} in {name}") - out.append("}\n\n") - - -def define_any_of(name: str, list_of_refs: list[Any], description: str | None = None) -> list[str]: - """Generate a Rust enum for a JSON-Schema `anyOf` union. - - For most types we simply map each `$ref` inside the `anyOf` list to a - similarly named enum variant that holds the referenced type as its - payload. For certain well-known composite types (currently only - `ClientRequest`) we need a little bit of extra intelligence: - - * The JSON shape of a request is `{ "method": , "params": }`. - * We want to deserialize directly into `ClientRequest` using Serde's - `#[serde(tag = "method", content = "params")]` representation so that - the enum payload is **only** the request's `params` object. - * Therefore each enum variant needs to carry the dedicated `…Params` type - (wrapped in `Option<…>` if the `params` field is not required), not the - full `…Request` struct from the schema definition. - """ - - # Verify each item in list_of_refs is a dict with a $ref key. - refs = [item["$ref"] for item in list_of_refs if isinstance(item, dict)] - - out: list[str] = [] - if description: - emit_doc_comment(description, out) - out.append(STANDARD_DERIVE) - - if serde := get_serde_annotation_for_anyof_type(name): - out.append(serde + "\n") - - if name in LARGE_ENUMS: - out.append("#[allow(clippy::large_enum_variant)]\n") - out.append(f"pub enum {name} {{\n") - - if name == "ClientRequest": - # Record the set of request type names so we can later generate a - # `TryFrom` implementation. - global CLIENT_REQUEST_TYPE_NAMES - CLIENT_REQUEST_TYPE_NAMES = [type_from_ref(r) for r in refs] - - if name == "ServerNotification": - global SERVER_NOTIFICATION_TYPE_NAMES - SERVER_NOTIFICATION_TYPE_NAMES = [type_from_ref(r) for r in refs] - - for ref in refs: - ref_name = type_from_ref(ref) - - # For JSONRPCMessage variants, drop the common "JSONRPC" prefix to - # make the enum easier to read (e.g. `Request` instead of - # `JSONRPCRequest`). The payload type remains unchanged. - variant_name = ( - ref_name[len("JSONRPC") :] - if name == "JSONRPCMessage" and ref_name.startswith("JSONRPC") - else ref_name - ) - - # Special-case for `ClientRequest` and `ServerNotification` so the enum - # variant's payload is the *Params type rather than the full *Request / - # *Notification marker type. - if name in ("ClientRequest", "ServerNotification"): - # Rely on the trait implementation to tell us the exact Rust type - # of the `params` payload. This guarantees we stay in sync with any - # special-case logic used elsewhere (e.g. objects with - # `additionalProperties` mapping to `serde_json::Value`). - if name == "ClientRequest": - payload_type = f"<{ref_name} as ModelContextProtocolRequest>::Params" - else: - payload_type = f"<{ref_name} as ModelContextProtocolNotification>::Params" - - # Determine the wire value for `method` so we can annotate the - # variant appropriately. If for some reason the schema does not - # specify a constant we fall back to the type name, which will at - # least compile (although deserialization will likely fail). - request_def = DEFINITIONS.get(ref_name, {}) - method_const = ( - request_def.get("properties", {}).get("method", {}).get("const", ref_name) - ) - - out.append(f' #[serde(rename = "{method_const}")]\n') - out.append(f" {variant_name}({payload_type}),\n") - else: - # The regular/straight-forward case. - out.append(f" {variant_name}({ref_name}),\n") - - out.append("}\n\n") - return out - - -def get_serde_annotation_for_anyof_type(type_name: str) -> str | None: - # TODO: Solve this in a more generic way. - match type_name: - case "ClientRequest": - return '#[serde(tag = "method", content = "params")]' - case "ServerNotification": - return '#[serde(tag = "method", content = "params")]' - case _: - return "#[serde(untagged)]" - - -def map_type( - typedef: dict[str, Any], - prop_name: str | None = None, - struct_name: str | None = None, -) -> str: - """typedef must have a `type` key, but may also have an `items`key.""" - ref_prop = typedef.get("$ref", None) - if ref_prop: - return type_from_ref(ref_prop) - - any_of = typedef.get("anyOf", None) - if any_of: - assert prop_name is not None - assert struct_name is not None - custom_type = struct_name + capitalize(prop_name) - extra_defs.extend(define_any_of(custom_type, any_of)) - return custom_type - - type_prop = typedef.get("type", None) - if type_prop is None: - # Likely `unknown` in TypeScript, like the JSONRPCError.data property. - return "serde_json::Value" - - if type_prop == "string": - if const_prop := typedef.get("const", None): - assert isinstance(const_prop, str) - return f'&\'static str = "{const_prop}"' - else: - return "String" - elif type_prop == "integer": - return "i64" - elif type_prop == "number": - return "f64" - elif type_prop == "boolean": - return "bool" - elif type_prop == "array": - item_type = typedef.get("items", None) - if item_type: - item_type = map_type(item_type, prop_name, struct_name) - assert isinstance(item_type, str) - return f"Vec<{item_type}>" - else: - raise ValueError("Array type without items.") - elif type_prop == "object": - # If the schema says `additionalProperties: {}` this is effectively an - # open-ended map, so deserialize into `serde_json::Value` for maximum - # flexibility. - if typedef.get("additionalProperties") is not None: - return "serde_json::Value" - - # If there are *no* properties declared treat it similarly. - if not typedef.get("properties"): - return "serde_json::Value" - - # Otherwise, synthesize a nested struct for the inline object. - assert prop_name is not None - assert struct_name is not None - custom_type = struct_name + capitalize(prop_name) - extra_defs.extend( - define_struct( - custom_type, - typedef["properties"], - set(typedef.get("required", [])), - typedef.get("description"), - ) - ) - return custom_type - else: - raise ValueError(f"Unknown type: {type_prop} in {typedef}") - - -@dataclass -class RustProp: - name: str - # serde annotation, if necessary - serde: str | None = None - # ts annotation, if necessary - ts: str | None = None - -def rust_prop_name(name: str, is_optional: bool) -> RustProp: - """Convert a JSON property name to a Rust property name.""" - prop_name: str - is_rename = False - if name == "type": - prop_name = "r#type" - elif name == "ref": - prop_name = "r#ref" - elif name == "enum": - prop_name = "r#enum" - elif snake_case := to_snake_case(name): - prop_name = snake_case - is_rename = True - else: - prop_name = name - - serde_annotations = [] - ts_str = None - if is_rename: - serde_annotations.append(f'rename = "{name}"') - if is_optional: - serde_annotations.append("default") - serde_annotations.append('skip_serializing_if = "Option::is_none"') - - if serde_annotations: - # Also mark optional fields for ts-rs generation. - serde_str = f"#[serde({', '.join(serde_annotations)})]" - else: - serde_str = None - - if is_optional and serde_str: - ts_str = "#[ts(optional)]" - - return RustProp(prop_name, serde_str, ts_str) - - -def to_snake_case(name: str) -> str | None: - """Convert a camelCase or PascalCase name to snake_case.""" - snake_case = name[0].lower() + "".join("_" + c.lower() if c.isupper() else c for c in name[1:]) - if snake_case != name: - return snake_case - else: - return None - - -def capitalize(name: str) -> str: - """Capitalize the first letter of a name.""" - return name[0].upper() + name[1:] - - -def check_string_list(value: Any) -> list[str] | None: - """If the value is a list of strings, return it. Otherwise, return None.""" - if not isinstance(value, list): - return None - for item in value: - if not isinstance(item, str): - return None - return value - - -def type_from_ref(ref: str) -> str: - """Convert a JSON reference to a Rust type.""" - assert ref.startswith("#/definitions/") - return ref.split("/")[-1] - - -def emit_doc_comment(text: str | None, out: list[str]) -> None: - """Append Rust doc comments derived from the JSON-schema description.""" - if not text: - return - for line in text.strip().split("\n"): - out.append(f"/// {line.rstrip()}\n") - - -def eprint(*args: Any, **kwargs: Any) -> None: - print(*args, file=sys.stderr, **kwargs) - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/codex-rs/mcp-types/schema/2025-03-26/schema.json b/codex-rs/mcp-types/schema/2025-03-26/schema.json deleted file mode 100644 index 328ff95f4b..0000000000 --- a/codex-rs/mcp-types/schema/2025-03-26/schema.json +++ /dev/null @@ -1,2138 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "Annotations": { - "description": "Optional annotations for the client. The client can use annotations to inform how objects are used or displayed", - "properties": { - "audience": { - "description": "Describes who the intended customer of this object or data is.\n\nIt can include multiple entries to indicate content useful for multiple audiences (e.g., `[\"user\", \"assistant\"]`).", - "items": { - "$ref": "#/definitions/Role" - }, - "type": "array" - }, - "priority": { - "description": "Describes how important this data is for operating the server.\n\nA value of 1 means \"most important,\" and indicates that the data is\neffectively required, while 0 means \"least important,\" and indicates that\nthe data is entirely optional.", - "maximum": 1, - "minimum": 0, - "type": "number" - } - }, - "type": "object" - }, - "AudioContent": { - "description": "Audio provided to or from an LLM.", - "properties": { - "annotations": { - "$ref": "#/definitions/Annotations", - "description": "Optional annotations for the client." - }, - "data": { - "description": "The base64-encoded audio data.", - "format": "byte", - "type": "string" - }, - "mimeType": { - "description": "The MIME type of the audio. Different providers may support different audio types.", - "type": "string" - }, - "type": { - "const": "audio", - "type": "string" - } - }, - "required": [ - "data", - "mimeType", - "type" - ], - "type": "object" - }, - "BlobResourceContents": { - "properties": { - "blob": { - "description": "A base64-encoded string representing the binary data of the item.", - "format": "byte", - "type": "string" - }, - "mimeType": { - "description": "The MIME type of this resource, if known.", - "type": "string" - }, - "uri": { - "description": "The URI of this resource.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "blob", - "uri" - ], - "type": "object" - }, - "CallToolRequest": { - "description": "Used by the client to invoke a tool provided by the server.", - "properties": { - "method": { - "const": "tools/call", - "type": "string" - }, - "params": { - "properties": { - "arguments": { - "additionalProperties": {}, - "type": "object" - }, - "name": { - "type": "string" - } - }, - "required": [ - "name" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "CallToolResult": { - "description": "The server's response to a tool call.\n\nAny errors that originate from the tool SHOULD be reported inside the result\nobject, with `isError` set to true, _not_ as an MCP protocol-level error\nresponse. Otherwise, the LLM would not be able to see that an error occurred\nand self-correct.\n\nHowever, any errors in _finding_ the tool, an error indicating that the\nserver does not support tool calls, or any other exceptional conditions,\nshould be reported as an MCP error response.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.", - "type": "object" - }, - "content": { - "items": { - "anyOf": [ - { - "$ref": "#/definitions/TextContent" - }, - { - "$ref": "#/definitions/ImageContent" - }, - { - "$ref": "#/definitions/AudioContent" - }, - { - "$ref": "#/definitions/EmbeddedResource" - } - ] - }, - "type": "array" - }, - "isError": { - "description": "Whether the tool call ended in an error.\n\nIf not set, this is assumed to be false (the call was successful).", - "type": "boolean" - } - }, - "required": [ - "content" - ], - "type": "object" - }, - "CancelledNotification": { - "description": "This notification can be sent by either side to indicate that it is cancelling a previously-issued request.\n\nThe request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.\n\nThis notification indicates that the result will be unused, so any associated processing SHOULD cease.\n\nA client MUST NOT attempt to cancel its `initialize` request.", - "properties": { - "method": { - "const": "notifications/cancelled", - "type": "string" - }, - "params": { - "properties": { - "reason": { - "description": "An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.", - "type": "string" - }, - "requestId": { - "$ref": "#/definitions/RequestId", - "description": "The ID of the request to cancel.\n\nThis MUST correspond to the ID of a request previously issued in the same direction." - } - }, - "required": [ - "requestId" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "ClientCapabilities": { - "description": "Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.", - "properties": { - "experimental": { - "additionalProperties": { - "additionalProperties": true, - "properties": {}, - "type": "object" - }, - "description": "Experimental, non-standard capabilities that the client supports.", - "type": "object" - }, - "roots": { - "description": "Present if the client supports listing roots.", - "properties": { - "listChanged": { - "description": "Whether the client supports notifications for changes to the roots list.", - "type": "boolean" - } - }, - "type": "object" - }, - "sampling": { - "additionalProperties": true, - "description": "Present if the client supports sampling from an LLM.", - "properties": {}, - "type": "object" - } - }, - "type": "object" - }, - "ClientNotification": { - "anyOf": [ - { - "$ref": "#/definitions/CancelledNotification" - }, - { - "$ref": "#/definitions/InitializedNotification" - }, - { - "$ref": "#/definitions/ProgressNotification" - }, - { - "$ref": "#/definitions/RootsListChangedNotification" - } - ] - }, - "ClientRequest": { - "anyOf": [ - { - "$ref": "#/definitions/InitializeRequest" - }, - { - "$ref": "#/definitions/PingRequest" - }, - { - "$ref": "#/definitions/ListResourcesRequest" - }, - { - "$ref": "#/definitions/ListResourceTemplatesRequest" - }, - { - "$ref": "#/definitions/ReadResourceRequest" - }, - { - "$ref": "#/definitions/SubscribeRequest" - }, - { - "$ref": "#/definitions/UnsubscribeRequest" - }, - { - "$ref": "#/definitions/ListPromptsRequest" - }, - { - "$ref": "#/definitions/GetPromptRequest" - }, - { - "$ref": "#/definitions/ListToolsRequest" - }, - { - "$ref": "#/definitions/CallToolRequest" - }, - { - "$ref": "#/definitions/SetLevelRequest" - }, - { - "$ref": "#/definitions/CompleteRequest" - } - ] - }, - "ClientResult": { - "anyOf": [ - { - "$ref": "#/definitions/Result" - }, - { - "$ref": "#/definitions/CreateMessageResult" - }, - { - "$ref": "#/definitions/ListRootsResult" - } - ] - }, - "CompleteRequest": { - "description": "A request from the client to the server, to ask for completion options.", - "properties": { - "method": { - "const": "completion/complete", - "type": "string" - }, - "params": { - "properties": { - "argument": { - "description": "The argument's information", - "properties": { - "name": { - "description": "The name of the argument", - "type": "string" - }, - "value": { - "description": "The value of the argument to use for completion matching.", - "type": "string" - } - }, - "required": [ - "name", - "value" - ], - "type": "object" - }, - "ref": { - "anyOf": [ - { - "$ref": "#/definitions/PromptReference" - }, - { - "$ref": "#/definitions/ResourceReference" - } - ] - } - }, - "required": [ - "argument", - "ref" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "CompleteResult": { - "description": "The server's response to a completion/complete request", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.", - "type": "object" - }, - "completion": { - "properties": { - "hasMore": { - "description": "Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.", - "type": "boolean" - }, - "total": { - "description": "The total number of completion options available. This can exceed the number of values actually sent in the response.", - "type": "integer" - }, - "values": { - "description": "An array of completion values. Must not exceed 100 items.", - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "values" - ], - "type": "object" - } - }, - "required": [ - "completion" - ], - "type": "object" - }, - "CreateMessageRequest": { - "description": "A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.", - "properties": { - "method": { - "const": "sampling/createMessage", - "type": "string" - }, - "params": { - "properties": { - "includeContext": { - "description": "A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. The client MAY ignore this request.", - "enum": [ - "allServers", - "none", - "thisServer" - ], - "type": "string" - }, - "maxTokens": { - "description": "The maximum number of tokens to sample, as requested by the server. The client MAY choose to sample fewer tokens than requested.", - "type": "integer" - }, - "messages": { - "items": { - "$ref": "#/definitions/SamplingMessage" - }, - "type": "array" - }, - "metadata": { - "additionalProperties": true, - "description": "Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.", - "properties": {}, - "type": "object" - }, - "modelPreferences": { - "$ref": "#/definitions/ModelPreferences", - "description": "The server's preferences for which model to select. The client MAY ignore these preferences." - }, - "stopSequences": { - "items": { - "type": "string" - }, - "type": "array" - }, - "systemPrompt": { - "description": "An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.", - "type": "string" - }, - "temperature": { - "type": "number" - } - }, - "required": [ - "maxTokens", - "messages" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "CreateMessageResult": { - "description": "The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.", - "type": "object" - }, - "content": { - "anyOf": [ - { - "$ref": "#/definitions/TextContent" - }, - { - "$ref": "#/definitions/ImageContent" - }, - { - "$ref": "#/definitions/AudioContent" - } - ] - }, - "model": { - "description": "The name of the model that generated the message.", - "type": "string" - }, - "role": { - "$ref": "#/definitions/Role" - }, - "stopReason": { - "description": "The reason why sampling stopped, if known.", - "type": "string" - } - }, - "required": [ - "content", - "model", - "role" - ], - "type": "object" - }, - "Cursor": { - "description": "An opaque token used to represent a cursor for pagination.", - "type": "string" - }, - "EmbeddedResource": { - "description": "The contents of a resource, embedded into a prompt or tool call result.\n\nIt is up to the client how best to render embedded resources for the benefit\nof the LLM and/or the user.", - "properties": { - "annotations": { - "$ref": "#/definitions/Annotations", - "description": "Optional annotations for the client." - }, - "resource": { - "anyOf": [ - { - "$ref": "#/definitions/TextResourceContents" - }, - { - "$ref": "#/definitions/BlobResourceContents" - } - ] - }, - "type": { - "const": "resource", - "type": "string" - } - }, - "required": [ - "resource", - "type" - ], - "type": "object" - }, - "EmptyResult": { - "$ref": "#/definitions/Result" - }, - "GetPromptRequest": { - "description": "Used by the client to get a prompt provided by the server.", - "properties": { - "method": { - "const": "prompts/get", - "type": "string" - }, - "params": { - "properties": { - "arguments": { - "additionalProperties": { - "type": "string" - }, - "description": "Arguments to use for templating the prompt.", - "type": "object" - }, - "name": { - "description": "The name of the prompt or prompt template.", - "type": "string" - } - }, - "required": [ - "name" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "GetPromptResult": { - "description": "The server's response to a prompts/get request from the client.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.", - "type": "object" - }, - "description": { - "description": "An optional description for the prompt.", - "type": "string" - }, - "messages": { - "items": { - "$ref": "#/definitions/PromptMessage" - }, - "type": "array" - } - }, - "required": [ - "messages" - ], - "type": "object" - }, - "ImageContent": { - "description": "An image provided to or from an LLM.", - "properties": { - "annotations": { - "$ref": "#/definitions/Annotations", - "description": "Optional annotations for the client." - }, - "data": { - "description": "The base64-encoded image data.", - "format": "byte", - "type": "string" - }, - "mimeType": { - "description": "The MIME type of the image. Different providers may support different image types.", - "type": "string" - }, - "type": { - "const": "image", - "type": "string" - } - }, - "required": [ - "data", - "mimeType", - "type" - ], - "type": "object" - }, - "Implementation": { - "description": "Describes the name and version of an MCP implementation.", - "properties": { - "name": { - "type": "string" - }, - "version": { - "type": "string" - } - }, - "required": [ - "name", - "version" - ], - "type": "object" - }, - "InitializeRequest": { - "description": "This request is sent from the client to the server when it first connects, asking it to begin initialization.", - "properties": { - "method": { - "const": "initialize", - "type": "string" - }, - "params": { - "properties": { - "capabilities": { - "$ref": "#/definitions/ClientCapabilities" - }, - "clientInfo": { - "$ref": "#/definitions/Implementation" - }, - "protocolVersion": { - "description": "The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.", - "type": "string" - } - }, - "required": [ - "capabilities", - "clientInfo", - "protocolVersion" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "InitializeResult": { - "description": "After receiving an initialize request from the client, the server sends this response.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.", - "type": "object" - }, - "capabilities": { - "$ref": "#/definitions/ServerCapabilities" - }, - "instructions": { - "description": "Instructions describing how to use the server and its features.\n\nThis can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a \"hint\" to the model. For example, this information MAY be added to the system prompt.", - "type": "string" - }, - "protocolVersion": { - "description": "The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.", - "type": "string" - }, - "serverInfo": { - "$ref": "#/definitions/Implementation" - } - }, - "required": [ - "capabilities", - "protocolVersion", - "serverInfo" - ], - "type": "object" - }, - "InitializedNotification": { - "description": "This notification is sent from the client to the server after initialization has finished.", - "properties": { - "method": { - "const": "notifications/initialized", - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "This parameter name is reserved by MCP to allow clients and servers to attach additional metadata to their notifications.", - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "JSONRPCBatchRequest": { - "description": "A JSON-RPC batch request, as described in https://www.jsonrpc.org/specification#batch.", - "items": { - "anyOf": [ - { - "$ref": "#/definitions/JSONRPCRequest" - }, - { - "$ref": "#/definitions/JSONRPCNotification" - } - ] - }, - "type": "array" - }, - "JSONRPCBatchResponse": { - "description": "A JSON-RPC batch response, as described in https://www.jsonrpc.org/specification#batch.", - "items": { - "anyOf": [ - { - "$ref": "#/definitions/JSONRPCResponse" - }, - { - "$ref": "#/definitions/JSONRPCError" - } - ] - }, - "type": "array" - }, - "JSONRPCError": { - "description": "A response to a request that indicates an error occurred.", - "properties": { - "error": { - "properties": { - "code": { - "description": "The error type that occurred.", - "type": "integer" - }, - "data": { - "description": "Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.)." - }, - "message": { - "description": "A short description of the error. The message SHOULD be limited to a concise single sentence.", - "type": "string" - } - }, - "required": [ - "code", - "message" - ], - "type": "object" - }, - "id": { - "$ref": "#/definitions/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - } - }, - "required": [ - "error", - "id", - "jsonrpc" - ], - "type": "object" - }, - "JSONRPCMessage": { - "anyOf": [ - { - "$ref": "#/definitions/JSONRPCRequest" - }, - { - "$ref": "#/definitions/JSONRPCNotification" - }, - { - "description": "A JSON-RPC batch request, as described in https://www.jsonrpc.org/specification#batch.", - "items": { - "anyOf": [ - { - "$ref": "#/definitions/JSONRPCRequest" - }, - { - "$ref": "#/definitions/JSONRPCNotification" - } - ] - }, - "type": "array" - }, - { - "$ref": "#/definitions/JSONRPCResponse" - }, - { - "$ref": "#/definitions/JSONRPCError" - }, - { - "description": "A JSON-RPC batch response, as described in https://www.jsonrpc.org/specification#batch.", - "items": { - "anyOf": [ - { - "$ref": "#/definitions/JSONRPCResponse" - }, - { - "$ref": "#/definitions/JSONRPCError" - } - ] - }, - "type": "array" - } - ], - "description": "Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent." - }, - "JSONRPCNotification": { - "description": "A notification which does not expect a response.", - "properties": { - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "This parameter name is reserved by MCP to allow clients and servers to attach additional metadata to their notifications.", - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "jsonrpc", - "method" - ], - "type": "object" - }, - "JSONRPCRequest": { - "description": "A request that expects a response.", - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "properties": { - "progressToken": { - "$ref": "#/definitions/ProgressToken", - "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." - } - }, - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "id", - "jsonrpc", - "method" - ], - "type": "object" - }, - "JSONRPCResponse": { - "description": "A successful (non-error) response to a request.", - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "result": { - "$ref": "#/definitions/Result" - } - }, - "required": [ - "id", - "jsonrpc", - "result" - ], - "type": "object" - }, - "ListPromptsRequest": { - "description": "Sent from the client to request a list of prompts and prompt templates the server has.", - "properties": { - "method": { - "const": "prompts/list", - "type": "string" - }, - "params": { - "properties": { - "cursor": { - "description": "An opaque token representing the current pagination position.\nIf provided, the server should return results starting after this cursor.", - "type": "string" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "ListPromptsResult": { - "description": "The server's response to a prompts/list request from the client.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.", - "type": "object" - }, - "nextCursor": { - "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", - "type": "string" - }, - "prompts": { - "items": { - "$ref": "#/definitions/Prompt" - }, - "type": "array" - } - }, - "required": [ - "prompts" - ], - "type": "object" - }, - "ListResourceTemplatesRequest": { - "description": "Sent from the client to request a list of resource templates the server has.", - "properties": { - "method": { - "const": "resources/templates/list", - "type": "string" - }, - "params": { - "properties": { - "cursor": { - "description": "An opaque token representing the current pagination position.\nIf provided, the server should return results starting after this cursor.", - "type": "string" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "ListResourceTemplatesResult": { - "description": "The server's response to a resources/templates/list request from the client.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.", - "type": "object" - }, - "nextCursor": { - "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", - "type": "string" - }, - "resourceTemplates": { - "items": { - "$ref": "#/definitions/ResourceTemplate" - }, - "type": "array" - } - }, - "required": [ - "resourceTemplates" - ], - "type": "object" - }, - "ListResourcesRequest": { - "description": "Sent from the client to request a list of resources the server has.", - "properties": { - "method": { - "const": "resources/list", - "type": "string" - }, - "params": { - "properties": { - "cursor": { - "description": "An opaque token representing the current pagination position.\nIf provided, the server should return results starting after this cursor.", - "type": "string" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "ListResourcesResult": { - "description": "The server's response to a resources/list request from the client.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.", - "type": "object" - }, - "nextCursor": { - "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", - "type": "string" - }, - "resources": { - "items": { - "$ref": "#/definitions/Resource" - }, - "type": "array" - } - }, - "required": [ - "resources" - ], - "type": "object" - }, - "ListRootsRequest": { - "description": "Sent from the server to request a list of root URIs from the client. Roots allow\nservers to ask for specific directories or files to operate on. A common example\nfor roots is providing a set of repositories or directories a server should operate\non.\n\nThis request is typically used when the server needs to understand the file system\nstructure or access specific locations that the client has permission to read from.", - "properties": { - "method": { - "const": "roots/list", - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "properties": { - "progressToken": { - "$ref": "#/definitions/ProgressToken", - "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." - } - }, - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "ListRootsResult": { - "description": "The client's response to a roots/list request from the server.\nThis result contains an array of Root objects, each representing a root directory\nor file that the server can operate on.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.", - "type": "object" - }, - "roots": { - "items": { - "$ref": "#/definitions/Root" - }, - "type": "array" - } - }, - "required": [ - "roots" - ], - "type": "object" - }, - "ListToolsRequest": { - "description": "Sent from the client to request a list of tools the server has.", - "properties": { - "method": { - "const": "tools/list", - "type": "string" - }, - "params": { - "properties": { - "cursor": { - "description": "An opaque token representing the current pagination position.\nIf provided, the server should return results starting after this cursor.", - "type": "string" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "ListToolsResult": { - "description": "The server's response to a tools/list request from the client.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.", - "type": "object" - }, - "nextCursor": { - "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", - "type": "string" - }, - "tools": { - "items": { - "$ref": "#/definitions/Tool" - }, - "type": "array" - } - }, - "required": [ - "tools" - ], - "type": "object" - }, - "LoggingLevel": { - "description": "The severity of a log message.\n\nThese map to syslog message severities, as specified in RFC-5424:\nhttps://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1", - "enum": [ - "alert", - "critical", - "debug", - "emergency", - "error", - "info", - "notice", - "warning" - ], - "type": "string" - }, - "LoggingMessageNotification": { - "description": "Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically.", - "properties": { - "method": { - "const": "notifications/message", - "type": "string" - }, - "params": { - "properties": { - "data": { - "description": "The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here." - }, - "level": { - "$ref": "#/definitions/LoggingLevel", - "description": "The severity of this log message." - }, - "logger": { - "description": "An optional name of the logger issuing this message.", - "type": "string" - } - }, - "required": [ - "data", - "level" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "ModelHint": { - "description": "Hints to use for model selection.\n\nKeys not declared here are currently left unspecified by the spec and are up\nto the client to interpret.", - "properties": { - "name": { - "description": "A hint for a model name.\n\nThe client SHOULD treat this as a substring of a model name; for example:\n - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022`\n - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc.\n - `claude` should match any Claude model\n\nThe client MAY also map the string to a different provider's model name or a different model info, as long as it fills a similar niche; for example:\n - `gemini-1.5-flash` could match `claude-3-haiku-20240307`", - "type": "string" - } - }, - "type": "object" - }, - "ModelPreferences": { - "description": "The server's preferences for model selection, requested of the client during sampling.\n\nBecause LLMs can vary along multiple dimensions, choosing the \"best\" model is\nrarely straightforward. Different models excel in different areas—some are\nfaster but less capable, others are more capable but more expensive, and so\non. This interface allows servers to express their priorities across multiple\ndimensions to help clients make an appropriate selection for their use case.\n\nThese preferences are always advisory. The client MAY ignore them. It is also\nup to the client to decide how to interpret these preferences and how to\nbalance them against other considerations.", - "properties": { - "costPriority": { - "description": "How much to prioritize cost when selecting a model. A value of 0 means cost\nis not important, while a value of 1 means cost is the most important\nfactor.", - "maximum": 1, - "minimum": 0, - "type": "number" - }, - "hints": { - "description": "Optional hints to use for model selection.\n\nIf multiple hints are specified, the client MUST evaluate them in order\n(such that the first match is taken).\n\nThe client SHOULD prioritize these hints over the numeric priorities, but\nMAY still use the priorities to select from ambiguous matches.", - "items": { - "$ref": "#/definitions/ModelHint" - }, - "type": "array" - }, - "intelligencePriority": { - "description": "How much to prioritize intelligence and capabilities when selecting a\nmodel. A value of 0 means intelligence is not important, while a value of 1\nmeans intelligence is the most important factor.", - "maximum": 1, - "minimum": 0, - "type": "number" - }, - "speedPriority": { - "description": "How much to prioritize sampling speed (latency) when selecting a model. A\nvalue of 0 means speed is not important, while a value of 1 means speed is\nthe most important factor.", - "maximum": 1, - "minimum": 0, - "type": "number" - } - }, - "type": "object" - }, - "Notification": { - "properties": { - "method": { - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "This parameter name is reserved by MCP to allow clients and servers to attach additional metadata to their notifications.", - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "PaginatedRequest": { - "properties": { - "method": { - "type": "string" - }, - "params": { - "properties": { - "cursor": { - "description": "An opaque token representing the current pagination position.\nIf provided, the server should return results starting after this cursor.", - "type": "string" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "PaginatedResult": { - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.", - "type": "object" - }, - "nextCursor": { - "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", - "type": "string" - } - }, - "type": "object" - }, - "PingRequest": { - "description": "A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.", - "properties": { - "method": { - "const": "ping", - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "properties": { - "progressToken": { - "$ref": "#/definitions/ProgressToken", - "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." - } - }, - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "ProgressNotification": { - "description": "An out-of-band notification used to inform the receiver of a progress update for a long-running request.", - "properties": { - "method": { - "const": "notifications/progress", - "type": "string" - }, - "params": { - "properties": { - "message": { - "description": "An optional message describing the current progress.", - "type": "string" - }, - "progress": { - "description": "The progress thus far. This should increase every time progress is made, even if the total is unknown.", - "type": "number" - }, - "progressToken": { - "$ref": "#/definitions/ProgressToken", - "description": "The progress token which was given in the initial request, used to associate this notification with the request that is proceeding." - }, - "total": { - "description": "Total number of items to process (or total progress required), if known.", - "type": "number" - } - }, - "required": [ - "progress", - "progressToken" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "ProgressToken": { - "description": "A progress token, used to associate progress notifications with the original request.", - "type": [ - "string", - "integer" - ] - }, - "Prompt": { - "description": "A prompt or prompt template that the server offers.", - "properties": { - "arguments": { - "description": "A list of arguments to use for templating the prompt.", - "items": { - "$ref": "#/definitions/PromptArgument" - }, - "type": "array" - }, - "description": { - "description": "An optional description of what this prompt provides", - "type": "string" - }, - "name": { - "description": "The name of the prompt or prompt template.", - "type": "string" - } - }, - "required": [ - "name" - ], - "type": "object" - }, - "PromptArgument": { - "description": "Describes an argument that a prompt can accept.", - "properties": { - "description": { - "description": "A human-readable description of the argument.", - "type": "string" - }, - "name": { - "description": "The name of the argument.", - "type": "string" - }, - "required": { - "description": "Whether this argument must be provided.", - "type": "boolean" - } - }, - "required": [ - "name" - ], - "type": "object" - }, - "PromptListChangedNotification": { - "description": "An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.", - "properties": { - "method": { - "const": "notifications/prompts/list_changed", - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "This parameter name is reserved by MCP to allow clients and servers to attach additional metadata to their notifications.", - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "PromptMessage": { - "description": "Describes a message returned as part of a prompt.\n\nThis is similar to `SamplingMessage`, but also supports the embedding of\nresources from the MCP server.", - "properties": { - "content": { - "anyOf": [ - { - "$ref": "#/definitions/TextContent" - }, - { - "$ref": "#/definitions/ImageContent" - }, - { - "$ref": "#/definitions/AudioContent" - }, - { - "$ref": "#/definitions/EmbeddedResource" - } - ] - }, - "role": { - "$ref": "#/definitions/Role" - } - }, - "required": [ - "content", - "role" - ], - "type": "object" - }, - "PromptReference": { - "description": "Identifies a prompt.", - "properties": { - "name": { - "description": "The name of the prompt or prompt template", - "type": "string" - }, - "type": { - "const": "ref/prompt", - "type": "string" - } - }, - "required": [ - "name", - "type" - ], - "type": "object" - }, - "ReadResourceRequest": { - "description": "Sent from the client to the server, to read a specific resource URI.", - "properties": { - "method": { - "const": "resources/read", - "type": "string" - }, - "params": { - "properties": { - "uri": { - "description": "The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "uri" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "ReadResourceResult": { - "description": "The server's response to a resources/read request from the client.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.", - "type": "object" - }, - "contents": { - "items": { - "anyOf": [ - { - "$ref": "#/definitions/TextResourceContents" - }, - { - "$ref": "#/definitions/BlobResourceContents" - } - ] - }, - "type": "array" - } - }, - "required": [ - "contents" - ], - "type": "object" - }, - "Request": { - "properties": { - "method": { - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "properties": { - "progressToken": { - "$ref": "#/definitions/ProgressToken", - "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." - } - }, - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "RequestId": { - "description": "A uniquely identifying ID for a request in JSON-RPC.", - "type": [ - "string", - "integer" - ] - }, - "Resource": { - "description": "A known resource that the server is capable of reading.", - "properties": { - "annotations": { - "$ref": "#/definitions/Annotations", - "description": "Optional annotations for the client." - }, - "description": { - "description": "A description of what this resource represents.\n\nThis can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.", - "type": "string" - }, - "mimeType": { - "description": "The MIME type of this resource, if known.", - "type": "string" - }, - "name": { - "description": "A human-readable name for this resource.\n\nThis can be used by clients to populate UI elements.", - "type": "string" - }, - "size": { - "description": "The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n\nThis can be used by Hosts to display file sizes and estimate context window usage.", - "type": "integer" - }, - "uri": { - "description": "The URI of this resource.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "name", - "uri" - ], - "type": "object" - }, - "ResourceContents": { - "description": "The contents of a specific resource or sub-resource.", - "properties": { - "mimeType": { - "description": "The MIME type of this resource, if known.", - "type": "string" - }, - "uri": { - "description": "The URI of this resource.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "uri" - ], - "type": "object" - }, - "ResourceListChangedNotification": { - "description": "An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.", - "properties": { - "method": { - "const": "notifications/resources/list_changed", - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "This parameter name is reserved by MCP to allow clients and servers to attach additional metadata to their notifications.", - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "ResourceReference": { - "description": "A reference to a resource or resource template definition.", - "properties": { - "type": { - "const": "ref/resource", - "type": "string" - }, - "uri": { - "description": "The URI or URI template of the resource.", - "format": "uri-template", - "type": "string" - } - }, - "required": [ - "type", - "uri" - ], - "type": "object" - }, - "ResourceTemplate": { - "description": "A template description for resources available on the server.", - "properties": { - "annotations": { - "$ref": "#/definitions/Annotations", - "description": "Optional annotations for the client." - }, - "description": { - "description": "A description of what this template is for.\n\nThis can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.", - "type": "string" - }, - "mimeType": { - "description": "The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.", - "type": "string" - }, - "name": { - "description": "A human-readable name for the type of resource this template refers to.\n\nThis can be used by clients to populate UI elements.", - "type": "string" - }, - "uriTemplate": { - "description": "A URI template (according to RFC 6570) that can be used to construct resource URIs.", - "format": "uri-template", - "type": "string" - } - }, - "required": [ - "name", - "uriTemplate" - ], - "type": "object" - }, - "ResourceUpdatedNotification": { - "description": "A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request.", - "properties": { - "method": { - "const": "notifications/resources/updated", - "type": "string" - }, - "params": { - "properties": { - "uri": { - "description": "The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "uri" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "Result": { - "additionalProperties": {}, - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.", - "type": "object" - } - }, - "type": "object" - }, - "Role": { - "description": "The sender or recipient of messages and data in a conversation.", - "enum": [ - "assistant", - "user" - ], - "type": "string" - }, - "Root": { - "description": "Represents a root directory or file that the server can operate on.", - "properties": { - "name": { - "description": "An optional name for the root. This can be used to provide a human-readable\nidentifier for the root, which may be useful for display purposes or for\nreferencing the root in other parts of the application.", - "type": "string" - }, - "uri": { - "description": "The URI identifying the root. This *must* start with file:// for now.\nThis restriction may be relaxed in future versions of the protocol to allow\nother URI schemes.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "uri" - ], - "type": "object" - }, - "RootsListChangedNotification": { - "description": "A notification from the client to the server, informing it that the list of roots has changed.\nThis notification should be sent whenever the client adds, removes, or modifies any root.\nThe server should then request an updated list of roots using the ListRootsRequest.", - "properties": { - "method": { - "const": "notifications/roots/list_changed", - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "This parameter name is reserved by MCP to allow clients and servers to attach additional metadata to their notifications.", - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "SamplingMessage": { - "description": "Describes a message issued to or received from an LLM API.", - "properties": { - "content": { - "anyOf": [ - { - "$ref": "#/definitions/TextContent" - }, - { - "$ref": "#/definitions/ImageContent" - }, - { - "$ref": "#/definitions/AudioContent" - } - ] - }, - "role": { - "$ref": "#/definitions/Role" - } - }, - "required": [ - "content", - "role" - ], - "type": "object" - }, - "ServerCapabilities": { - "description": "Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.", - "properties": { - "completions": { - "additionalProperties": true, - "description": "Present if the server supports argument autocompletion suggestions.", - "properties": {}, - "type": "object" - }, - "experimental": { - "additionalProperties": { - "additionalProperties": true, - "properties": {}, - "type": "object" - }, - "description": "Experimental, non-standard capabilities that the server supports.", - "type": "object" - }, - "logging": { - "additionalProperties": true, - "description": "Present if the server supports sending log messages to the client.", - "properties": {}, - "type": "object" - }, - "prompts": { - "description": "Present if the server offers any prompt templates.", - "properties": { - "listChanged": { - "description": "Whether this server supports notifications for changes to the prompt list.", - "type": "boolean" - } - }, - "type": "object" - }, - "resources": { - "description": "Present if the server offers any resources to read.", - "properties": { - "listChanged": { - "description": "Whether this server supports notifications for changes to the resource list.", - "type": "boolean" - }, - "subscribe": { - "description": "Whether this server supports subscribing to resource updates.", - "type": "boolean" - } - }, - "type": "object" - }, - "tools": { - "description": "Present if the server offers any tools to call.", - "properties": { - "listChanged": { - "description": "Whether this server supports notifications for changes to the tool list.", - "type": "boolean" - } - }, - "type": "object" - } - }, - "type": "object" - }, - "ServerNotification": { - "anyOf": [ - { - "$ref": "#/definitions/CancelledNotification" - }, - { - "$ref": "#/definitions/ProgressNotification" - }, - { - "$ref": "#/definitions/ResourceListChangedNotification" - }, - { - "$ref": "#/definitions/ResourceUpdatedNotification" - }, - { - "$ref": "#/definitions/PromptListChangedNotification" - }, - { - "$ref": "#/definitions/ToolListChangedNotification" - }, - { - "$ref": "#/definitions/LoggingMessageNotification" - } - ] - }, - "ServerRequest": { - "anyOf": [ - { - "$ref": "#/definitions/PingRequest" - }, - { - "$ref": "#/definitions/CreateMessageRequest" - }, - { - "$ref": "#/definitions/ListRootsRequest" - } - ] - }, - "ServerResult": { - "anyOf": [ - { - "$ref": "#/definitions/Result" - }, - { - "$ref": "#/definitions/InitializeResult" - }, - { - "$ref": "#/definitions/ListResourcesResult" - }, - { - "$ref": "#/definitions/ListResourceTemplatesResult" - }, - { - "$ref": "#/definitions/ReadResourceResult" - }, - { - "$ref": "#/definitions/ListPromptsResult" - }, - { - "$ref": "#/definitions/GetPromptResult" - }, - { - "$ref": "#/definitions/ListToolsResult" - }, - { - "$ref": "#/definitions/CallToolResult" - }, - { - "$ref": "#/definitions/CompleteResult" - } - ] - }, - "SetLevelRequest": { - "description": "A request from the client to the server, to enable or adjust logging.", - "properties": { - "method": { - "const": "logging/setLevel", - "type": "string" - }, - "params": { - "properties": { - "level": { - "$ref": "#/definitions/LoggingLevel", - "description": "The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/message." - } - }, - "required": [ - "level" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "SubscribeRequest": { - "description": "Sent from the client to request resources/updated notifications from the server whenever a particular resource changes.", - "properties": { - "method": { - "const": "resources/subscribe", - "type": "string" - }, - "params": { - "properties": { - "uri": { - "description": "The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "uri" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "TextContent": { - "description": "Text provided to or from an LLM.", - "properties": { - "annotations": { - "$ref": "#/definitions/Annotations", - "description": "Optional annotations for the client." - }, - "text": { - "description": "The text content of the message.", - "type": "string" - }, - "type": { - "const": "text", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "type": "object" - }, - "TextResourceContents": { - "properties": { - "mimeType": { - "description": "The MIME type of this resource, if known.", - "type": "string" - }, - "text": { - "description": "The text of the item. This must only be set if the item can actually be represented as text (not binary data).", - "type": "string" - }, - "uri": { - "description": "The URI of this resource.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "text", - "uri" - ], - "type": "object" - }, - "Tool": { - "description": "Definition for a tool the client can call.", - "properties": { - "annotations": { - "$ref": "#/definitions/ToolAnnotations", - "description": "Optional additional tool information." - }, - "description": { - "description": "A human-readable description of the tool.\n\nThis can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a \"hint\" to the model.", - "type": "string" - }, - "inputSchema": { - "description": "A JSON Schema object defining the expected parameters for the tool.", - "properties": { - "properties": { - "additionalProperties": { - "additionalProperties": true, - "properties": {}, - "type": "object" - }, - "type": "object" - }, - "required": { - "items": { - "type": "string" - }, - "type": "array" - }, - "type": { - "const": "object", - "type": "string" - } - }, - "required": [ - "type" - ], - "type": "object" - }, - "name": { - "description": "The name of the tool.", - "type": "string" - } - }, - "required": [ - "inputSchema", - "name" - ], - "type": "object" - }, - "ToolAnnotations": { - "description": "Additional properties describing a Tool to clients.\n\nNOTE: all properties in ToolAnnotations are **hints**.\nThey are not guaranteed to provide a faithful description of\ntool behavior (including descriptive properties like `title`).\n\nClients should never make tool use decisions based on ToolAnnotations\nreceived from untrusted servers.", - "properties": { - "destructiveHint": { - "description": "If true, the tool may perform destructive updates to its environment.\nIf false, the tool performs only additive updates.\n\n(This property is meaningful only when `readOnlyHint == false`)\n\nDefault: true", - "type": "boolean" - }, - "idempotentHint": { - "description": "If true, calling the tool repeatedly with the same arguments\nwill have no additional effect on the its environment.\n\n(This property is meaningful only when `readOnlyHint == false`)\n\nDefault: false", - "type": "boolean" - }, - "openWorldHint": { - "description": "If true, this tool may interact with an \"open world\" of external\nentities. If false, the tool's domain of interaction is closed.\nFor example, the world of a web search tool is open, whereas that\nof a memory tool is not.\n\nDefault: true", - "type": "boolean" - }, - "readOnlyHint": { - "description": "If true, the tool does not modify its environment.\n\nDefault: false", - "type": "boolean" - }, - "title": { - "description": "A human-readable title for the tool.", - "type": "string" - } - }, - "type": "object" - }, - "ToolListChangedNotification": { - "description": "An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.", - "properties": { - "method": { - "const": "notifications/tools/list_changed", - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "This parameter name is reserved by MCP to allow clients and servers to attach additional metadata to their notifications.", - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "UnsubscribeRequest": { - "description": "Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.", - "properties": { - "method": { - "const": "resources/unsubscribe", - "type": "string" - }, - "params": { - "properties": { - "uri": { - "description": "The URI of the resource to unsubscribe from.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "uri" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - } - } -} diff --git a/codex-rs/mcp-types/schema/2025-06-18/schema.json b/codex-rs/mcp-types/schema/2025-06-18/schema.json deleted file mode 100644 index d5faee82cd..0000000000 --- a/codex-rs/mcp-types/schema/2025-06-18/schema.json +++ /dev/null @@ -1,2516 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "Annotations": { - "description": "Optional annotations for the client. The client can use annotations to inform how objects are used or displayed", - "properties": { - "audience": { - "description": "Describes who the intended customer of this object or data is.\n\nIt can include multiple entries to indicate content useful for multiple audiences (e.g., `[\"user\", \"assistant\"]`).", - "items": { - "$ref": "#/definitions/Role" - }, - "type": "array" - }, - "lastModified": { - "description": "The moment the resource was last modified, as an ISO 8601 formatted string.\n\nShould be an ISO 8601 formatted string (e.g., \"2025-01-12T15:00:58Z\").\n\nExamples: last activity timestamp in an open file, timestamp when the resource\nwas attached, etc.", - "type": "string" - }, - "priority": { - "description": "Describes how important this data is for operating the server.\n\nA value of 1 means \"most important,\" and indicates that the data is\neffectively required, while 0 means \"least important,\" and indicates that\nthe data is entirely optional.", - "maximum": 1, - "minimum": 0, - "type": "number" - } - }, - "type": "object" - }, - "AudioContent": { - "description": "Audio provided to or from an LLM.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "annotations": { - "$ref": "#/definitions/Annotations", - "description": "Optional annotations for the client." - }, - "data": { - "description": "The base64-encoded audio data.", - "format": "byte", - "type": "string" - }, - "mimeType": { - "description": "The MIME type of the audio. Different providers may support different audio types.", - "type": "string" - }, - "type": { - "const": "audio", - "type": "string" - } - }, - "required": [ - "data", - "mimeType", - "type" - ], - "type": "object" - }, - "BaseMetadata": { - "description": "Base interface for metadata with name (identifier) and title (display name) properties.", - "properties": { - "name": { - "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", - "type": "string" - }, - "title": { - "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for Tool,\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", - "type": "string" - } - }, - "required": [ - "name" - ], - "type": "object" - }, - "BlobResourceContents": { - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "blob": { - "description": "A base64-encoded string representing the binary data of the item.", - "format": "byte", - "type": "string" - }, - "mimeType": { - "description": "The MIME type of this resource, if known.", - "type": "string" - }, - "uri": { - "description": "The URI of this resource.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "blob", - "uri" - ], - "type": "object" - }, - "BooleanSchema": { - "properties": { - "default": { - "type": "boolean" - }, - "description": { - "type": "string" - }, - "title": { - "type": "string" - }, - "type": { - "const": "boolean", - "type": "string" - } - }, - "required": [ - "type" - ], - "type": "object" - }, - "CallToolRequest": { - "description": "Used by the client to invoke a tool provided by the server.", - "properties": { - "method": { - "const": "tools/call", - "type": "string" - }, - "params": { - "properties": { - "arguments": { - "additionalProperties": {}, - "type": "object" - }, - "name": { - "type": "string" - } - }, - "required": [ - "name" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "CallToolResult": { - "description": "The server's response to a tool call.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "content": { - "description": "A list of content objects that represent the unstructured result of the tool call.", - "items": { - "$ref": "#/definitions/ContentBlock" - }, - "type": "array" - }, - "isError": { - "description": "Whether the tool call ended in an error.\n\nIf not set, this is assumed to be false (the call was successful).\n\nAny errors that originate from the tool SHOULD be reported inside the result\nobject, with `isError` set to true, _not_ as an MCP protocol-level error\nresponse. Otherwise, the LLM would not be able to see that an error occurred\nand self-correct.\n\nHowever, any errors in _finding_ the tool, an error indicating that the\nserver does not support tool calls, or any other exceptional conditions,\nshould be reported as an MCP error response.", - "type": "boolean" - }, - "structuredContent": { - "additionalProperties": {}, - "description": "An optional JSON object that represents the structured result of the tool call.", - "type": "object" - } - }, - "required": [ - "content" - ], - "type": "object" - }, - "CancelledNotification": { - "description": "This notification can be sent by either side to indicate that it is cancelling a previously-issued request.\n\nThe request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.\n\nThis notification indicates that the result will be unused, so any associated processing SHOULD cease.\n\nA client MUST NOT attempt to cancel its `initialize` request.", - "properties": { - "method": { - "const": "notifications/cancelled", - "type": "string" - }, - "params": { - "properties": { - "reason": { - "description": "An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.", - "type": "string" - }, - "requestId": { - "$ref": "#/definitions/RequestId", - "description": "The ID of the request to cancel.\n\nThis MUST correspond to the ID of a request previously issued in the same direction." - } - }, - "required": [ - "requestId" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "ClientCapabilities": { - "description": "Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.", - "properties": { - "elicitation": { - "additionalProperties": true, - "description": "Present if the client supports elicitation from the server.", - "properties": {}, - "type": "object" - }, - "experimental": { - "additionalProperties": { - "additionalProperties": true, - "properties": {}, - "type": "object" - }, - "description": "Experimental, non-standard capabilities that the client supports.", - "type": "object" - }, - "roots": { - "description": "Present if the client supports listing roots.", - "properties": { - "listChanged": { - "description": "Whether the client supports notifications for changes to the roots list.", - "type": "boolean" - } - }, - "type": "object" - }, - "sampling": { - "additionalProperties": true, - "description": "Present if the client supports sampling from an LLM.", - "properties": {}, - "type": "object" - } - }, - "type": "object" - }, - "ClientNotification": { - "anyOf": [ - { - "$ref": "#/definitions/CancelledNotification" - }, - { - "$ref": "#/definitions/InitializedNotification" - }, - { - "$ref": "#/definitions/ProgressNotification" - }, - { - "$ref": "#/definitions/RootsListChangedNotification" - } - ] - }, - "ClientRequest": { - "anyOf": [ - { - "$ref": "#/definitions/InitializeRequest" - }, - { - "$ref": "#/definitions/PingRequest" - }, - { - "$ref": "#/definitions/ListResourcesRequest" - }, - { - "$ref": "#/definitions/ListResourceTemplatesRequest" - }, - { - "$ref": "#/definitions/ReadResourceRequest" - }, - { - "$ref": "#/definitions/SubscribeRequest" - }, - { - "$ref": "#/definitions/UnsubscribeRequest" - }, - { - "$ref": "#/definitions/ListPromptsRequest" - }, - { - "$ref": "#/definitions/GetPromptRequest" - }, - { - "$ref": "#/definitions/ListToolsRequest" - }, - { - "$ref": "#/definitions/CallToolRequest" - }, - { - "$ref": "#/definitions/SetLevelRequest" - }, - { - "$ref": "#/definitions/CompleteRequest" - } - ] - }, - "ClientResult": { - "anyOf": [ - { - "$ref": "#/definitions/Result" - }, - { - "$ref": "#/definitions/CreateMessageResult" - }, - { - "$ref": "#/definitions/ListRootsResult" - }, - { - "$ref": "#/definitions/ElicitResult" - } - ] - }, - "CompleteRequest": { - "description": "A request from the client to the server, to ask for completion options.", - "properties": { - "method": { - "const": "completion/complete", - "type": "string" - }, - "params": { - "properties": { - "argument": { - "description": "The argument's information", - "properties": { - "name": { - "description": "The name of the argument", - "type": "string" - }, - "value": { - "description": "The value of the argument to use for completion matching.", - "type": "string" - } - }, - "required": [ - "name", - "value" - ], - "type": "object" - }, - "context": { - "description": "Additional, optional context for completions", - "properties": { - "arguments": { - "additionalProperties": { - "type": "string" - }, - "description": "Previously-resolved variables in a URI template or prompt.", - "type": "object" - } - }, - "type": "object" - }, - "ref": { - "anyOf": [ - { - "$ref": "#/definitions/PromptReference" - }, - { - "$ref": "#/definitions/ResourceTemplateReference" - } - ] - } - }, - "required": [ - "argument", - "ref" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "CompleteResult": { - "description": "The server's response to a completion/complete request", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "completion": { - "properties": { - "hasMore": { - "description": "Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.", - "type": "boolean" - }, - "total": { - "description": "The total number of completion options available. This can exceed the number of values actually sent in the response.", - "type": "integer" - }, - "values": { - "description": "An array of completion values. Must not exceed 100 items.", - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "values" - ], - "type": "object" - } - }, - "required": [ - "completion" - ], - "type": "object" - }, - "ContentBlock": { - "anyOf": [ - { - "$ref": "#/definitions/TextContent" - }, - { - "$ref": "#/definitions/ImageContent" - }, - { - "$ref": "#/definitions/AudioContent" - }, - { - "$ref": "#/definitions/ResourceLink" - }, - { - "$ref": "#/definitions/EmbeddedResource" - } - ] - }, - "CreateMessageRequest": { - "description": "A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.", - "properties": { - "method": { - "const": "sampling/createMessage", - "type": "string" - }, - "params": { - "properties": { - "includeContext": { - "description": "A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. The client MAY ignore this request.", - "enum": [ - "allServers", - "none", - "thisServer" - ], - "type": "string" - }, - "maxTokens": { - "description": "The maximum number of tokens to sample, as requested by the server. The client MAY choose to sample fewer tokens than requested.", - "type": "integer" - }, - "messages": { - "items": { - "$ref": "#/definitions/SamplingMessage" - }, - "type": "array" - }, - "metadata": { - "additionalProperties": true, - "description": "Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.", - "properties": {}, - "type": "object" - }, - "modelPreferences": { - "$ref": "#/definitions/ModelPreferences", - "description": "The server's preferences for which model to select. The client MAY ignore these preferences." - }, - "stopSequences": { - "items": { - "type": "string" - }, - "type": "array" - }, - "systemPrompt": { - "description": "An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.", - "type": "string" - }, - "temperature": { - "type": "number" - } - }, - "required": [ - "maxTokens", - "messages" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "CreateMessageResult": { - "description": "The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "content": { - "anyOf": [ - { - "$ref": "#/definitions/TextContent" - }, - { - "$ref": "#/definitions/ImageContent" - }, - { - "$ref": "#/definitions/AudioContent" - } - ] - }, - "model": { - "description": "The name of the model that generated the message.", - "type": "string" - }, - "role": { - "$ref": "#/definitions/Role" - }, - "stopReason": { - "description": "The reason why sampling stopped, if known.", - "type": "string" - } - }, - "required": [ - "content", - "model", - "role" - ], - "type": "object" - }, - "Cursor": { - "description": "An opaque token used to represent a cursor for pagination.", - "type": "string" - }, - "ElicitRequest": { - "description": "A request from the server to elicit additional information from the user via the client.", - "properties": { - "method": { - "const": "elicitation/create", - "type": "string" - }, - "params": { - "properties": { - "message": { - "description": "The message to present to the user.", - "type": "string" - }, - "requestedSchema": { - "description": "A restricted subset of JSON Schema.\nOnly top-level properties are allowed, without nesting.", - "properties": { - "properties": { - "additionalProperties": { - "$ref": "#/definitions/PrimitiveSchemaDefinition" - }, - "type": "object" - }, - "required": { - "items": { - "type": "string" - }, - "type": "array" - }, - "type": { - "const": "object", - "type": "string" - } - }, - "required": [ - "properties", - "type" - ], - "type": "object" - } - }, - "required": [ - "message", - "requestedSchema" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "ElicitResult": { - "description": "The client's response to an elicitation request.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "action": { - "description": "The user action in response to the elicitation.\n- \"accept\": User submitted the form/confirmed the action\n- \"decline\": User explicitly declined the action\n- \"cancel\": User dismissed without making an explicit choice", - "enum": [ - "accept", - "cancel", - "decline" - ], - "type": "string" - }, - "content": { - "additionalProperties": { - "type": [ - "string", - "integer", - "boolean" - ] - }, - "description": "The submitted form data, only present when action is \"accept\".\nContains values matching the requested schema.", - "type": "object" - } - }, - "required": [ - "action" - ], - "type": "object" - }, - "EmbeddedResource": { - "description": "The contents of a resource, embedded into a prompt or tool call result.\n\nIt is up to the client how best to render embedded resources for the benefit\nof the LLM and/or the user.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "annotations": { - "$ref": "#/definitions/Annotations", - "description": "Optional annotations for the client." - }, - "resource": { - "anyOf": [ - { - "$ref": "#/definitions/TextResourceContents" - }, - { - "$ref": "#/definitions/BlobResourceContents" - } - ] - }, - "type": { - "const": "resource", - "type": "string" - } - }, - "required": [ - "resource", - "type" - ], - "type": "object" - }, - "EmptyResult": { - "$ref": "#/definitions/Result" - }, - "EnumSchema": { - "properties": { - "description": { - "type": "string" - }, - "enum": { - "items": { - "type": "string" - }, - "type": "array" - }, - "enumNames": { - "items": { - "type": "string" - }, - "type": "array" - }, - "title": { - "type": "string" - }, - "type": { - "const": "string", - "type": "string" - } - }, - "required": [ - "enum", - "type" - ], - "type": "object" - }, - "GetPromptRequest": { - "description": "Used by the client to get a prompt provided by the server.", - "properties": { - "method": { - "const": "prompts/get", - "type": "string" - }, - "params": { - "properties": { - "arguments": { - "additionalProperties": { - "type": "string" - }, - "description": "Arguments to use for templating the prompt.", - "type": "object" - }, - "name": { - "description": "The name of the prompt or prompt template.", - "type": "string" - } - }, - "required": [ - "name" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "GetPromptResult": { - "description": "The server's response to a prompts/get request from the client.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "description": { - "description": "An optional description for the prompt.", - "type": "string" - }, - "messages": { - "items": { - "$ref": "#/definitions/PromptMessage" - }, - "type": "array" - } - }, - "required": [ - "messages" - ], - "type": "object" - }, - "ImageContent": { - "description": "An image provided to or from an LLM.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "annotations": { - "$ref": "#/definitions/Annotations", - "description": "Optional annotations for the client." - }, - "data": { - "description": "The base64-encoded image data.", - "format": "byte", - "type": "string" - }, - "mimeType": { - "description": "The MIME type of the image. Different providers may support different image types.", - "type": "string" - }, - "type": { - "const": "image", - "type": "string" - } - }, - "required": [ - "data", - "mimeType", - "type" - ], - "type": "object" - }, - "Implementation": { - "description": "Describes the name and version of an MCP implementation, with an optional title for UI representation.", - "properties": { - "name": { - "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", - "type": "string" - }, - "title": { - "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for Tool,\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", - "type": "string" - }, - "version": { - "type": "string" - } - }, - "required": [ - "name", - "version" - ], - "type": "object" - }, - "InitializeRequest": { - "description": "This request is sent from the client to the server when it first connects, asking it to begin initialization.", - "properties": { - "method": { - "const": "initialize", - "type": "string" - }, - "params": { - "properties": { - "capabilities": { - "$ref": "#/definitions/ClientCapabilities" - }, - "clientInfo": { - "$ref": "#/definitions/Implementation" - }, - "protocolVersion": { - "description": "The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.", - "type": "string" - } - }, - "required": [ - "capabilities", - "clientInfo", - "protocolVersion" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "InitializeResult": { - "description": "After receiving an initialize request from the client, the server sends this response.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "capabilities": { - "$ref": "#/definitions/ServerCapabilities" - }, - "instructions": { - "description": "Instructions describing how to use the server and its features.\n\nThis can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a \"hint\" to the model. For example, this information MAY be added to the system prompt.", - "type": "string" - }, - "protocolVersion": { - "description": "The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.", - "type": "string" - }, - "serverInfo": { - "$ref": "#/definitions/Implementation" - } - }, - "required": [ - "capabilities", - "protocolVersion", - "serverInfo" - ], - "type": "object" - }, - "InitializedNotification": { - "description": "This notification is sent from the client to the server after initialization has finished.", - "properties": { - "method": { - "const": "notifications/initialized", - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "JSONRPCError": { - "description": "A response to a request that indicates an error occurred.", - "properties": { - "error": { - "properties": { - "code": { - "description": "The error type that occurred.", - "type": "integer" - }, - "data": { - "description": "Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.)." - }, - "message": { - "description": "A short description of the error. The message SHOULD be limited to a concise single sentence.", - "type": "string" - } - }, - "required": [ - "code", - "message" - ], - "type": "object" - }, - "id": { - "$ref": "#/definitions/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - } - }, - "required": [ - "error", - "id", - "jsonrpc" - ], - "type": "object" - }, - "JSONRPCMessage": { - "anyOf": [ - { - "$ref": "#/definitions/JSONRPCRequest" - }, - { - "$ref": "#/definitions/JSONRPCNotification" - }, - { - "$ref": "#/definitions/JSONRPCResponse" - }, - { - "$ref": "#/definitions/JSONRPCError" - } - ], - "description": "Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent." - }, - "JSONRPCNotification": { - "description": "A notification which does not expect a response.", - "properties": { - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "jsonrpc", - "method" - ], - "type": "object" - }, - "JSONRPCRequest": { - "description": "A request that expects a response.", - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "properties": { - "progressToken": { - "$ref": "#/definitions/ProgressToken", - "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." - } - }, - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "id", - "jsonrpc", - "method" - ], - "type": "object" - }, - "JSONRPCResponse": { - "description": "A successful (non-error) response to a request.", - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "result": { - "$ref": "#/definitions/Result" - } - }, - "required": [ - "id", - "jsonrpc", - "result" - ], - "type": "object" - }, - "ListPromptsRequest": { - "description": "Sent from the client to request a list of prompts and prompt templates the server has.", - "properties": { - "method": { - "const": "prompts/list", - "type": "string" - }, - "params": { - "properties": { - "cursor": { - "description": "An opaque token representing the current pagination position.\nIf provided, the server should return results starting after this cursor.", - "type": "string" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "ListPromptsResult": { - "description": "The server's response to a prompts/list request from the client.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "nextCursor": { - "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", - "type": "string" - }, - "prompts": { - "items": { - "$ref": "#/definitions/Prompt" - }, - "type": "array" - } - }, - "required": [ - "prompts" - ], - "type": "object" - }, - "ListResourceTemplatesRequest": { - "description": "Sent from the client to request a list of resource templates the server has.", - "properties": { - "method": { - "const": "resources/templates/list", - "type": "string" - }, - "params": { - "properties": { - "cursor": { - "description": "An opaque token representing the current pagination position.\nIf provided, the server should return results starting after this cursor.", - "type": "string" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "ListResourceTemplatesResult": { - "description": "The server's response to a resources/templates/list request from the client.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "nextCursor": { - "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", - "type": "string" - }, - "resourceTemplates": { - "items": { - "$ref": "#/definitions/ResourceTemplate" - }, - "type": "array" - } - }, - "required": [ - "resourceTemplates" - ], - "type": "object" - }, - "ListResourcesRequest": { - "description": "Sent from the client to request a list of resources the server has.", - "properties": { - "method": { - "const": "resources/list", - "type": "string" - }, - "params": { - "properties": { - "cursor": { - "description": "An opaque token representing the current pagination position.\nIf provided, the server should return results starting after this cursor.", - "type": "string" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "ListResourcesResult": { - "description": "The server's response to a resources/list request from the client.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "nextCursor": { - "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", - "type": "string" - }, - "resources": { - "items": { - "$ref": "#/definitions/Resource" - }, - "type": "array" - } - }, - "required": [ - "resources" - ], - "type": "object" - }, - "ListRootsRequest": { - "description": "Sent from the server to request a list of root URIs from the client. Roots allow\nservers to ask for specific directories or files to operate on. A common example\nfor roots is providing a set of repositories or directories a server should operate\non.\n\nThis request is typically used when the server needs to understand the file system\nstructure or access specific locations that the client has permission to read from.", - "properties": { - "method": { - "const": "roots/list", - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "properties": { - "progressToken": { - "$ref": "#/definitions/ProgressToken", - "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." - } - }, - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "ListRootsResult": { - "description": "The client's response to a roots/list request from the server.\nThis result contains an array of Root objects, each representing a root directory\nor file that the server can operate on.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "roots": { - "items": { - "$ref": "#/definitions/Root" - }, - "type": "array" - } - }, - "required": [ - "roots" - ], - "type": "object" - }, - "ListToolsRequest": { - "description": "Sent from the client to request a list of tools the server has.", - "properties": { - "method": { - "const": "tools/list", - "type": "string" - }, - "params": { - "properties": { - "cursor": { - "description": "An opaque token representing the current pagination position.\nIf provided, the server should return results starting after this cursor.", - "type": "string" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "ListToolsResult": { - "description": "The server's response to a tools/list request from the client.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "nextCursor": { - "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", - "type": "string" - }, - "tools": { - "items": { - "$ref": "#/definitions/Tool" - }, - "type": "array" - } - }, - "required": [ - "tools" - ], - "type": "object" - }, - "LoggingLevel": { - "description": "The severity of a log message.\n\nThese map to syslog message severities, as specified in RFC-5424:\nhttps://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1", - "enum": [ - "alert", - "critical", - "debug", - "emergency", - "error", - "info", - "notice", - "warning" - ], - "type": "string" - }, - "LoggingMessageNotification": { - "description": "Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically.", - "properties": { - "method": { - "const": "notifications/message", - "type": "string" - }, - "params": { - "properties": { - "data": { - "description": "The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here." - }, - "level": { - "$ref": "#/definitions/LoggingLevel", - "description": "The severity of this log message." - }, - "logger": { - "description": "An optional name of the logger issuing this message.", - "type": "string" - } - }, - "required": [ - "data", - "level" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "ModelHint": { - "description": "Hints to use for model selection.\n\nKeys not declared here are currently left unspecified by the spec and are up\nto the client to interpret.", - "properties": { - "name": { - "description": "A hint for a model name.\n\nThe client SHOULD treat this as a substring of a model name; for example:\n - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022`\n - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc.\n - `claude` should match any Claude model\n\nThe client MAY also map the string to a different provider's model name or a different model info, as long as it fills a similar niche; for example:\n - `gemini-1.5-flash` could match `claude-3-haiku-20240307`", - "type": "string" - } - }, - "type": "object" - }, - "ModelPreferences": { - "description": "The server's preferences for model selection, requested of the client during sampling.\n\nBecause LLMs can vary along multiple dimensions, choosing the \"best\" model is\nrarely straightforward. Different models excel in different areas—some are\nfaster but less capable, others are more capable but more expensive, and so\non. This interface allows servers to express their priorities across multiple\ndimensions to help clients make an appropriate selection for their use case.\n\nThese preferences are always advisory. The client MAY ignore them. It is also\nup to the client to decide how to interpret these preferences and how to\nbalance them against other considerations.", - "properties": { - "costPriority": { - "description": "How much to prioritize cost when selecting a model. A value of 0 means cost\nis not important, while a value of 1 means cost is the most important\nfactor.", - "maximum": 1, - "minimum": 0, - "type": "number" - }, - "hints": { - "description": "Optional hints to use for model selection.\n\nIf multiple hints are specified, the client MUST evaluate them in order\n(such that the first match is taken).\n\nThe client SHOULD prioritize these hints over the numeric priorities, but\nMAY still use the priorities to select from ambiguous matches.", - "items": { - "$ref": "#/definitions/ModelHint" - }, - "type": "array" - }, - "intelligencePriority": { - "description": "How much to prioritize intelligence and capabilities when selecting a\nmodel. A value of 0 means intelligence is not important, while a value of 1\nmeans intelligence is the most important factor.", - "maximum": 1, - "minimum": 0, - "type": "number" - }, - "speedPriority": { - "description": "How much to prioritize sampling speed (latency) when selecting a model. A\nvalue of 0 means speed is not important, while a value of 1 means speed is\nthe most important factor.", - "maximum": 1, - "minimum": 0, - "type": "number" - } - }, - "type": "object" - }, - "Notification": { - "properties": { - "method": { - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "NumberSchema": { - "properties": { - "description": { - "type": "string" - }, - "maximum": { - "type": "integer" - }, - "minimum": { - "type": "integer" - }, - "title": { - "type": "string" - }, - "type": { - "enum": [ - "integer", - "number" - ], - "type": "string" - } - }, - "required": [ - "type" - ], - "type": "object" - }, - "PaginatedRequest": { - "properties": { - "method": { - "type": "string" - }, - "params": { - "properties": { - "cursor": { - "description": "An opaque token representing the current pagination position.\nIf provided, the server should return results starting after this cursor.", - "type": "string" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "PaginatedResult": { - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "nextCursor": { - "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", - "type": "string" - } - }, - "type": "object" - }, - "PingRequest": { - "description": "A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.", - "properties": { - "method": { - "const": "ping", - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "properties": { - "progressToken": { - "$ref": "#/definitions/ProgressToken", - "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." - } - }, - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "PrimitiveSchemaDefinition": { - "anyOf": [ - { - "$ref": "#/definitions/StringSchema" - }, - { - "$ref": "#/definitions/NumberSchema" - }, - { - "$ref": "#/definitions/BooleanSchema" - }, - { - "$ref": "#/definitions/EnumSchema" - } - ], - "description": "Restricted schema definitions that only allow primitive types\nwithout nested objects or arrays." - }, - "ProgressNotification": { - "description": "An out-of-band notification used to inform the receiver of a progress update for a long-running request.", - "properties": { - "method": { - "const": "notifications/progress", - "type": "string" - }, - "params": { - "properties": { - "message": { - "description": "An optional message describing the current progress.", - "type": "string" - }, - "progress": { - "description": "The progress thus far. This should increase every time progress is made, even if the total is unknown.", - "type": "number" - }, - "progressToken": { - "$ref": "#/definitions/ProgressToken", - "description": "The progress token which was given in the initial request, used to associate this notification with the request that is proceeding." - }, - "total": { - "description": "Total number of items to process (or total progress required), if known.", - "type": "number" - } - }, - "required": [ - "progress", - "progressToken" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "ProgressToken": { - "description": "A progress token, used to associate progress notifications with the original request.", - "type": [ - "string", - "integer" - ] - }, - "Prompt": { - "description": "A prompt or prompt template that the server offers.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "arguments": { - "description": "A list of arguments to use for templating the prompt.", - "items": { - "$ref": "#/definitions/PromptArgument" - }, - "type": "array" - }, - "description": { - "description": "An optional description of what this prompt provides", - "type": "string" - }, - "name": { - "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", - "type": "string" - }, - "title": { - "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for Tool,\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", - "type": "string" - } - }, - "required": [ - "name" - ], - "type": "object" - }, - "PromptArgument": { - "description": "Describes an argument that a prompt can accept.", - "properties": { - "description": { - "description": "A human-readable description of the argument.", - "type": "string" - }, - "name": { - "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", - "type": "string" - }, - "required": { - "description": "Whether this argument must be provided.", - "type": "boolean" - }, - "title": { - "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for Tool,\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", - "type": "string" - } - }, - "required": [ - "name" - ], - "type": "object" - }, - "PromptListChangedNotification": { - "description": "An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.", - "properties": { - "method": { - "const": "notifications/prompts/list_changed", - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "PromptMessage": { - "description": "Describes a message returned as part of a prompt.\n\nThis is similar to `SamplingMessage`, but also supports the embedding of\nresources from the MCP server.", - "properties": { - "content": { - "$ref": "#/definitions/ContentBlock" - }, - "role": { - "$ref": "#/definitions/Role" - } - }, - "required": [ - "content", - "role" - ], - "type": "object" - }, - "PromptReference": { - "description": "Identifies a prompt.", - "properties": { - "name": { - "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", - "type": "string" - }, - "title": { - "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for Tool,\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", - "type": "string" - }, - "type": { - "const": "ref/prompt", - "type": "string" - } - }, - "required": [ - "name", - "type" - ], - "type": "object" - }, - "ReadResourceRequest": { - "description": "Sent from the client to the server, to read a specific resource URI.", - "properties": { - "method": { - "const": "resources/read", - "type": "string" - }, - "params": { - "properties": { - "uri": { - "description": "The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "uri" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "ReadResourceResult": { - "description": "The server's response to a resources/read request from the client.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "contents": { - "items": { - "anyOf": [ - { - "$ref": "#/definitions/TextResourceContents" - }, - { - "$ref": "#/definitions/BlobResourceContents" - } - ] - }, - "type": "array" - } - }, - "required": [ - "contents" - ], - "type": "object" - }, - "Request": { - "properties": { - "method": { - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "properties": { - "progressToken": { - "$ref": "#/definitions/ProgressToken", - "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." - } - }, - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "RequestId": { - "description": "A uniquely identifying ID for a request in JSON-RPC.", - "type": [ - "string", - "integer" - ] - }, - "Resource": { - "description": "A known resource that the server is capable of reading.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "annotations": { - "$ref": "#/definitions/Annotations", - "description": "Optional annotations for the client." - }, - "description": { - "description": "A description of what this resource represents.\n\nThis can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.", - "type": "string" - }, - "mimeType": { - "description": "The MIME type of this resource, if known.", - "type": "string" - }, - "name": { - "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", - "type": "string" - }, - "size": { - "description": "The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n\nThis can be used by Hosts to display file sizes and estimate context window usage.", - "type": "integer" - }, - "title": { - "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for Tool,\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", - "type": "string" - }, - "uri": { - "description": "The URI of this resource.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "name", - "uri" - ], - "type": "object" - }, - "ResourceContents": { - "description": "The contents of a specific resource or sub-resource.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "mimeType": { - "description": "The MIME type of this resource, if known.", - "type": "string" - }, - "uri": { - "description": "The URI of this resource.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "uri" - ], - "type": "object" - }, - "ResourceLink": { - "description": "A resource that the server is capable of reading, included in a prompt or tool call result.\n\nNote: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "annotations": { - "$ref": "#/definitions/Annotations", - "description": "Optional annotations for the client." - }, - "description": { - "description": "A description of what this resource represents.\n\nThis can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.", - "type": "string" - }, - "mimeType": { - "description": "The MIME type of this resource, if known.", - "type": "string" - }, - "name": { - "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", - "type": "string" - }, - "size": { - "description": "The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n\nThis can be used by Hosts to display file sizes and estimate context window usage.", - "type": "integer" - }, - "title": { - "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for Tool,\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", - "type": "string" - }, - "type": { - "const": "resource_link", - "type": "string" - }, - "uri": { - "description": "The URI of this resource.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "name", - "type", - "uri" - ], - "type": "object" - }, - "ResourceListChangedNotification": { - "description": "An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.", - "properties": { - "method": { - "const": "notifications/resources/list_changed", - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "ResourceTemplate": { - "description": "A template description for resources available on the server.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "annotations": { - "$ref": "#/definitions/Annotations", - "description": "Optional annotations for the client." - }, - "description": { - "description": "A description of what this template is for.\n\nThis can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.", - "type": "string" - }, - "mimeType": { - "description": "The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.", - "type": "string" - }, - "name": { - "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", - "type": "string" - }, - "title": { - "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for Tool,\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", - "type": "string" - }, - "uriTemplate": { - "description": "A URI template (according to RFC 6570) that can be used to construct resource URIs.", - "format": "uri-template", - "type": "string" - } - }, - "required": [ - "name", - "uriTemplate" - ], - "type": "object" - }, - "ResourceTemplateReference": { - "description": "A reference to a resource or resource template definition.", - "properties": { - "type": { - "const": "ref/resource", - "type": "string" - }, - "uri": { - "description": "The URI or URI template of the resource.", - "format": "uri-template", - "type": "string" - } - }, - "required": [ - "type", - "uri" - ], - "type": "object" - }, - "ResourceUpdatedNotification": { - "description": "A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request.", - "properties": { - "method": { - "const": "notifications/resources/updated", - "type": "string" - }, - "params": { - "properties": { - "uri": { - "description": "The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "uri" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "Result": { - "additionalProperties": {}, - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - } - }, - "type": "object" - }, - "Role": { - "description": "The sender or recipient of messages and data in a conversation.", - "enum": [ - "assistant", - "user" - ], - "type": "string" - }, - "Root": { - "description": "Represents a root directory or file that the server can operate on.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "name": { - "description": "An optional name for the root. This can be used to provide a human-readable\nidentifier for the root, which may be useful for display purposes or for\nreferencing the root in other parts of the application.", - "type": "string" - }, - "uri": { - "description": "The URI identifying the root. This *must* start with file:// for now.\nThis restriction may be relaxed in future versions of the protocol to allow\nother URI schemes.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "uri" - ], - "type": "object" - }, - "RootsListChangedNotification": { - "description": "A notification from the client to the server, informing it that the list of roots has changed.\nThis notification should be sent whenever the client adds, removes, or modifies any root.\nThe server should then request an updated list of roots using the ListRootsRequest.", - "properties": { - "method": { - "const": "notifications/roots/list_changed", - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "SamplingMessage": { - "description": "Describes a message issued to or received from an LLM API.", - "properties": { - "content": { - "anyOf": [ - { - "$ref": "#/definitions/TextContent" - }, - { - "$ref": "#/definitions/ImageContent" - }, - { - "$ref": "#/definitions/AudioContent" - } - ] - }, - "role": { - "$ref": "#/definitions/Role" - } - }, - "required": [ - "content", - "role" - ], - "type": "object" - }, - "ServerCapabilities": { - "description": "Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.", - "properties": { - "completions": { - "additionalProperties": true, - "description": "Present if the server supports argument autocompletion suggestions.", - "properties": {}, - "type": "object" - }, - "experimental": { - "additionalProperties": { - "additionalProperties": true, - "properties": {}, - "type": "object" - }, - "description": "Experimental, non-standard capabilities that the server supports.", - "type": "object" - }, - "logging": { - "additionalProperties": true, - "description": "Present if the server supports sending log messages to the client.", - "properties": {}, - "type": "object" - }, - "prompts": { - "description": "Present if the server offers any prompt templates.", - "properties": { - "listChanged": { - "description": "Whether this server supports notifications for changes to the prompt list.", - "type": "boolean" - } - }, - "type": "object" - }, - "resources": { - "description": "Present if the server offers any resources to read.", - "properties": { - "listChanged": { - "description": "Whether this server supports notifications for changes to the resource list.", - "type": "boolean" - }, - "subscribe": { - "description": "Whether this server supports subscribing to resource updates.", - "type": "boolean" - } - }, - "type": "object" - }, - "tools": { - "description": "Present if the server offers any tools to call.", - "properties": { - "listChanged": { - "description": "Whether this server supports notifications for changes to the tool list.", - "type": "boolean" - } - }, - "type": "object" - } - }, - "type": "object" - }, - "ServerNotification": { - "anyOf": [ - { - "$ref": "#/definitions/CancelledNotification" - }, - { - "$ref": "#/definitions/ProgressNotification" - }, - { - "$ref": "#/definitions/ResourceListChangedNotification" - }, - { - "$ref": "#/definitions/ResourceUpdatedNotification" - }, - { - "$ref": "#/definitions/PromptListChangedNotification" - }, - { - "$ref": "#/definitions/ToolListChangedNotification" - }, - { - "$ref": "#/definitions/LoggingMessageNotification" - } - ] - }, - "ServerRequest": { - "anyOf": [ - { - "$ref": "#/definitions/PingRequest" - }, - { - "$ref": "#/definitions/CreateMessageRequest" - }, - { - "$ref": "#/definitions/ListRootsRequest" - }, - { - "$ref": "#/definitions/ElicitRequest" - } - ] - }, - "ServerResult": { - "anyOf": [ - { - "$ref": "#/definitions/Result" - }, - { - "$ref": "#/definitions/InitializeResult" - }, - { - "$ref": "#/definitions/ListResourcesResult" - }, - { - "$ref": "#/definitions/ListResourceTemplatesResult" - }, - { - "$ref": "#/definitions/ReadResourceResult" - }, - { - "$ref": "#/definitions/ListPromptsResult" - }, - { - "$ref": "#/definitions/GetPromptResult" - }, - { - "$ref": "#/definitions/ListToolsResult" - }, - { - "$ref": "#/definitions/CallToolResult" - }, - { - "$ref": "#/definitions/CompleteResult" - } - ] - }, - "SetLevelRequest": { - "description": "A request from the client to the server, to enable or adjust logging.", - "properties": { - "method": { - "const": "logging/setLevel", - "type": "string" - }, - "params": { - "properties": { - "level": { - "$ref": "#/definitions/LoggingLevel", - "description": "The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/message." - } - }, - "required": [ - "level" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "StringSchema": { - "properties": { - "description": { - "type": "string" - }, - "format": { - "enum": [ - "date", - "date-time", - "email", - "uri" - ], - "type": "string" - }, - "maxLength": { - "type": "integer" - }, - "minLength": { - "type": "integer" - }, - "title": { - "type": "string" - }, - "type": { - "const": "string", - "type": "string" - } - }, - "required": [ - "type" - ], - "type": "object" - }, - "SubscribeRequest": { - "description": "Sent from the client to request resources/updated notifications from the server whenever a particular resource changes.", - "properties": { - "method": { - "const": "resources/subscribe", - "type": "string" - }, - "params": { - "properties": { - "uri": { - "description": "The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "uri" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "TextContent": { - "description": "Text provided to or from an LLM.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "annotations": { - "$ref": "#/definitions/Annotations", - "description": "Optional annotations for the client." - }, - "text": { - "description": "The text content of the message.", - "type": "string" - }, - "type": { - "const": "text", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "type": "object" - }, - "TextResourceContents": { - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "mimeType": { - "description": "The MIME type of this resource, if known.", - "type": "string" - }, - "text": { - "description": "The text of the item. This must only be set if the item can actually be represented as text (not binary data).", - "type": "string" - }, - "uri": { - "description": "The URI of this resource.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "text", - "uri" - ], - "type": "object" - }, - "Tool": { - "description": "Definition for a tool the client can call.", - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - }, - "annotations": { - "$ref": "#/definitions/ToolAnnotations", - "description": "Optional additional tool information.\n\nDisplay name precedence order is: title, annotations.title, then name." - }, - "description": { - "description": "A human-readable description of the tool.\n\nThis can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a \"hint\" to the model.", - "type": "string" - }, - "inputSchema": { - "description": "A JSON Schema object defining the expected parameters for the tool.", - "properties": { - "properties": { - "additionalProperties": { - "additionalProperties": true, - "properties": {}, - "type": "object" - }, - "type": "object" - }, - "required": { - "items": { - "type": "string" - }, - "type": "array" - }, - "type": { - "const": "object", - "type": "string" - } - }, - "required": [ - "type" - ], - "type": "object" - }, - "name": { - "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", - "type": "string" - }, - "outputSchema": { - "description": "An optional JSON Schema object defining the structure of the tool's output returned in\nthe structuredContent field of a CallToolResult.", - "properties": { - "properties": { - "additionalProperties": { - "additionalProperties": true, - "properties": {}, - "type": "object" - }, - "type": "object" - }, - "required": { - "items": { - "type": "string" - }, - "type": "array" - }, - "type": { - "const": "object", - "type": "string" - } - }, - "required": [ - "type" - ], - "type": "object" - }, - "title": { - "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for Tool,\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", - "type": "string" - } - }, - "required": [ - "inputSchema", - "name" - ], - "type": "object" - }, - "ToolAnnotations": { - "description": "Additional properties describing a Tool to clients.\n\nNOTE: all properties in ToolAnnotations are **hints**.\nThey are not guaranteed to provide a faithful description of\ntool behavior (including descriptive properties like `title`).\n\nClients should never make tool use decisions based on ToolAnnotations\nreceived from untrusted servers.", - "properties": { - "destructiveHint": { - "description": "If true, the tool may perform destructive updates to its environment.\nIf false, the tool performs only additive updates.\n\n(This property is meaningful only when `readOnlyHint == false`)\n\nDefault: true", - "type": "boolean" - }, - "idempotentHint": { - "description": "If true, calling the tool repeatedly with the same arguments\nwill have no additional effect on the its environment.\n\n(This property is meaningful only when `readOnlyHint == false`)\n\nDefault: false", - "type": "boolean" - }, - "openWorldHint": { - "description": "If true, this tool may interact with an \"open world\" of external\nentities. If false, the tool's domain of interaction is closed.\nFor example, the world of a web search tool is open, whereas that\nof a memory tool is not.\n\nDefault: true", - "type": "boolean" - }, - "readOnlyHint": { - "description": "If true, the tool does not modify its environment.\n\nDefault: false", - "type": "boolean" - }, - "title": { - "description": "A human-readable title for the tool.", - "type": "string" - } - }, - "type": "object" - }, - "ToolListChangedNotification": { - "description": "An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.", - "properties": { - "method": { - "const": "notifications/tools/list_changed", - "type": "string" - }, - "params": { - "additionalProperties": {}, - "properties": { - "_meta": { - "additionalProperties": {}, - "description": "See [specification/2025-06-18/basic/index#general-fields] for notes on _meta usage.", - "type": "object" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "UnsubscribeRequest": { - "description": "Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.", - "properties": { - "method": { - "const": "resources/unsubscribe", - "type": "string" - }, - "params": { - "properties": { - "uri": { - "description": "The URI of the resource to unsubscribe from.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "uri" - ], - "type": "object" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - } - } -} diff --git a/codex-rs/mcp-types/src/lib.rs b/codex-rs/mcp-types/src/lib.rs deleted file mode 100644 index 7418bea854..0000000000 --- a/codex-rs/mcp-types/src/lib.rs +++ /dev/null @@ -1,1714 +0,0 @@ -// @generated -// DO NOT EDIT THIS FILE DIRECTLY. -// Run the following in the crate root to regenerate this file: -// -// ```shell -// ./generate_mcp_types.py -// ``` -use serde::Deserialize; -use serde::Serialize; -use serde::de::DeserializeOwned; -use std::convert::TryFrom; - -use schemars::JsonSchema; -use ts_rs::TS; - -pub const MCP_SCHEMA_VERSION: &str = "2025-06-18"; -pub const JSONRPC_VERSION: &str = "2.0"; - -/// Paired request/response types for the Model Context Protocol (MCP). -pub trait ModelContextProtocolRequest { - const METHOD: &'static str; - type Params: DeserializeOwned + Serialize + Send + Sync + 'static; - type Result: DeserializeOwned + Serialize + Send + Sync + 'static; -} - -/// One-way message in the Model Context Protocol (MCP). -pub trait ModelContextProtocolNotification { - const METHOD: &'static str; - type Params: DeserializeOwned + Serialize + Send + Sync + 'static; -} - -fn default_jsonrpc() -> String { - JSONRPC_VERSION.to_owned() -} - -/// Optional annotations for the client. The client can use annotations to inform how objects are used or displayed -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct Annotations { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub audience: Option>, - #[serde( - rename = "lastModified", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub last_modified: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub priority: Option, -} - -/// Audio provided to or from an LLM. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct AudioContent { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub annotations: Option, - pub data: String, - #[serde(rename = "mimeType")] - pub mime_type: String, - pub r#type: String, // &'static str = "audio" -} - -/// Base interface for metadata with name (identifier) and title (display name) properties. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct BaseMetadata { - pub name: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub title: Option, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct BlobResourceContents { - pub blob: String, - #[serde(rename = "mimeType", default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub mime_type: Option, - pub uri: String, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct BooleanSchema { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub default: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub description: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub title: Option, - pub r#type: String, // &'static str = "boolean" -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum CallToolRequest {} - -impl ModelContextProtocolRequest for CallToolRequest { - const METHOD: &'static str = "tools/call"; - type Params = CallToolRequestParams; - type Result = CallToolResult; -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct CallToolRequestParams { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub arguments: Option, - pub name: String, -} - -/// The server's response to a tool call. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct CallToolResult { - pub content: Vec, - #[serde(rename = "isError", default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub is_error: Option, - #[serde( - rename = "structuredContent", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub structured_content: Option, -} - -impl From for serde_json::Value { - fn from(value: CallToolResult) -> Self { - // Leave this as it should never fail - #[expect(clippy::unwrap_used)] - serde_json::to_value(value).unwrap() - } -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum CancelledNotification {} - -impl ModelContextProtocolNotification for CancelledNotification { - const METHOD: &'static str = "notifications/cancelled"; - type Params = CancelledNotificationParams; -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct CancelledNotificationParams { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub reason: Option, - #[serde(rename = "requestId")] - pub request_id: RequestId, -} - -/// Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ClientCapabilities { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub elicitation: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub experimental: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub roots: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub sampling: Option, -} - -/// Present if the client supports listing roots. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ClientCapabilitiesRoots { - #[serde( - rename = "listChanged", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub list_changed: Option, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -#[serde(untagged)] -pub enum ClientNotification { - CancelledNotification(CancelledNotification), - InitializedNotification(InitializedNotification), - ProgressNotification(ProgressNotification), - RootsListChangedNotification(RootsListChangedNotification), -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -#[serde(tag = "method", content = "params")] -pub enum ClientRequest { - #[serde(rename = "initialize")] - InitializeRequest(::Params), - #[serde(rename = "ping")] - PingRequest(::Params), - #[serde(rename = "resources/list")] - ListResourcesRequest(::Params), - #[serde(rename = "resources/templates/list")] - ListResourceTemplatesRequest( - ::Params, - ), - #[serde(rename = "resources/read")] - ReadResourceRequest(::Params), - #[serde(rename = "resources/subscribe")] - SubscribeRequest(::Params), - #[serde(rename = "resources/unsubscribe")] - UnsubscribeRequest(::Params), - #[serde(rename = "prompts/list")] - ListPromptsRequest(::Params), - #[serde(rename = "prompts/get")] - GetPromptRequest(::Params), - #[serde(rename = "tools/list")] - ListToolsRequest(::Params), - #[serde(rename = "tools/call")] - CallToolRequest(::Params), - #[serde(rename = "logging/setLevel")] - SetLevelRequest(::Params), - #[serde(rename = "completion/complete")] - CompleteRequest(::Params), -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -#[serde(untagged)] -pub enum ClientResult { - Result(Result), - CreateMessageResult(CreateMessageResult), - ListRootsResult(ListRootsResult), - ElicitResult(ElicitResult), -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum CompleteRequest {} - -impl ModelContextProtocolRequest for CompleteRequest { - const METHOD: &'static str = "completion/complete"; - type Params = CompleteRequestParams; - type Result = CompleteResult; -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct CompleteRequestParams { - pub argument: CompleteRequestParamsArgument, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub context: Option, - pub r#ref: CompleteRequestParamsRef, -} - -/// Additional, optional context for completions -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct CompleteRequestParamsContext { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub arguments: Option, -} - -/// The argument's information -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct CompleteRequestParamsArgument { - pub name: String, - pub value: String, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -#[serde(untagged)] -pub enum CompleteRequestParamsRef { - PromptReference(PromptReference), - ResourceTemplateReference(ResourceTemplateReference), -} - -/// The server's response to a completion/complete request -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct CompleteResult { - pub completion: CompleteResultCompletion, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct CompleteResultCompletion { - #[serde(rename = "hasMore", default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub has_more: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub total: Option, - pub values: Vec, -} - -impl From for serde_json::Value { - fn from(value: CompleteResult) -> Self { - // Leave this as it should never fail - #[expect(clippy::unwrap_used)] - serde_json::to_value(value).unwrap() - } -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -#[serde(untagged)] -pub enum ContentBlock { - TextContent(TextContent), - ImageContent(ImageContent), - AudioContent(AudioContent), - ResourceLink(ResourceLink), - EmbeddedResource(EmbeddedResource), -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum CreateMessageRequest {} - -impl ModelContextProtocolRequest for CreateMessageRequest { - const METHOD: &'static str = "sampling/createMessage"; - type Params = CreateMessageRequestParams; - type Result = CreateMessageResult; -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct CreateMessageRequestParams { - #[serde( - rename = "includeContext", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub include_context: Option, - #[serde(rename = "maxTokens")] - pub max_tokens: i64, - pub messages: Vec, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub metadata: Option, - #[serde( - rename = "modelPreferences", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub model_preferences: Option, - #[serde( - rename = "stopSequences", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub stop_sequences: Option>, - #[serde( - rename = "systemPrompt", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub system_prompt: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub temperature: Option, -} - -/// The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct CreateMessageResult { - pub content: CreateMessageResultContent, - pub model: String, - pub role: Role, - #[serde( - rename = "stopReason", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub stop_reason: Option, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -#[serde(untagged)] -pub enum CreateMessageResultContent { - TextContent(TextContent), - ImageContent(ImageContent), - AudioContent(AudioContent), -} - -impl From for serde_json::Value { - fn from(value: CreateMessageResult) -> Self { - // Leave this as it should never fail - #[expect(clippy::unwrap_used)] - serde_json::to_value(value).unwrap() - } -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct Cursor(String); - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum ElicitRequest {} - -impl ModelContextProtocolRequest for ElicitRequest { - const METHOD: &'static str = "elicitation/create"; - type Params = ElicitRequestParams; - type Result = ElicitResult; -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ElicitRequestParams { - pub message: String, - #[serde(rename = "requestedSchema")] - pub requested_schema: ElicitRequestParamsRequestedSchema, -} - -/// A restricted subset of JSON Schema. -/// Only top-level properties are allowed, without nesting. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ElicitRequestParamsRequestedSchema { - pub properties: serde_json::Value, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub required: Option>, - pub r#type: String, // &'static str = "object" -} - -/// The client's response to an elicitation request. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ElicitResult { - pub action: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub content: Option, -} - -impl From for serde_json::Value { - fn from(value: ElicitResult) -> Self { - // Leave this as it should never fail - #[expect(clippy::unwrap_used)] - serde_json::to_value(value).unwrap() - } -} - -/// The contents of a resource, embedded into a prompt or tool call result. -/// -/// It is up to the client how best to render embedded resources for the benefit -/// of the LLM and/or the user. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct EmbeddedResource { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub annotations: Option, - pub resource: EmbeddedResourceResource, - pub r#type: String, // &'static str = "resource" -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -#[serde(untagged)] -pub enum EmbeddedResourceResource { - TextResourceContents(TextResourceContents), - BlobResourceContents(BlobResourceContents), -} - -pub type EmptyResult = Result; - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct EnumSchema { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub description: Option, - pub r#enum: Vec, - #[serde(rename = "enumNames", default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub enum_names: Option>, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub title: Option, - pub r#type: String, // &'static str = "string" -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum GetPromptRequest {} - -impl ModelContextProtocolRequest for GetPromptRequest { - const METHOD: &'static str = "prompts/get"; - type Params = GetPromptRequestParams; - type Result = GetPromptResult; -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct GetPromptRequestParams { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub arguments: Option, - pub name: String, -} - -/// The server's response to a prompts/get request from the client. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct GetPromptResult { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub description: Option, - pub messages: Vec, -} - -impl From for serde_json::Value { - fn from(value: GetPromptResult) -> Self { - // Leave this as it should never fail - #[expect(clippy::unwrap_used)] - serde_json::to_value(value).unwrap() - } -} - -/// An image provided to or from an LLM. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ImageContent { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub annotations: Option, - pub data: String, - #[serde(rename = "mimeType")] - pub mime_type: String, - pub r#type: String, // &'static str = "image" -} - -/// Describes the name and version of an MCP implementation, with an optional title for UI representation. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct Implementation { - pub name: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub title: Option, - pub version: String, - // This is an extra field that the Codex MCP server sends as part of InitializeResult. - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub user_agent: Option, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum InitializeRequest {} - -impl ModelContextProtocolRequest for InitializeRequest { - const METHOD: &'static str = "initialize"; - type Params = InitializeRequestParams; - type Result = InitializeResult; -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct InitializeRequestParams { - pub capabilities: ClientCapabilities, - #[serde(rename = "clientInfo")] - pub client_info: Implementation, - #[serde(rename = "protocolVersion")] - pub protocol_version: String, -} - -/// After receiving an initialize request from the client, the server sends this response. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct InitializeResult { - pub capabilities: ServerCapabilities, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub instructions: Option, - #[serde(rename = "protocolVersion")] - pub protocol_version: String, - #[serde(rename = "serverInfo")] - pub server_info: Implementation, -} - -impl From for serde_json::Value { - fn from(value: InitializeResult) -> Self { - // Leave this as it should never fail - #[expect(clippy::unwrap_used)] - serde_json::to_value(value).unwrap() - } -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum InitializedNotification {} - -impl ModelContextProtocolNotification for InitializedNotification { - const METHOD: &'static str = "notifications/initialized"; - type Params = Option; -} - -/// A response to a request that indicates an error occurred. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct JSONRPCError { - pub error: JSONRPCErrorError, - pub id: RequestId, - #[serde(rename = "jsonrpc", default = "default_jsonrpc")] - pub jsonrpc: String, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct JSONRPCErrorError { - pub code: i64, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub data: Option, - pub message: String, -} - -/// Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -#[serde(untagged)] -pub enum JSONRPCMessage { - Request(JSONRPCRequest), - Notification(JSONRPCNotification), - Response(JSONRPCResponse), - Error(JSONRPCError), -} - -/// A notification which does not expect a response. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct JSONRPCNotification { - #[serde(rename = "jsonrpc", default = "default_jsonrpc")] - pub jsonrpc: String, - pub method: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub params: Option, -} - -/// A request that expects a response. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct JSONRPCRequest { - pub id: RequestId, - #[serde(rename = "jsonrpc", default = "default_jsonrpc")] - pub jsonrpc: String, - pub method: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub params: Option, -} - -/// A successful (non-error) response to a request. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct JSONRPCResponse { - pub id: RequestId, - #[serde(rename = "jsonrpc", default = "default_jsonrpc")] - pub jsonrpc: String, - pub result: Result, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum ListPromptsRequest {} - -impl ModelContextProtocolRequest for ListPromptsRequest { - const METHOD: &'static str = "prompts/list"; - type Params = Option; - type Result = ListPromptsResult; -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ListPromptsRequestParams { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub cursor: Option, -} - -/// The server's response to a prompts/list request from the client. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ListPromptsResult { - #[serde( - rename = "nextCursor", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub next_cursor: Option, - pub prompts: Vec, -} - -impl From for serde_json::Value { - fn from(value: ListPromptsResult) -> Self { - // Leave this as it should never fail - #[expect(clippy::unwrap_used)] - serde_json::to_value(value).unwrap() - } -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum ListResourceTemplatesRequest {} - -impl ModelContextProtocolRequest for ListResourceTemplatesRequest { - const METHOD: &'static str = "resources/templates/list"; - type Params = Option; - type Result = ListResourceTemplatesResult; -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ListResourceTemplatesRequestParams { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub cursor: Option, -} - -/// The server's response to a resources/templates/list request from the client. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ListResourceTemplatesResult { - #[serde( - rename = "nextCursor", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub next_cursor: Option, - #[serde(rename = "resourceTemplates")] - pub resource_templates: Vec, -} - -impl From for serde_json::Value { - fn from(value: ListResourceTemplatesResult) -> Self { - // Leave this as it should never fail - #[expect(clippy::unwrap_used)] - serde_json::to_value(value).unwrap() - } -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum ListResourcesRequest {} - -impl ModelContextProtocolRequest for ListResourcesRequest { - const METHOD: &'static str = "resources/list"; - type Params = Option; - type Result = ListResourcesResult; -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ListResourcesRequestParams { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub cursor: Option, -} - -/// The server's response to a resources/list request from the client. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ListResourcesResult { - #[serde( - rename = "nextCursor", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub next_cursor: Option, - pub resources: Vec, -} - -impl From for serde_json::Value { - fn from(value: ListResourcesResult) -> Self { - // Leave this as it should never fail - #[expect(clippy::unwrap_used)] - serde_json::to_value(value).unwrap() - } -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum ListRootsRequest {} - -impl ModelContextProtocolRequest for ListRootsRequest { - const METHOD: &'static str = "roots/list"; - type Params = Option; - type Result = ListRootsResult; -} - -/// The client's response to a roots/list request from the server. -/// This result contains an array of Root objects, each representing a root directory -/// or file that the server can operate on. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ListRootsResult { - pub roots: Vec, -} - -impl From for serde_json::Value { - fn from(value: ListRootsResult) -> Self { - // Leave this as it should never fail - #[expect(clippy::unwrap_used)] - serde_json::to_value(value).unwrap() - } -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum ListToolsRequest {} - -impl ModelContextProtocolRequest for ListToolsRequest { - const METHOD: &'static str = "tools/list"; - type Params = Option; - type Result = ListToolsResult; -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ListToolsRequestParams { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub cursor: Option, -} - -/// The server's response to a tools/list request from the client. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ListToolsResult { - #[serde( - rename = "nextCursor", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub next_cursor: Option, - pub tools: Vec, -} - -impl From for serde_json::Value { - fn from(value: ListToolsResult) -> Self { - // Leave this as it should never fail - #[expect(clippy::unwrap_used)] - serde_json::to_value(value).unwrap() - } -} - -/// The severity of a log message. -/// -/// These map to syslog message severities, as specified in RFC-5424: -/// https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1 -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum LoggingLevel { - #[serde(rename = "alert")] - Alert, - #[serde(rename = "critical")] - Critical, - #[serde(rename = "debug")] - Debug, - #[serde(rename = "emergency")] - Emergency, - #[serde(rename = "error")] - Error, - #[serde(rename = "info")] - Info, - #[serde(rename = "notice")] - Notice, - #[serde(rename = "warning")] - Warning, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum LoggingMessageNotification {} - -impl ModelContextProtocolNotification for LoggingMessageNotification { - const METHOD: &'static str = "notifications/message"; - type Params = LoggingMessageNotificationParams; -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct LoggingMessageNotificationParams { - pub data: serde_json::Value, - pub level: LoggingLevel, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub logger: Option, -} - -/// Hints to use for model selection. -/// -/// Keys not declared here are currently left unspecified by the spec and are up -/// to the client to interpret. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ModelHint { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub name: Option, -} - -/// The server's preferences for model selection, requested of the client during sampling. -/// -/// Because LLMs can vary along multiple dimensions, choosing the "best" model is -/// rarely straightforward. Different models excel in different areas—some are -/// faster but less capable, others are more capable but more expensive, and so -/// on. This interface allows servers to express their priorities across multiple -/// dimensions to help clients make an appropriate selection for their use case. -/// -/// These preferences are always advisory. The client MAY ignore them. It is also -/// up to the client to decide how to interpret these preferences and how to -/// balance them against other considerations. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ModelPreferences { - #[serde( - rename = "costPriority", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub cost_priority: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub hints: Option>, - #[serde( - rename = "intelligencePriority", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub intelligence_priority: Option, - #[serde( - rename = "speedPriority", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub speed_priority: Option, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct Notification { - pub method: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub params: Option, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct NumberSchema { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub description: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub maximum: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub minimum: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub title: Option, - pub r#type: String, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct PaginatedRequest { - pub method: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub params: Option, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct PaginatedRequestParams { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub cursor: Option, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct PaginatedResult { - #[serde( - rename = "nextCursor", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub next_cursor: Option, -} - -impl From for serde_json::Value { - fn from(value: PaginatedResult) -> Self { - // Leave this as it should never fail - #[expect(clippy::unwrap_used)] - serde_json::to_value(value).unwrap() - } -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum PingRequest {} - -impl ModelContextProtocolRequest for PingRequest { - const METHOD: &'static str = "ping"; - type Params = Option; - type Result = Result; -} - -/// Restricted schema definitions that only allow primitive types -/// without nested objects or arrays. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -#[serde(untagged)] -pub enum PrimitiveSchemaDefinition { - StringSchema(StringSchema), - NumberSchema(NumberSchema), - BooleanSchema(BooleanSchema), - EnumSchema(EnumSchema), -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum ProgressNotification {} - -impl ModelContextProtocolNotification for ProgressNotification { - const METHOD: &'static str = "notifications/progress"; - type Params = ProgressNotificationParams; -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ProgressNotificationParams { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub message: Option, - pub progress: f64, - #[serde(rename = "progressToken")] - pub progress_token: ProgressToken, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub total: Option, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Hash, Eq, JsonSchema, TS)] -#[serde(untagged)] -pub enum ProgressToken { - String(String), - Integer(i64), -} - -/// A prompt or prompt template that the server offers. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct Prompt { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub arguments: Option>, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub description: Option, - pub name: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub title: Option, -} - -/// Describes an argument that a prompt can accept. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct PromptArgument { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub description: Option, - pub name: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub required: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub title: Option, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum PromptListChangedNotification {} - -impl ModelContextProtocolNotification for PromptListChangedNotification { - const METHOD: &'static str = "notifications/prompts/list_changed"; - type Params = Option; -} - -/// Describes a message returned as part of a prompt. -/// -/// This is similar to `SamplingMessage`, but also supports the embedding of -/// resources from the MCP server. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct PromptMessage { - pub content: ContentBlock, - pub role: Role, -} - -/// Identifies a prompt. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct PromptReference { - pub name: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub title: Option, - pub r#type: String, // &'static str = "ref/prompt" -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum ReadResourceRequest {} - -impl ModelContextProtocolRequest for ReadResourceRequest { - const METHOD: &'static str = "resources/read"; - type Params = ReadResourceRequestParams; - type Result = ReadResourceResult; -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ReadResourceRequestParams { - pub uri: String, -} - -/// The server's response to a resources/read request from the client. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ReadResourceResult { - pub contents: Vec, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -#[serde(untagged)] -pub enum ReadResourceResultContents { - TextResourceContents(TextResourceContents), - BlobResourceContents(BlobResourceContents), -} - -impl From for serde_json::Value { - fn from(value: ReadResourceResult) -> Self { - // Leave this as it should never fail - #[expect(clippy::unwrap_used)] - serde_json::to_value(value).unwrap() - } -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct Request { - pub method: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub params: Option, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Hash, Eq, JsonSchema, TS)] -#[serde(untagged)] -pub enum RequestId { - String(String), - Integer(i64), -} - -/// A known resource that the server is capable of reading. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct Resource { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub annotations: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub description: Option, - #[serde(rename = "mimeType", default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub mime_type: Option, - pub name: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub size: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub title: Option, - pub uri: String, -} - -/// The contents of a specific resource or sub-resource. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ResourceContents { - #[serde(rename = "mimeType", default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub mime_type: Option, - pub uri: String, -} - -/// A resource that the server is capable of reading, included in a prompt or tool call result. -/// -/// Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ResourceLink { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub annotations: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub description: Option, - #[serde(rename = "mimeType", default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub mime_type: Option, - pub name: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub size: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub title: Option, - pub r#type: String, // &'static str = "resource_link" - pub uri: String, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum ResourceListChangedNotification {} - -impl ModelContextProtocolNotification for ResourceListChangedNotification { - const METHOD: &'static str = "notifications/resources/list_changed"; - type Params = Option; -} - -/// A template description for resources available on the server. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ResourceTemplate { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub annotations: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub description: Option, - #[serde(rename = "mimeType", default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub mime_type: Option, - pub name: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub title: Option, - #[serde(rename = "uriTemplate")] - pub uri_template: String, -} - -/// A reference to a resource or resource template definition. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ResourceTemplateReference { - pub r#type: String, // &'static str = "ref/resource" - pub uri: String, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum ResourceUpdatedNotification {} - -impl ModelContextProtocolNotification for ResourceUpdatedNotification { - const METHOD: &'static str = "notifications/resources/updated"; - type Params = ResourceUpdatedNotificationParams; -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ResourceUpdatedNotificationParams { - pub uri: String, -} - -pub type Result = serde_json::Value; - -/// The sender or recipient of messages and data in a conversation. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum Role { - #[serde(rename = "assistant")] - Assistant, - #[serde(rename = "user")] - User, -} - -/// Represents a root directory or file that the server can operate on. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct Root { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub name: Option, - pub uri: String, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum RootsListChangedNotification {} - -impl ModelContextProtocolNotification for RootsListChangedNotification { - const METHOD: &'static str = "notifications/roots/list_changed"; - type Params = Option; -} - -/// Describes a message issued to or received from an LLM API. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct SamplingMessage { - pub content: SamplingMessageContent, - pub role: Role, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -#[serde(untagged)] -pub enum SamplingMessageContent { - TextContent(TextContent), - ImageContent(ImageContent), - AudioContent(AudioContent), -} - -/// Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ServerCapabilities { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub completions: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub experimental: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub logging: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub prompts: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub resources: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub tools: Option, -} - -/// Present if the server offers any tools to call. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ServerCapabilitiesTools { - #[serde( - rename = "listChanged", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub list_changed: Option, -} - -/// Present if the server offers any resources to read. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ServerCapabilitiesResources { - #[serde( - rename = "listChanged", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub list_changed: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub subscribe: Option, -} - -/// Present if the server offers any prompt templates. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ServerCapabilitiesPrompts { - #[serde( - rename = "listChanged", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub list_changed: Option, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -#[serde(tag = "method", content = "params")] -pub enum ServerNotification { - #[serde(rename = "notifications/cancelled")] - CancelledNotification(::Params), - #[serde(rename = "notifications/progress")] - ProgressNotification(::Params), - #[serde(rename = "notifications/resources/list_changed")] - ResourceListChangedNotification( - ::Params, - ), - #[serde(rename = "notifications/resources/updated")] - ResourceUpdatedNotification( - ::Params, - ), - #[serde(rename = "notifications/prompts/list_changed")] - PromptListChangedNotification( - ::Params, - ), - #[serde(rename = "notifications/tools/list_changed")] - ToolListChangedNotification( - ::Params, - ), - #[serde(rename = "notifications/message")] - LoggingMessageNotification( - ::Params, - ), -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -#[serde(untagged)] -pub enum ServerRequest { - PingRequest(PingRequest), - CreateMessageRequest(CreateMessageRequest), - ListRootsRequest(ListRootsRequest), - ElicitRequest(ElicitRequest), -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -#[serde(untagged)] -#[allow(clippy::large_enum_variant)] -pub enum ServerResult { - Result(Result), - InitializeResult(InitializeResult), - ListResourcesResult(ListResourcesResult), - ListResourceTemplatesResult(ListResourceTemplatesResult), - ReadResourceResult(ReadResourceResult), - ListPromptsResult(ListPromptsResult), - GetPromptResult(GetPromptResult), - ListToolsResult(ListToolsResult), - CallToolResult(CallToolResult), - CompleteResult(CompleteResult), -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum SetLevelRequest {} - -impl ModelContextProtocolRequest for SetLevelRequest { - const METHOD: &'static str = "logging/setLevel"; - type Params = SetLevelRequestParams; - type Result = Result; -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct SetLevelRequestParams { - pub level: LoggingLevel, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct StringSchema { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub description: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub format: Option, - #[serde(rename = "maxLength", default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub max_length: Option, - #[serde(rename = "minLength", default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub min_length: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub title: Option, - pub r#type: String, // &'static str = "string" -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum SubscribeRequest {} - -impl ModelContextProtocolRequest for SubscribeRequest { - const METHOD: &'static str = "resources/subscribe"; - type Params = SubscribeRequestParams; - type Result = Result; -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct SubscribeRequestParams { - pub uri: String, -} - -/// Text provided to or from an LLM. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct TextContent { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub annotations: Option, - pub text: String, - pub r#type: String, // &'static str = "text" -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct TextResourceContents { - #[serde(rename = "mimeType", default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub mime_type: Option, - pub text: String, - pub uri: String, -} - -/// Definition for a tool the client can call. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct Tool { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub annotations: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub description: Option, - #[serde(rename = "inputSchema")] - pub input_schema: ToolInputSchema, - pub name: String, - #[serde( - rename = "outputSchema", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub output_schema: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub title: Option, -} - -fn tool_output_schema_type_default_str() -> String { - "object".to_string() -} - -/// An optional JSON Schema object defining the structure of the tool's output returned in -/// the structuredContent field of a CallToolResult. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ToolOutputSchema { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub properties: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub required: Option>, - #[serde(default = "tool_output_schema_type_default_str")] - pub r#type: String, // &'static str = "object" -} - -fn tool_input_schema_type_default_str() -> String { - "object".to_string() -} - -/// A JSON Schema object defining the expected parameters for the tool. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ToolInputSchema { - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub properties: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub required: Option>, - #[serde(default = "tool_input_schema_type_default_str")] - pub r#type: String, // &'static str = "object" -} - -/// Additional properties describing a Tool to clients. -/// -/// NOTE: all properties in ToolAnnotations are **hints**. -/// They are not guaranteed to provide a faithful description of -/// tool behavior (including descriptive properties like `title`). -/// -/// Clients should never make tool use decisions based on ToolAnnotations -/// received from untrusted servers. -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct ToolAnnotations { - #[serde( - rename = "destructiveHint", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub destructive_hint: Option, - #[serde( - rename = "idempotentHint", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub idempotent_hint: Option, - #[serde( - rename = "openWorldHint", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub open_world_hint: Option, - #[serde( - rename = "readOnlyHint", - default, - skip_serializing_if = "Option::is_none" - )] - #[ts(optional)] - pub read_only_hint: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub title: Option, -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum ToolListChangedNotification {} - -impl ModelContextProtocolNotification for ToolListChangedNotification { - const METHOD: &'static str = "notifications/tools/list_changed"; - type Params = Option; -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub enum UnsubscribeRequest {} - -impl ModelContextProtocolRequest for UnsubscribeRequest { - const METHOD: &'static str = "resources/unsubscribe"; - type Params = UnsubscribeRequestParams; - type Result = Result; -} - -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -pub struct UnsubscribeRequestParams { - pub uri: String, -} - -impl TryFrom for ClientRequest { - type Error = serde_json::Error; - fn try_from(req: JSONRPCRequest) -> std::result::Result { - match req.method.as_str() { - "initialize" => { - let params_json = req.params.unwrap_or(serde_json::Value::Null); - let params: ::Params = - serde_json::from_value(params_json)?; - Ok(ClientRequest::InitializeRequest(params)) - } - "ping" => { - let params_json = req.params.unwrap_or(serde_json::Value::Null); - let params: ::Params = - serde_json::from_value(params_json)?; - Ok(ClientRequest::PingRequest(params)) - } - "resources/list" => { - let params_json = req.params.unwrap_or(serde_json::Value::Null); - let params: ::Params = - serde_json::from_value(params_json)?; - Ok(ClientRequest::ListResourcesRequest(params)) - } - "resources/templates/list" => { - let params_json = req.params.unwrap_or(serde_json::Value::Null); - let params: ::Params = - serde_json::from_value(params_json)?; - Ok(ClientRequest::ListResourceTemplatesRequest(params)) - } - "resources/read" => { - let params_json = req.params.unwrap_or(serde_json::Value::Null); - let params: ::Params = - serde_json::from_value(params_json)?; - Ok(ClientRequest::ReadResourceRequest(params)) - } - "resources/subscribe" => { - let params_json = req.params.unwrap_or(serde_json::Value::Null); - let params: ::Params = - serde_json::from_value(params_json)?; - Ok(ClientRequest::SubscribeRequest(params)) - } - "resources/unsubscribe" => { - let params_json = req.params.unwrap_or(serde_json::Value::Null); - let params: ::Params = - serde_json::from_value(params_json)?; - Ok(ClientRequest::UnsubscribeRequest(params)) - } - "prompts/list" => { - let params_json = req.params.unwrap_or(serde_json::Value::Null); - let params: ::Params = - serde_json::from_value(params_json)?; - Ok(ClientRequest::ListPromptsRequest(params)) - } - "prompts/get" => { - let params_json = req.params.unwrap_or(serde_json::Value::Null); - let params: ::Params = - serde_json::from_value(params_json)?; - Ok(ClientRequest::GetPromptRequest(params)) - } - "tools/list" => { - let params_json = req.params.unwrap_or(serde_json::Value::Null); - let params: ::Params = - serde_json::from_value(params_json)?; - Ok(ClientRequest::ListToolsRequest(params)) - } - "tools/call" => { - let params_json = req.params.unwrap_or(serde_json::Value::Null); - let params: ::Params = - serde_json::from_value(params_json)?; - Ok(ClientRequest::CallToolRequest(params)) - } - "logging/setLevel" => { - let params_json = req.params.unwrap_or(serde_json::Value::Null); - let params: ::Params = - serde_json::from_value(params_json)?; - Ok(ClientRequest::SetLevelRequest(params)) - } - "completion/complete" => { - let params_json = req.params.unwrap_or(serde_json::Value::Null); - let params: ::Params = - serde_json::from_value(params_json)?; - Ok(ClientRequest::CompleteRequest(params)) - } - _ => Err(serde_json::Error::io(std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!("Unknown method: {}", req.method), - ))), - } - } -} - -impl TryFrom for ServerNotification { - type Error = serde_json::Error; - fn try_from(n: JSONRPCNotification) -> std::result::Result { - match n.method.as_str() { - "notifications/cancelled" => { - let params_json = n.params.unwrap_or(serde_json::Value::Null); - let params: ::Params = - serde_json::from_value(params_json)?; - Ok(ServerNotification::CancelledNotification(params)) - } - "notifications/progress" => { - let params_json = n.params.unwrap_or(serde_json::Value::Null); - let params: ::Params = - serde_json::from_value(params_json)?; - Ok(ServerNotification::ProgressNotification(params)) - } - "notifications/resources/list_changed" => { - let params_json = n.params.unwrap_or(serde_json::Value::Null); - let params: ::Params = serde_json::from_value(params_json)?; - Ok(ServerNotification::ResourceListChangedNotification(params)) - } - "notifications/resources/updated" => { - let params_json = n.params.unwrap_or(serde_json::Value::Null); - let params: ::Params = serde_json::from_value(params_json)?; - Ok(ServerNotification::ResourceUpdatedNotification(params)) - } - "notifications/prompts/list_changed" => { - let params_json = n.params.unwrap_or(serde_json::Value::Null); - let params: ::Params = serde_json::from_value(params_json)?; - Ok(ServerNotification::PromptListChangedNotification(params)) - } - "notifications/tools/list_changed" => { - let params_json = n.params.unwrap_or(serde_json::Value::Null); - let params: ::Params = serde_json::from_value(params_json)?; - Ok(ServerNotification::ToolListChangedNotification(params)) - } - "notifications/message" => { - let params_json = n.params.unwrap_or(serde_json::Value::Null); - let params: ::Params = serde_json::from_value(params_json)?; - Ok(ServerNotification::LoggingMessageNotification(params)) - } - _ => Err(serde_json::Error::io(std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!("Unknown method: {}", n.method), - ))), - } - } -} diff --git a/codex-rs/mcp-types/tests/all.rs b/codex-rs/mcp-types/tests/all.rs deleted file mode 100644 index 7e136e4cce..0000000000 --- a/codex-rs/mcp-types/tests/all.rs +++ /dev/null @@ -1,3 +0,0 @@ -// Single integration test binary that aggregates all test modules. -// The submodules live in `tests/suite/`. -mod suite; diff --git a/codex-rs/mcp-types/tests/suite/initialize.rs b/codex-rs/mcp-types/tests/suite/initialize.rs deleted file mode 100644 index 73ff120274..0000000000 --- a/codex-rs/mcp-types/tests/suite/initialize.rs +++ /dev/null @@ -1,70 +0,0 @@ -use mcp_types::ClientCapabilities; -use mcp_types::ClientRequest; -use mcp_types::Implementation; -use mcp_types::InitializeRequestParams; -use mcp_types::JSONRPC_VERSION; -use mcp_types::JSONRPCMessage; -use mcp_types::JSONRPCRequest; -use mcp_types::RequestId; -use serde_json::json; - -#[test] -fn deserialize_initialize_request() { - let raw = r#"{ - "jsonrpc": "2.0", - "id": 1, - "method": "initialize", - "params": { - "capabilities": {}, - "clientInfo": { "name": "acme-client", "title": "Acme", "version": "1.2.3" }, - "protocolVersion": "2025-06-18" - } - }"#; - - // Deserialize full JSONRPCMessage first. - let msg: JSONRPCMessage = - serde_json::from_str(raw).expect("failed to deserialize JSONRPCMessage"); - - // Extract the request variant. - let JSONRPCMessage::Request(json_req) = msg else { - unreachable!() - }; - - let expected_req = JSONRPCRequest { - jsonrpc: JSONRPC_VERSION.into(), - id: RequestId::Integer(1), - method: "initialize".into(), - params: Some(json!({ - "capabilities": {}, - "clientInfo": { "name": "acme-client", "title": "Acme", "version": "1.2.3" }, - "protocolVersion": "2025-06-18" - })), - }; - - assert_eq!(json_req, expected_req); - - let client_req: ClientRequest = - ClientRequest::try_from(json_req).expect("conversion must succeed"); - let ClientRequest::InitializeRequest(init_params) = client_req else { - unreachable!() - }; - - assert_eq!( - init_params, - InitializeRequestParams { - capabilities: ClientCapabilities { - experimental: None, - roots: None, - sampling: None, - elicitation: None, - }, - client_info: Implementation { - name: "acme-client".into(), - title: Some("Acme".to_string()), - version: "1.2.3".into(), - user_agent: None, - }, - protocol_version: "2025-06-18".into(), - } - ); -} diff --git a/codex-rs/mcp-types/tests/suite/mod.rs b/codex-rs/mcp-types/tests/suite/mod.rs deleted file mode 100644 index 94f4709c90..0000000000 --- a/codex-rs/mcp-types/tests/suite/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -// Aggregates all former standalone integration tests as modules. -mod initialize; -mod progress_notification; diff --git a/codex-rs/mcp-types/tests/suite/progress_notification.rs b/codex-rs/mcp-types/tests/suite/progress_notification.rs deleted file mode 100644 index 396efca2bd..0000000000 --- a/codex-rs/mcp-types/tests/suite/progress_notification.rs +++ /dev/null @@ -1,43 +0,0 @@ -use mcp_types::JSONRPCMessage; -use mcp_types::ProgressNotificationParams; -use mcp_types::ProgressToken; -use mcp_types::ServerNotification; - -#[test] -fn deserialize_progress_notification() { - let raw = r#"{ - "jsonrpc": "2.0", - "method": "notifications/progress", - "params": { - "message": "Half way there", - "progress": 0.5, - "progressToken": 99, - "total": 1.0 - } - }"#; - - // Deserialize full JSONRPCMessage first. - let msg: JSONRPCMessage = serde_json::from_str(raw).expect("invalid JSONRPCMessage"); - - // Extract the notification variant. - let JSONRPCMessage::Notification(notif) = msg else { - unreachable!() - }; - - // Convert via generated TryFrom. - let server_notif: ServerNotification = - ServerNotification::try_from(notif).expect("conversion must succeed"); - - let ServerNotification::ProgressNotification(params) = server_notif else { - unreachable!() - }; - - let expected_params = ProgressNotificationParams { - message: Some("Half way there".into()), - progress: 0.5, - progress_token: ProgressToken::Integer(99), - total: Some(1.0), - }; - - assert_eq!(params, expected_params); -} diff --git a/codex-rs/protocol/Cargo.toml b/codex-rs/protocol/Cargo.toml index c3d9d30915..b58393936b 100644 --- a/codex-rs/protocol/Cargo.toml +++ b/codex-rs/protocol/Cargo.toml @@ -19,7 +19,6 @@ codex-utils-image = { workspace = true } icu_decimal = { workspace = true } icu_locale_core = { workspace = true } icu_provider = { workspace = true, features = ["sync"] } -mcp-types = { workspace = true } mime_guess = { workspace = true } schemars = { workspace = true } serde = { workspace = true, features = ["derive"] } diff --git a/codex-rs/protocol/src/approvals.rs b/codex-rs/protocol/src/approvals.rs index 78050dfa86..635cd5223d 100644 --- a/codex-rs/protocol/src/approvals.rs +++ b/codex-rs/protocol/src/approvals.rs @@ -1,9 +1,9 @@ use std::collections::HashMap; use std::path::PathBuf; +use crate::mcp::RequestId; use crate::parse_command::ParsedCommand; use crate::protocol::FileChange; -use mcp_types::RequestId; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; @@ -62,6 +62,7 @@ pub struct ExecApprovalRequestEvent { #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] pub struct ElicitationRequestEvent { pub server_name: String, + #[ts(type = "string | number")] pub id: RequestId, pub message: String, // TODO: MCP servers can request we fill out a schema for the elicitation. We don't support diff --git a/codex-rs/protocol/src/lib.rs b/codex-rs/protocol/src/lib.rs index 60b01bbd73..5841b1187e 100644 --- a/codex-rs/protocol/src/lib.rs +++ b/codex-rs/protocol/src/lib.rs @@ -6,6 +6,7 @@ pub mod config_types; pub mod custom_prompts; pub mod dynamic_tools; pub mod items; +pub mod mcp; pub mod message_history; pub mod models; pub mod num_format; diff --git a/codex-rs/protocol/src/mcp.rs b/codex-rs/protocol/src/mcp.rs new file mode 100644 index 0000000000..2f650002b8 --- /dev/null +++ b/codex-rs/protocol/src/mcp.rs @@ -0,0 +1,115 @@ +use schemars::JsonSchema; +use serde::Deserialize; +use serde::Serialize; +use ts_rs::TS; + +/// Types used when representing Model Context Protocol (MCP) values inside the +/// Codex protocol. +/// +/// We intentionally keep these types TS/JSON-schema friendly (via `ts-rs` and +/// `schemars`) so they can be embedded in Codex's own protocol structures. + +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema, TS)] +#[serde(untagged)] +pub enum RequestId { + String(String), + #[ts(type = "number")] + Integer(i64), +} + +impl std::fmt::Display for RequestId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + RequestId::String(s) => f.write_str(s), + RequestId::Integer(i) => i.fmt(f), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +pub struct Tool { + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub title: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub description: Option, + pub input_schema: serde_json::Value, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub output_schema: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub annotations: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub icons: Option>, + #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub meta: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +pub struct Resource { + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub annotations: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub mime_type: Option, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + #[ts(type = "number")] + pub size: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub title: Option, + pub uri: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub icons: Option>, + #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub meta: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +pub struct ResourceTemplate { + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub annotations: Option, + pub uri_template: String, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub title: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub mime_type: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +pub struct CallToolResult { + pub content: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub structured_content: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub is_error: Option, + #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub meta: Option, +} diff --git a/codex-rs/protocol/src/models.rs b/codex-rs/protocol/src/models.rs index 8e67fc40fc..16cfa06e70 100644 --- a/codex-rs/protocol/src/models.rs +++ b/codex-rs/protocol/src/models.rs @@ -2,8 +2,6 @@ use std::collections::HashMap; use std::path::Path; use codex_utils_image::load_and_resize_to_fit; -use mcp_types::CallToolResult; -use mcp_types::ContentBlock; use serde::Deserialize; use serde::Deserializer; use serde::Serialize; @@ -24,6 +22,8 @@ use codex_git::GhostCommit; use codex_utils_image::error::ImageProcessingError; use schemars::JsonSchema; +use crate::mcp::CallToolResult; + /// Controls whether a command should use the session sandbox or bypass it. #[derive( Debug, Clone, Copy, Default, Eq, Hash, PartialEq, Serialize, Deserialize, JsonSchema, TS, @@ -805,6 +805,7 @@ impl From<&CallToolResult> for FunctionCallOutputPayload { content, structured_content, is_error, + meta: _, } = call_tool_result; let is_success = is_error != &Some(true); @@ -841,7 +842,7 @@ impl From<&CallToolResult> for FunctionCallOutputPayload { } }; - let content_items = convert_content_blocks_to_items(content); + let content_items = convert_mcp_content_to_items(content); FunctionCallOutputPayload { content: serialized_content, @@ -851,32 +852,44 @@ impl From<&CallToolResult> for FunctionCallOutputPayload { } } -fn convert_content_blocks_to_items( - blocks: &[ContentBlock], +fn convert_mcp_content_to_items( + contents: &[serde_json::Value], ) -> Option> { let mut saw_image = false; - let mut items = Vec::with_capacity(blocks.len()); - tracing::warn!("Blocks: {:?}", blocks); - for block in blocks { - match block { - ContentBlock::TextContent(text) => { - items.push(FunctionCallOutputContentItem::InputText { - text: text.text.clone(), - }); - } - ContentBlock::ImageContent(image) => { + let mut items = Vec::with_capacity(contents.len()); + + for content in contents { + let item = match content.get("type").and_then(serde_json::Value::as_str) { + Some("text") => FunctionCallOutputContentItem::InputText { + text: content + .get("text") + .and_then(serde_json::Value::as_str) + .unwrap_or_default() + .to_string(), + }, + Some("image") => { saw_image = true; - // Just in case the content doesn't include a data URL, add it. - let image_url = if image.data.starts_with("data:") { - image.data.clone() + let mime_type = content + .get("mimeType") + .or_else(|| content.get("mime_type")) + .and_then(serde_json::Value::as_str) + .unwrap_or("application/octet-stream"); + let data = content + .get("data") + .and_then(serde_json::Value::as_str) + .unwrap_or_default(); + let image_url = if data.starts_with("data:") { + data.to_string() } else { - format!("data:{};base64,{}", image.mime_type, image.data) + format!("data:{mime_type};base64,{data}") }; - items.push(FunctionCallOutputContentItem::InputImage { image_url }); + FunctionCallOutputContentItem::InputImage { image_url } } - // TODO: render audio, resource, and embedded resource content to the model. - _ => return None, - } + _ => FunctionCallOutputContentItem::InputText { + text: serde_json::to_string(content).unwrap_or_else(|_| "".to_string()), + }, + }; + items.push(item); } if saw_image { Some(items) } else { None } @@ -908,8 +921,6 @@ mod tests { use crate::protocol::AskForApproval; use anyhow::Result; use codex_execpolicy::Policy; - use mcp_types::ImageContent; - use mcp_types::TextContent; use pretty_assertions::assert_eq; use std::path::PathBuf; use tempfile::tempdir; @@ -1040,20 +1051,12 @@ mod tests { fn serializes_image_outputs_as_array() -> Result<()> { let call_tool_result = CallToolResult { content: vec![ - ContentBlock::TextContent(TextContent { - annotations: None, - text: "caption".into(), - r#type: "text".into(), - }), - ContentBlock::ImageContent(ImageContent { - annotations: None, - data: "BASE64".into(), - mime_type: "image/png".into(), - r#type: "image".into(), - }), + serde_json::json!({"type":"text","text":"caption"}), + serde_json::json!({"type":"image","data":"BASE64","mimeType":"image/png"}), ], - is_error: None, structured_content: None, + is_error: Some(false), + meta: None, }; let payload = FunctionCallOutputPayload::from(&call_tool_result); diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 6a6939620f..71a7973c6d 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -23,6 +23,11 @@ use crate::dynamic_tools::DynamicToolCallRequest; use crate::dynamic_tools::DynamicToolResponse; use crate::dynamic_tools::DynamicToolSpec; use crate::items::TurnItem; +use crate::mcp::CallToolResult; +use crate::mcp::RequestId; +use crate::mcp::Resource as McpResource; +use crate::mcp::ResourceTemplate as McpResourceTemplate; +use crate::mcp::Tool as McpTool; use crate::message_history::HistoryEntry; use crate::models::BaseInstructions; use crate::models::ContentItem; @@ -35,11 +40,6 @@ use crate::plan_tool::UpdatePlanArgs; use crate::request_user_input::RequestUserInputResponse; use crate::user_input::UserInput; use codex_utils_absolute_path::AbsolutePathBuf; -use mcp_types::CallToolResult; -use mcp_types::RequestId; -use mcp_types::Resource as McpResource; -use mcp_types::ResourceTemplate as McpResourceTemplate; -use mcp_types::Tool as McpTool; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; diff --git a/codex-rs/rmcp-client/Cargo.toml b/codex-rs/rmcp-client/Cargo.toml index 4b2d6964f4..2b8752fcea 100644 --- a/codex-rs/rmcp-client/Cargo.toml +++ b/codex-rs/rmcp-client/Cargo.toml @@ -18,7 +18,6 @@ codex-protocol = { workspace = true } codex-utils-home-dir = { workspace = true } futures = { workspace = true, default-features = false, features = ["std"] } keyring = { workspace = true, features = ["crypto-rust"] } -mcp-types = { path = "../mcp-types" } oauth2 = "5" reqwest = { version = "0.12", default-features = false, features = [ "json", diff --git a/codex-rs/rmcp-client/src/logging_client_handler.rs b/codex-rs/rmcp-client/src/logging_client_handler.rs index 0d2c3aaa97..8db730df06 100644 --- a/codex-rs/rmcp-client/src/logging_client_handler.rs +++ b/codex-rs/rmcp-client/src/logging_client_handler.rs @@ -9,7 +9,6 @@ use rmcp::model::CreateElicitationResult; use rmcp::model::LoggingLevel; use rmcp::model::LoggingMessageNotificationParam; use rmcp::model::ProgressNotificationParam; -use rmcp::model::RequestId; use rmcp::model::ResourceUpdatedNotificationParam; use rmcp::service::NotificationContext; use rmcp::service::RequestContext; @@ -41,11 +40,7 @@ impl ClientHandler for LoggingClientHandler { request: CreateElicitationRequestParam, context: RequestContext, ) -> Result { - let id = match context.id { - RequestId::String(id) => mcp_types::RequestId::String(id.to_string()), - RequestId::Number(id) => mcp_types::RequestId::Integer(id), - }; - (self.send_elicitation)(id, request) + (self.send_elicitation)(context.id, request) .await .map_err(|err| rmcp::ErrorData::internal_error(err.to_string(), None)) } diff --git a/codex-rs/rmcp-client/src/rmcp_client.rs b/codex-rs/rmcp-client/src/rmcp_client.rs index c1bf6d39d3..12b4b52b91 100644 --- a/codex-rs/rmcp-client/src/rmcp_client.rs +++ b/codex-rs/rmcp-client/src/rmcp_client.rs @@ -10,22 +10,9 @@ use anyhow::Result; use anyhow::anyhow; use futures::FutureExt; use futures::future::BoxFuture; -use mcp_types::CallToolRequestParams; -use mcp_types::CallToolResult; -use mcp_types::InitializeRequestParams; -use mcp_types::InitializeResult; -use mcp_types::ListResourceTemplatesRequestParams; -use mcp_types::ListResourceTemplatesResult; -use mcp_types::ListResourcesRequestParams; -use mcp_types::ListResourcesResult; -use mcp_types::ListToolsRequestParams; -use mcp_types::ListToolsResult; -use mcp_types::ReadResourceRequestParams; -use mcp_types::ReadResourceResult; -use mcp_types::RequestId; -use mcp_types::Tool; use reqwest::header::HeaderMap; use rmcp::model::CallToolRequestParam; +use rmcp::model::CallToolResult; use rmcp::model::ClientNotification; use rmcp::model::ClientRequest; use rmcp::model::CreateElicitationRequestParam; @@ -34,9 +21,16 @@ use rmcp::model::CustomNotification; use rmcp::model::CustomRequest; use rmcp::model::Extensions; use rmcp::model::InitializeRequestParam; +use rmcp::model::InitializeResult; +use rmcp::model::ListResourceTemplatesResult; +use rmcp::model::ListResourcesResult; +use rmcp::model::ListToolsResult; use rmcp::model::PaginatedRequestParam; use rmcp::model::ReadResourceRequestParam; +use rmcp::model::ReadResourceResult; +use rmcp::model::RequestId; use rmcp::model::ServerResult; +use rmcp::model::Tool; use rmcp::service::RoleClient; use rmcp::service::RunningService; use rmcp::service::{self}; @@ -62,9 +56,6 @@ use crate::oauth::StoredOAuthTokens; use crate::program_resolver; use crate::utils::apply_default_headers; use crate::utils::build_default_headers; -use crate::utils::convert_call_tool_result; -use crate::utils::convert_to_mcp; -use crate::utils::convert_to_rmcp; use crate::utils::create_env_for_mcp_server; use crate::utils::run_with_timeout; @@ -229,12 +220,11 @@ impl RmcpClient { /// https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle#initialization pub async fn initialize( &self, - params: InitializeRequestParams, + params: InitializeRequestParam, timeout: Option, send_elicitation: SendElicitation, ) -> Result { - let rmcp_params: InitializeRequestParam = convert_to_rmcp(params.clone())?; - let client_handler = LoggingClientHandler::new(rmcp_params, send_elicitation); + let client_handler = LoggingClientHandler::new(params.clone(), send_elicitation); let (transport, oauth_persistor) = { let mut guard = self.state.lock().await; @@ -275,7 +265,7 @@ impl RmcpClient { .peer() .peer_info() .ok_or_else(|| anyhow!("handshake succeeded but server info was missing"))?; - let initialize_result = convert_to_mcp(initialize_result_rmcp)?; + let initialize_result = initialize_result_rmcp.clone(); { let mut guard = self.state.lock().await; @@ -296,28 +286,26 @@ impl RmcpClient { pub async fn list_tools( &self, - params: Option, + params: Option, timeout: Option, ) -> Result { - let result = self.list_tools_with_connector_ids(params, timeout).await?; - Ok(ListToolsResult { - next_cursor: result.next_cursor, - tools: result.tools.into_iter().map(|tool| tool.tool).collect(), - }) + self.refresh_oauth_if_needed().await; + let service = self.service().await?; + let fut = service.list_tools(params); + let result = run_with_timeout(fut, timeout, "tools/list").await?; + self.persist_oauth_tokens().await; + Ok(result) } pub async fn list_tools_with_connector_ids( &self, - params: Option, + params: Option, timeout: Option, ) -> Result { self.refresh_oauth_if_needed().await; let service = self.service().await?; - let rmcp_params = params - .map(convert_to_rmcp::<_, PaginatedRequestParam>) - .transpose()?; - let fut = service.list_tools(rmcp_params); + let fut = service.list_tools(params); let result = run_with_timeout(fut, timeout, "tools/list").await?; let tools = result .tools @@ -327,7 +315,6 @@ impl RmcpClient { let connector_id = Self::meta_string(meta, "connector_id"); let connector_name = Self::meta_string(meta, "connector_name") .or_else(|| Self::meta_string(meta, "connector_display_name")); - let tool = convert_to_mcp(tool)?; Ok(ToolWithConnectorId { tool, connector_id, @@ -352,53 +339,43 @@ impl RmcpClient { pub async fn list_resources( &self, - params: Option, + params: Option, timeout: Option, ) -> Result { self.refresh_oauth_if_needed().await; let service = self.service().await?; - let rmcp_params = params - .map(convert_to_rmcp::<_, PaginatedRequestParam>) - .transpose()?; - let fut = service.list_resources(rmcp_params); + let fut = service.list_resources(params); let result = run_with_timeout(fut, timeout, "resources/list").await?; - let converted = convert_to_mcp(result)?; self.persist_oauth_tokens().await; - Ok(converted) + Ok(result) } pub async fn list_resource_templates( &self, - params: Option, + params: Option, timeout: Option, ) -> Result { self.refresh_oauth_if_needed().await; let service = self.service().await?; - let rmcp_params = params - .map(convert_to_rmcp::<_, PaginatedRequestParam>) - .transpose()?; - let fut = service.list_resource_templates(rmcp_params); + let fut = service.list_resource_templates(params); let result = run_with_timeout(fut, timeout, "resources/templates/list").await?; - let converted = convert_to_mcp(result)?; self.persist_oauth_tokens().await; - Ok(converted) + Ok(result) } pub async fn read_resource( &self, - params: ReadResourceRequestParams, + params: ReadResourceRequestParam, timeout: Option, ) -> Result { self.refresh_oauth_if_needed().await; let service = self.service().await?; - let rmcp_params: ReadResourceRequestParam = convert_to_rmcp(params)?; - let fut = service.read_resource(rmcp_params); + let fut = service.read_resource(params); let result = run_with_timeout(fut, timeout, "resources/read").await?; - let converted = convert_to_mcp(result)?; self.persist_oauth_tokens().await; - Ok(converted) + Ok(result) } pub async fn call_tool( @@ -409,13 +386,23 @@ impl RmcpClient { ) -> Result { self.refresh_oauth_if_needed().await; let service = self.service().await?; - let params = CallToolRequestParams { arguments, name }; - let rmcp_params: CallToolRequestParam = convert_to_rmcp(params)?; + let arguments = match arguments { + Some(Value::Object(map)) => Some(map), + Some(other) => { + return Err(anyhow!( + "MCP tool arguments must be a JSON object, got {other}" + )); + } + None => None, + }; + let rmcp_params = CallToolRequestParam { + name: name.into(), + arguments, + }; let fut = service.call_tool(rmcp_params); - let rmcp_result = run_with_timeout(fut, timeout, "tools/call").await?; - let converted = convert_call_tool_result(rmcp_result)?; + let result = run_with_timeout(fut, timeout, "tools/call").await?; self.persist_oauth_tokens().await; - Ok(converted) + Ok(result) } pub async fn send_custom_notification( diff --git a/codex-rs/rmcp-client/src/utils.rs b/codex-rs/rmcp-client/src/utils.rs index 8deb4d402b..e47c1d14b6 100644 --- a/codex-rs/rmcp-client/src/utils.rs +++ b/codex-rs/rmcp-client/src/utils.rs @@ -5,14 +5,11 @@ use std::time::Duration; use anyhow::Context; use anyhow::Result; use anyhow::anyhow; -use mcp_types::CallToolResult; use reqwest::ClientBuilder; use reqwest::header::HeaderMap; use reqwest::header::HeaderName; use reqwest::header::HeaderValue; -use rmcp::model::CallToolResult as RmcpCallToolResult; use rmcp::service::ServiceError; -use serde_json::Value; use tokio::time; pub(crate) async fn run_with_timeout( @@ -33,45 +30,6 @@ where } } -pub(crate) fn convert_call_tool_result(result: RmcpCallToolResult) -> Result { - let mut value = serde_json::to_value(result)?; - if let Some(obj) = value.as_object_mut() - && (obj.get("content").is_none() - || obj.get("content").is_some_and(serde_json::Value::is_null)) - { - obj.insert("content".to_string(), Value::Array(Vec::new())); - } - serde_json::from_value(value).context("failed to convert call tool result") -} - -/// Convert from mcp-types to Rust SDK types. -/// -/// The Rust SDK types are the same as our mcp-types crate because they are both -/// derived from the same MCP specification. -/// As a result, it should be safe to convert directly from one to the other. -pub(crate) fn convert_to_rmcp(value: T) -> Result -where - T: serde::Serialize, - U: serde::de::DeserializeOwned, -{ - let json = serde_json::to_value(value)?; - serde_json::from_value(json).map_err(|err| anyhow!(err)) -} - -/// Convert from Rust SDK types to mcp-types. -/// -/// The Rust SDK types are the same as our mcp-types crate because they are both -/// derived from the same MCP specification. -/// As a result, it should be safe to convert directly from one to the other. -pub(crate) fn convert_to_mcp(value: T) -> Result -where - T: serde::Serialize, - U: serde::de::DeserializeOwned, -{ - let json = serde_json::to_value(value)?; - serde_json::from_value(json).map_err(|err| anyhow!(err)) -} - pub(crate) fn create_env_for_mcp_server( extra_env: Option>, env_vars: &[String], @@ -203,10 +161,7 @@ pub(crate) const DEFAULT_ENV_VARS: &[&str] = &[ #[cfg(test)] mod tests { use super::*; - use mcp_types::ContentBlock; use pretty_assertions::assert_eq; - use rmcp::model::CallToolResult as RmcpCallToolResult; - use serde_json::json; use serial_test::serial; use std::ffi::OsString; @@ -260,43 +215,4 @@ mod tests { let env = create_env_for_mcp_server(None, &[custom_var.to_string()]); assert_eq!(env.get(custom_var), Some(&value.to_string())); } - - #[test] - fn convert_call_tool_result_defaults_missing_content() -> Result<()> { - let structured_content = json!({ "key": "value" }); - let rmcp_result = RmcpCallToolResult { - content: vec![], - structured_content: Some(structured_content.clone()), - is_error: Some(true), - meta: None, - }; - - let result = convert_call_tool_result(rmcp_result)?; - - assert!(result.content.is_empty()); - assert_eq!(result.structured_content, Some(structured_content)); - assert_eq!(result.is_error, Some(true)); - - Ok(()) - } - - #[test] - fn convert_call_tool_result_preserves_existing_content() -> Result<()> { - let rmcp_result = RmcpCallToolResult::success(vec![rmcp::model::Content::text("hello")]); - - let result = convert_call_tool_result(rmcp_result)?; - - assert_eq!(result.content.len(), 1); - match &result.content[0] { - ContentBlock::TextContent(text_content) => { - assert_eq!(text_content.text, "hello"); - assert_eq!(text_content.r#type, "text"); - } - other => panic!("expected text content got {other:?}"), - } - assert_eq!(result.structured_content, None); - assert_eq!(result.is_error, Some(false)); - - Ok(()) - } } diff --git a/codex-rs/rmcp-client/tests/resources.rs b/codex-rs/rmcp-client/tests/resources.rs index 3d627ebbf4..9bfd77c183 100644 --- a/codex-rs/rmcp-client/tests/resources.rs +++ b/codex-rs/rmcp-client/tests/resources.rs @@ -7,15 +7,15 @@ use codex_rmcp_client::ElicitationResponse; use codex_rmcp_client::RmcpClient; use codex_utils_cargo_bin::CargoBinError; use futures::FutureExt as _; -use mcp_types::ClientCapabilities; -use mcp_types::Implementation; -use mcp_types::InitializeRequestParams; -use mcp_types::ListResourceTemplatesResult; -use mcp_types::ReadResourceRequestParams; -use mcp_types::ReadResourceResultContents; -use mcp_types::Resource; -use mcp_types::ResourceTemplate; -use mcp_types::TextResourceContents; +use rmcp::model::AnnotateAble; +use rmcp::model::ClientCapabilities; +use rmcp::model::ElicitationCapability; +use rmcp::model::Implementation; +use rmcp::model::InitializeRequestParam; +use rmcp::model::ListResourceTemplatesResult; +use rmcp::model::ProtocolVersion; +use rmcp::model::ReadResourceRequestParam; +use rmcp::model::ResourceContents; use serde_json::json; const RESOURCE_URI: &str = "memo://codex/example-note"; @@ -24,21 +24,24 @@ fn stdio_server_bin() -> Result { codex_utils_cargo_bin::cargo_bin("test_stdio_server") } -fn init_params() -> InitializeRequestParams { - InitializeRequestParams { +fn init_params() -> InitializeRequestParam { + InitializeRequestParam { capabilities: ClientCapabilities { experimental: None, roots: None, sampling: None, - elicitation: Some(json!({})), + elicitation: Some(ElicitationCapability { + schema_validation: None, + }), }, client_info: Implementation { name: "codex-test".into(), version: "0.0.0-test".into(), title: Some("Codex rmcp resource test".into()), - user_agent: None, + icons: None, + website_url: None, }, - protocol_version: mcp_types::MCP_SCHEMA_VERSION.to_string(), + protocol_version: ProtocolVersion::V_2025_06_18, } } @@ -79,15 +82,17 @@ async fn rmcp_client_can_list_and_read_resources() -> anyhow::Result<()> { .expect("memo resource present"); assert_eq!( memo, - &Resource { - annotations: None, + &rmcp::model::RawResource { + uri: RESOURCE_URI.to_string(), + name: "example-note".to_string(), + title: Some("Example Note".to_string()), description: Some("A sample MCP resource exposed for integration tests.".to_string()), mime_type: Some("text/plain".to_string()), - name: "example-note".to_string(), size: None, - title: Some("Example Note".to_string()), - uri: RESOURCE_URI.to_string(), + icons: None, + meta: None, } + .no_annotation() ); let templates = client .list_resource_templates(None, Some(Duration::from_secs(5))) @@ -95,39 +100,39 @@ async fn rmcp_client_can_list_and_read_resources() -> anyhow::Result<()> { assert_eq!( templates, ListResourceTemplatesResult { + meta: None, next_cursor: None, - resource_templates: vec![ResourceTemplate { - annotations: None, - description: Some( - "Template for memo://codex/{slug} resources used in tests.".to_string() - ), - mime_type: Some("text/plain".to_string()), - name: "codex-memo".to_string(), - title: Some("Codex Memo".to_string()), - uri_template: "memo://codex/{slug}".to_string(), - }], + resource_templates: vec![ + rmcp::model::RawResourceTemplate { + uri_template: "memo://codex/{slug}".to_string(), + name: "codex-memo".to_string(), + title: Some("Codex Memo".to_string()), + description: Some( + "Template for memo://codex/{slug} resources used in tests.".to_string(), + ), + mime_type: Some("text/plain".to_string()), + } + .no_annotation() + ], } ); let read = client .read_resource( - ReadResourceRequestParams { + ReadResourceRequestParam { uri: RESOURCE_URI.to_string(), }, Some(Duration::from_secs(5)), ) .await?; - let ReadResourceResultContents::TextResourceContents(text) = - read.contents.first().expect("resource contents present") - else { - panic!("expected text resource"); - }; + let text = read.contents.first().expect("resource contents present"); assert_eq!( text, - &TextResourceContents { - text: "This is a sample MCP resource served by the rmcp test server.".to_string(), + &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, } ); diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index d859aa945e..8bdd473220 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -54,7 +54,6 @@ dunce = { workspace = true } image = { workspace = true, features = ["jpeg", "png"] } itertools = { workspace = true } lazy_static = { workspace = true } -mcp-types = { workspace = true } pathdiff = { workspace = true } pulldown-cmark = { workspace = true } rand = { workspace = true } @@ -67,6 +66,7 @@ ratatui = { workspace = true, features = [ ratatui-macros = { workspace = true } regex-lite = { workspace = true } reqwest = { version = "0.12", features = ["json"] } +rmcp = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true, features = ["preserve_order"] } shlex = { workspace = true } diff --git a/codex-rs/tui/src/bottom_pane/approval_overlay.rs b/codex-rs/tui/src/bottom_pane/approval_overlay.rs index 0f0445fee8..15f252e86f 100644 --- a/codex-rs/tui/src/bottom_pane/approval_overlay.rs +++ b/codex-rs/tui/src/bottom_pane/approval_overlay.rs @@ -23,11 +23,11 @@ use codex_core::protocol::ExecPolicyAmendment; use codex_core::protocol::FileChange; use codex_core::protocol::Op; use codex_core::protocol::ReviewDecision; +use codex_protocol::mcp::RequestId; use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use crossterm::event::KeyEventKind; use crossterm::event::KeyModifiers; -use mcp_types::RequestId; use ratatui::buffer::Buffer; use ratatui::layout::Rect; use ratatui::style::Stylize; diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__binary_size_ideal_response.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__binary_size_ideal_response.snap index 77738439a1..38fb05e28d 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__binary_size_ideal_response.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__binary_size_ideal_response.snap @@ -27,7 +27,7 @@ expression: "lines[start_idx..].join(\"\\n\")" exec, linux-sandbox, tui, login, ollama, and mcp. • Ran for d in ansi-escape apply-patch arg0 cli common core exec execpolicy - │ file-search linux-sandbox login mcp-client mcp-server mcp-types ollama + │ file-search linux-sandbox login mcp-client mcp-server ollama │ tui; do echo "--- $d/Cargo.toml"; sed -n '1,200p' $d/Cargo.toml; echo; │ … +1 lines └ --- ansi-escape/Cargo.toml diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 934c9506f5..7113726288 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -46,6 +46,8 @@ use codex_core::protocol::McpInvocation; use codex_core::protocol::SessionConfiguredEvent; use codex_core::web_search::web_search_detail; use codex_otel::RuntimeMetricsSummary; +use codex_protocol::mcp::Resource; +use codex_protocol::mcp::ResourceTemplate; use codex_protocol::models::WebSearchAction; use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig; use codex_protocol::plan_tool::PlanItemArg; @@ -54,10 +56,6 @@ use codex_protocol::plan_tool::UpdatePlanArgs; use codex_protocol::user_input::TextElement; use image::DynamicImage; use image::ImageReader; -use mcp_types::EmbeddedResourceResource; -use mcp_types::Resource; -use mcp_types::ResourceLink; -use mcp_types::ResourceTemplate; use ratatui::prelude::*; use ratatui::style::Color; use ratatui::style::Modifier; @@ -1199,7 +1197,7 @@ pub(crate) struct McpToolCallCell { invocation: McpInvocation, start_time: Instant, duration: Option, - result: Option>, + result: Option>, animations_enabled: bool, } @@ -1226,7 +1224,7 @@ impl McpToolCallCell { pub(crate) fn complete( &mut self, duration: Duration, - result: Result, + result: Result, ) -> Option> { let image_cell = try_new_completed_mcp_tool_call_with_image_output(&result) .map(|cell| Box::new(cell) as Box); @@ -1249,23 +1247,32 @@ impl McpToolCallCell { self.result = Some(Err("interrupted".to_string())); } - fn render_content_block(block: &mcp_types::ContentBlock, width: usize) -> String { - match block { - mcp_types::ContentBlock::TextContent(text) => { + fn render_content_block(block: &serde_json::Value, width: usize) -> String { + let content = match serde_json::from_value::(block.clone()) { + Ok(content) => content, + Err(_) => { + return format_and_truncate_tool_result( + &block.to_string(), + TOOL_CALL_MAX_LINES, + width, + ); + } + }; + + match content.raw { + rmcp::model::RawContent::Text(text) => { format_and_truncate_tool_result(&text.text, TOOL_CALL_MAX_LINES, width) } - mcp_types::ContentBlock::ImageContent(_) => "".to_string(), - mcp_types::ContentBlock::AudioContent(_) => "