diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 2bd66370..ed0b562b 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1940,6 +1940,14 @@ dependencies = [ "regex-automata 0.1.10", ] +[[package]] +name = "mcp-types" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "memchr" version = "2.7.4" diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index ea000731..ded97915 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -7,6 +7,7 @@ members = [ "core", "exec", "execpolicy", + "mcp-types", "tui", ] diff --git a/codex-rs/mcp-types/Cargo.toml b/codex-rs/mcp-types/Cargo.toml new file mode 100644 index 00000000..cefbcc9c --- /dev/null +++ b/codex-rs/mcp-types/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "mcp-types" +version = "0.1.0" +edition = "2021" + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" diff --git a/codex-rs/mcp-types/README.md b/codex-rs/mcp-types/README.md new file mode 100644 index 00000000..2ac613ea --- /dev/null +++ b/codex-rs/mcp-types/README.md @@ -0,0 +1,8 @@ +# mcp-types + +Types for Model Context Protocol. Inspired by https://crates.io/crates/lsp-types. + +As documented on https://modelcontextprotocol.io/specification/2025-03-26/basic: + +- TypeScript schema is the source of truth: https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/schema/2025-03-26/schema.ts +- JSON schema is amenable to automated tooling: https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/schema/2025-03-26/schema.json diff --git a/codex-rs/mcp-types/generate_mcp_types.py b/codex-rs/mcp-types/generate_mcp_types.py new file mode 100755 index 00000000..f613aa74 --- /dev/null +++ b/codex-rs/mcp-types/generate_mcp_types.py @@ -0,0 +1,621 @@ +#!/usr/bin/env python3 +# flake8: noqa: E501 + +import json +import subprocess +import sys + +from dataclasses import ( + dataclass, +) +from pathlib import Path + +# Helper first so it is defined when other functions call it. +from typing import Any, Literal + + +STANDARD_DERIVE = "#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]\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] = [] + + +def main() -> int: + num_args = len(sys.argv) + if num_args == 1: + schema_file = ( + Path(__file__).resolve().parent / "schema" / "2025-03-26" / "schema.json" + ) + elif num_args == 2: + schema_file = Path(sys.argv[1]) + else: + print("Usage: python3 codegen.py ") + return 1 + + lib_rs = Path(__file__).resolve().parent / "src/lib.rs" + + 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 = [ + """ +// @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; + +/// 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; +} + +""" + ] + 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) + + subprocess.check_call( + ["cargo", "fmt", "--", "--config", "imports_granularity=Item"], + cwd=lib_rs.parent.parent, + stderr=subprocess.DEVNULL, + ) + + return 0 + + +def add_definition(name: str, definition: dict[str, Any], out: list[str]) -> None: + # 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)) + 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) + if name == "JSONRPCMessage": + # Special case for JSONRPCMessage because its definition in the + # JSON schema does not quite match how we think about this type + # definition in Rust. + deep_copied_any_of = json.loads(json.dumps(any_of)) + deep_copied_any_of[2] = { + "$ref": "#/definitions/JSONRPCBatchRequest", + } + deep_copied_any_of[5] = { + "$ref": "#/definitions/JSONRPCBatchResponse", + } + out.extend(define_any_of(name, deep_copied_any_of, description)) + else: + 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 + + def append(self, out: list[str], supports_const: bool) -> None: + # Omit these for now. + if self.name == "jsonrpc": + return + + if self.serde: + out.append(f" {self.serde}\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 define_struct( + name: str, + properties: dict[str, Any], + required_props: set[str], + description: str | None, +) -> list[str]: + out: list[str] = [] + + fields: list[StructField] = [] + for prop_name, prop in properties.items(): + if prop_name == "_meta": + # TODO? + continue + + prop_type = map_type(prop, prop_name, name) + if prop_name not in required_props: + prop_type = f"Option<{prop_type}>" + rs_prop = rust_prop_name(prop_name) + if prop_type.startswith("&'static str"): + fields.append(StructField("const", rs_prop.name, prop_type, rs_prop.serde)) + else: + fields.append(StructField("pub", rs_prop.name, prop_type, rs_prop.serde)) + + 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("#[derive(Debug)]\n") + 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") + return out + + +def define_untagged_enum(name: str, type_list: list[str], out: list[str]) -> None: + out.append(STANDARD_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") + + 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 "JSONRPCMessage": + return "#[serde(untagged)]" + case _: + return None + + +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 + + +def rust_prop_name(name: str) -> RustProp: + """Convert a JSON property name to a Rust property name.""" + if name == "type": + return RustProp("r#type", None) + elif name == "ref": + return RustProp("r#ref", None) + elif snake_case := to_snake_case(name): + return RustProp(snake_case, f'#[serde(rename = "{name}")]') + else: + return RustProp(name, None) + + +def to_snake_case(name: str) -> str: + """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") + + +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 new file mode 100644 index 00000000..a1e3f267 --- /dev/null +++ b/codex-rs/mcp-types/schema/2025-03-26/schema.json @@ -0,0 +1,2139 @@ +{ + "$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 family, 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/src/lib.rs b/codex-rs/mcp-types/src/lib.rs new file mode 100644 index 00000000..4ae0fa09 --- /dev/null +++ b/codex-rs/mcp-types/src/lib.rs @@ -0,0 +1,1162 @@ +// @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::de::DeserializeOwned; +use serde::Deserialize; +use serde::Serialize; +use std::convert::TryFrom; + +/// 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; +} + +/// Optional annotations for the client. The client can use annotations to inform how objects are used or displayed +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct Annotations { + pub audience: Option>, + pub priority: Option, +} + +/// Audio provided to or from an LLM. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct AudioContent { + pub annotations: Option, + pub data: String, + #[serde(rename = "mimeType")] + pub mime_type: String, + pub r#type: String, // &'static str = "audio" +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct BlobResourceContents { + pub blob: String, + #[serde(rename = "mimeType")] + pub mime_type: Option, + pub uri: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +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)] +pub struct CallToolRequestParams { + pub arguments: Option, + pub name: String, +} + +/// The server's response to a tool call. +/// +/// Any errors that originate from the tool SHOULD be reported inside the result +/// object, with `isError` set to true, _not_ as an MCP protocol-level error +/// response. Otherwise, the LLM would not be able to see that an error occurred +/// and self-correct. +/// +/// However, any errors in _finding_ the tool, an error indicating that the +/// server does not support tool calls, or any other exceptional conditions, +/// should be reported as an MCP error response. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct CallToolResult { + pub content: Vec, + #[serde(rename = "isError")] + pub is_error: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub enum CallToolResultContent { + TextContent(TextContent), + ImageContent(ImageContent), + AudioContent(AudioContent), + EmbeddedResource(EmbeddedResource), +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub enum CancelledNotification {} + +impl ModelContextProtocolNotification for CancelledNotification { + const METHOD: &'static str = "notifications/cancelled"; + type Params = CancelledNotificationParams; +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct CancelledNotificationParams { + 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)] +pub struct ClientCapabilities { + pub experimental: Option, + pub roots: Option, + pub sampling: Option, +} + +/// Present if the client supports listing roots. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct ClientCapabilitiesRoots { + #[serde(rename = "listChanged")] + pub list_changed: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub enum ClientNotification { + CancelledNotification(CancelledNotification), + InitializedNotification(InitializedNotification), + ProgressNotification(ProgressNotification), + RootsListChangedNotification(RootsListChangedNotification), +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[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)] +pub enum ClientResult { + Result(Result), + CreateMessageResult(CreateMessageResult), + ListRootsResult(ListRootsResult), +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +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)] +pub struct CompleteRequestParams { + pub argument: CompleteRequestParamsArgument, + pub r#ref: CompleteRequestParamsRef, +} + +/// The argument's information +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct CompleteRequestParamsArgument { + pub name: String, + pub value: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub enum CompleteRequestParamsRef { + PromptReference(PromptReference), + ResourceReference(ResourceReference), +} + +/// The server's response to a completion/complete request +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct CompleteResult { + pub completion: CompleteResultCompletion, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct CompleteResultCompletion { + #[serde(rename = "hasMore")] + pub has_more: Option, + pub total: Option, + pub values: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +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)] +pub struct CreateMessageRequestParams { + #[serde(rename = "includeContext")] + pub include_context: Option, + #[serde(rename = "maxTokens")] + pub max_tokens: i64, + pub messages: Vec, + pub metadata: Option, + #[serde(rename = "modelPreferences")] + pub model_preferences: Option, + #[serde(rename = "stopSequences")] + pub stop_sequences: Option>, + #[serde(rename = "systemPrompt")] + pub system_prompt: Option, + 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)] +pub struct CreateMessageResult { + pub content: CreateMessageResultContent, + pub model: String, + pub role: Role, + #[serde(rename = "stopReason")] + pub stop_reason: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub enum CreateMessageResultContent { + TextContent(TextContent), + ImageContent(ImageContent), + AudioContent(AudioContent), +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct Cursor(String); + +/// 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)] +pub struct EmbeddedResource { + pub annotations: Option, + pub resource: EmbeddedResourceResource, + pub r#type: String, // &'static str = "resource" +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub enum EmbeddedResourceResource { + TextResourceContents(TextResourceContents), + BlobResourceContents(BlobResourceContents), +} + +pub type EmptyResult = Result; + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +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)] +pub struct GetPromptRequestParams { + pub arguments: Option, + pub name: String, +} + +/// The server's response to a prompts/get request from the client. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct GetPromptResult { + pub description: Option, + pub messages: Vec, +} + +/// An image provided to or from an LLM. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct ImageContent { + 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. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct Implementation { + pub name: String, + pub version: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub enum InitializeRequest {} + +impl ModelContextProtocolRequest for InitializeRequest { + const METHOD: &'static str = "initialize"; + type Params = InitializeRequestParams; + type Result = InitializeResult; +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +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)] +pub struct InitializeResult { + pub capabilities: ServerCapabilities, + pub instructions: Option, + #[serde(rename = "protocolVersion")] + pub protocol_version: String, + #[serde(rename = "serverInfo")] + pub server_info: Implementation, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub enum InitializedNotification {} + +impl ModelContextProtocolNotification for InitializedNotification { + const METHOD: &'static str = "notifications/initialized"; + type Params = Option; +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub enum JSONRPCBatchRequestItem { + JSONRPCRequest(JSONRPCRequest), + JSONRPCNotification(JSONRPCNotification), +} + +pub type JSONRPCBatchRequest = Vec; + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub enum JSONRPCBatchResponseItem { + JSONRPCResponse(JSONRPCResponse), + JSONRPCError(JSONRPCError), +} + +pub type JSONRPCBatchResponse = Vec; + +/// A response to a request that indicates an error occurred. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct JSONRPCError { + pub error: JSONRPCErrorError, + pub id: RequestId, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct JSONRPCErrorError { + pub code: i64, + 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)] +#[serde(untagged)] +pub enum JSONRPCMessage { + Request(JSONRPCRequest), + Notification(JSONRPCNotification), + BatchRequest(JSONRPCBatchRequest), + Response(JSONRPCResponse), + Error(JSONRPCError), + BatchResponse(JSONRPCBatchResponse), +} + +/// A notification which does not expect a response. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct JSONRPCNotification { + pub method: String, + pub params: Option, +} + +/// A request that expects a response. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct JSONRPCRequest { + pub id: RequestId, + pub method: String, + pub params: Option, +} + +/// A successful (non-error) response to a request. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct JSONRPCResponse { + pub id: RequestId, + pub result: Result, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +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)] +pub struct ListPromptsRequestParams { + pub cursor: Option, +} + +/// The server's response to a prompts/list request from the client. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct ListPromptsResult { + #[serde(rename = "nextCursor")] + pub next_cursor: Option, + pub prompts: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +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)] +pub struct ListResourceTemplatesRequestParams { + pub cursor: Option, +} + +/// The server's response to a resources/templates/list request from the client. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct ListResourceTemplatesResult { + #[serde(rename = "nextCursor")] + pub next_cursor: Option, + #[serde(rename = "resourceTemplates")] + pub resource_templates: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +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)] +pub struct ListResourcesRequestParams { + pub cursor: Option, +} + +/// The server's response to a resources/list request from the client. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct ListResourcesResult { + #[serde(rename = "nextCursor")] + pub next_cursor: Option, + pub resources: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +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)] +pub struct ListRootsResult { + pub roots: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +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)] +pub struct ListToolsRequestParams { + pub cursor: Option, +} + +/// The server's response to a tools/list request from the client. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct ListToolsResult { + #[serde(rename = "nextCursor")] + pub next_cursor: Option, + pub tools: Vec, +} + +/// 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)] +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)] +pub enum LoggingMessageNotification {} + +impl ModelContextProtocolNotification for LoggingMessageNotification { + const METHOD: &'static str = "notifications/message"; + type Params = LoggingMessageNotificationParams; +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct LoggingMessageNotificationParams { + pub data: serde_json::Value, + pub level: LoggingLevel, + 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)] +pub struct ModelHint { + 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)] +pub struct ModelPreferences { + #[serde(rename = "costPriority")] + pub cost_priority: Option, + pub hints: Option>, + #[serde(rename = "intelligencePriority")] + pub intelligence_priority: Option, + #[serde(rename = "speedPriority")] + pub speed_priority: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct Notification { + pub method: String, + pub params: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct PaginatedRequest { + pub method: String, + pub params: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct PaginatedRequestParams { + pub cursor: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct PaginatedResult { + #[serde(rename = "nextCursor")] + pub next_cursor: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub enum PingRequest {} + +impl ModelContextProtocolRequest for PingRequest { + const METHOD: &'static str = "ping"; + type Params = Option; + type Result = Result; +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub enum ProgressNotification {} + +impl ModelContextProtocolNotification for ProgressNotification { + const METHOD: &'static str = "notifications/progress"; + type Params = ProgressNotificationParams; +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct ProgressNotificationParams { + pub message: Option, + pub progress: f64, + #[serde(rename = "progressToken")] + pub progress_token: ProgressToken, + pub total: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(untagged)] +pub enum ProgressToken { + String(String), + Integer(i64), +} + +/// A prompt or prompt template that the server offers. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct Prompt { + pub arguments: Option>, + pub description: Option, + pub name: String, +} + +/// Describes an argument that a prompt can accept. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct PromptArgument { + pub description: Option, + pub name: String, + pub required: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +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)] +pub struct PromptMessage { + pub content: PromptMessageContent, + pub role: Role, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub enum PromptMessageContent { + TextContent(TextContent), + ImageContent(ImageContent), + AudioContent(AudioContent), + EmbeddedResource(EmbeddedResource), +} + +/// Identifies a prompt. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct PromptReference { + pub name: String, + pub r#type: String, // &'static str = "ref/prompt" +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +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)] +pub struct ReadResourceRequestParams { + pub uri: String, +} + +/// The server's response to a resources/read request from the client. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct ReadResourceResult { + pub contents: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub enum ReadResourceResultContents { + TextResourceContents(TextResourceContents), + BlobResourceContents(BlobResourceContents), +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct Request { + pub method: String, + pub params: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[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)] +pub struct Resource { + pub annotations: Option, + pub description: Option, + #[serde(rename = "mimeType")] + pub mime_type: Option, + pub name: String, + pub size: Option, + pub uri: String, +} + +/// The contents of a specific resource or sub-resource. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct ResourceContents { + #[serde(rename = "mimeType")] + pub mime_type: Option, + pub uri: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub enum ResourceListChangedNotification {} + +impl ModelContextProtocolNotification for ResourceListChangedNotification { + const METHOD: &'static str = "notifications/resources/list_changed"; + type Params = Option; +} + +/// A reference to a resource or resource template definition. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct ResourceReference { + pub r#type: String, // &'static str = "ref/resource" + pub uri: String, +} + +/// A template description for resources available on the server. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct ResourceTemplate { + pub annotations: Option, + pub description: Option, + #[serde(rename = "mimeType")] + pub mime_type: Option, + pub name: String, + #[serde(rename = "uriTemplate")] + pub uri_template: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub enum ResourceUpdatedNotification {} + +impl ModelContextProtocolNotification for ResourceUpdatedNotification { + const METHOD: &'static str = "notifications/resources/updated"; + type Params = ResourceUpdatedNotificationParams; +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct ResourceUpdatedNotificationParams { + pub uri: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct Result {} + +/// The sender or recipient of messages and data in a conversation. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +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)] +pub struct Root { + pub name: Option, + pub uri: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +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)] +pub struct SamplingMessage { + pub content: SamplingMessageContent, + pub role: Role, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +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)] +pub struct ServerCapabilities { + pub completions: Option, + pub experimental: Option, + pub logging: Option, + pub prompts: Option, + pub resources: Option, + pub tools: Option, +} + +/// Present if the server offers any tools to call. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct ServerCapabilitiesTools { + #[serde(rename = "listChanged")] + pub list_changed: Option, +} + +/// Present if the server offers any resources to read. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct ServerCapabilitiesResources { + #[serde(rename = "listChanged")] + pub list_changed: Option, + pub subscribe: Option, +} + +/// Present if the server offers any prompt templates. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct ServerCapabilitiesPrompts { + #[serde(rename = "listChanged")] + pub list_changed: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[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)] +pub enum ServerRequest { + PingRequest(PingRequest), + CreateMessageRequest(CreateMessageRequest), + ListRootsRequest(ListRootsRequest), +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +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)] +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)] +pub struct SetLevelRequestParams { + pub level: LoggingLevel, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +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)] +pub struct SubscribeRequestParams { + pub uri: String, +} + +/// Text provided to or from an LLM. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct TextContent { + pub annotations: Option, + pub text: String, + pub r#type: String, // &'static str = "text" +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct TextResourceContents { + #[serde(rename = "mimeType")] + pub mime_type: Option, + pub text: String, + pub uri: String, +} + +/// Definition for a tool the client can call. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct Tool { + pub annotations: Option, + pub description: Option, + #[serde(rename = "inputSchema")] + pub input_schema: ToolInputSchema, + pub name: String, +} + +/// A JSON Schema object defining the expected parameters for the tool. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct ToolInputSchema { + pub properties: Option, + pub required: Option>, + 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)] +pub struct ToolAnnotations { + #[serde(rename = "destructiveHint")] + pub destructive_hint: Option, + #[serde(rename = "idempotentHint")] + pub idempotent_hint: Option, + #[serde(rename = "openWorldHint")] + pub open_world_hint: Option, + #[serde(rename = "readOnlyHint")] + pub read_only_hint: Option, + pub title: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub enum ToolListChangedNotification {} + +impl ModelContextProtocolNotification for ToolListChangedNotification { + const METHOD: &'static str = "notifications/tools/list_changed"; + type Params = Option; +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +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)] +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/initialize.rs b/codex-rs/mcp-types/tests/initialize.rs new file mode 100644 index 00000000..e857f8db --- /dev/null +++ b/codex-rs/mcp-types/tests/initialize.rs @@ -0,0 +1,65 @@ +use mcp_types::ClientCapabilities; +use mcp_types::ClientRequest; +use mcp_types::Implementation; +use mcp_types::InitializeRequestParams; +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", "version": "1.2.3" }, + "protocolVersion": "2025-03-26" + } + }"#; + + // 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 { + id: RequestId::Integer(1), + method: "initialize".into(), + params: Some(json!({ + "capabilities": {}, + "clientInfo": { "name": "acme-client", "version": "1.2.3" }, + "protocolVersion": "2025-03-26" + })), + }; + + 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, + }, + client_info: Implementation { + name: "acme-client".into(), + version: "1.2.3".into(), + }, + protocol_version: "2025-03-26".into(), + } + ); +} diff --git a/codex-rs/mcp-types/tests/progress_notification.rs b/codex-rs/mcp-types/tests/progress_notification.rs new file mode 100644 index 00000000..396efca2 --- /dev/null +++ b/codex-rs/mcp-types/tests/progress_notification.rs @@ -0,0 +1,43 @@ +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); +}