use std::fmt;
use std::path::PathBuf;
use std::time::Duration;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;
use crate::mcp::config::McpConfigError;
pub const MCP_PROTOCOL_VERSION: &str = "2025-03-26";
pub const JSONRPC_VERSION: &str = "2.0";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImplementationInfo {
pub name: String,
pub version: String,
}
impl ImplementationInfo {
pub fn blyte() -> Self {
Self {
name: "blyte".to_string(),
version: env!("CARGO_PKG_VERSION").to_string(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InitializeResult {
pub protocol_version: String,
#[serde(default)]
pub capabilities: Value,
#[serde(default)]
pub server_info: Option<ImplementationInfo>,
#[serde(default)]
pub instructions: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolAnnotations {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub read_only_hint: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub destructive_hint: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub idempotent_hint: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub open_world_hint: Option<bool>,
}
fn default_input_schema() -> Value {
serde_json::json!({ "type": "object", "properties": {} })
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Tool {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default = "default_input_schema")]
pub input_schema: Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub annotations: Option<ToolAnnotations>,
}
impl Tool {
pub fn is_read_only(&self) -> bool {
self.annotations
.as_ref()
.and_then(|a| a.read_only_hint)
.unwrap_or(false)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolsListResult {
#[serde(default)]
pub tools: Vec<Tool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub next_cursor: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResourceContent {
pub uri: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mime_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub text: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub blob: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ContentBlock {
Text {
text: String,
},
Image {
data: String,
mime_type: String,
},
Audio {
data: String,
mime_type: String,
},
Resource {
resource: ResourceContent,
},
ResourceLink {
uri: String,
name: Option<String>,
description: Option<String>,
mime_type: Option<String>,
},
Other(Value),
}
impl Serialize for ContentBlock {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let value = match self {
Self::Text { text } => serde_json::json!({
"type": "text",
"text": text,
}),
Self::Image { data, mime_type } => serde_json::json!({
"type": "image",
"data": data,
"mimeType": mime_type,
}),
Self::Audio { data, mime_type } => serde_json::json!({
"type": "audio",
"data": data,
"mimeType": mime_type,
}),
Self::Resource { resource } => serde_json::json!({
"type": "resource",
"resource": resource,
}),
Self::ResourceLink {
uri,
name,
description,
mime_type,
} => {
let mut obj = serde_json::Map::new();
obj.insert(
"type".to_string(),
Value::String("resource_link".to_string()),
);
obj.insert("uri".to_string(), Value::String(uri.clone()));
if let Some(name) = name {
obj.insert("name".to_string(), Value::String(name.clone()));
}
if let Some(description) = description {
obj.insert(
"description".to_string(),
Value::String(description.clone()),
);
}
if let Some(mime_type) = mime_type {
obj.insert("mimeType".to_string(), Value::String(mime_type.clone()));
}
Value::Object(obj)
}
Self::Other(v) => v.clone(),
};
value.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for ContentBlock {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = Value::deserialize(deserializer)?;
let kind = value.get("type").and_then(Value::as_str);
match kind {
Some("text") => {
let text = value
.get("text")
.and_then(Value::as_str)
.ok_or_else(|| serde::de::Error::missing_field("text"))?
.to_string();
Ok(Self::Text { text })
}
Some("image") => {
let data = value
.get("data")
.and_then(Value::as_str)
.ok_or_else(|| serde::de::Error::missing_field("data"))?
.to_string();
let mime_type = value
.get("mimeType")
.and_then(Value::as_str)
.ok_or_else(|| serde::de::Error::missing_field("mimeType"))?
.to_string();
Ok(Self::Image { data, mime_type })
}
Some("audio") => {
let data = value
.get("data")
.and_then(Value::as_str)
.ok_or_else(|| serde::de::Error::missing_field("data"))?
.to_string();
let mime_type = value
.get("mimeType")
.and_then(Value::as_str)
.ok_or_else(|| serde::de::Error::missing_field("mimeType"))?
.to_string();
Ok(Self::Audio { data, mime_type })
}
Some("resource") => {
let res_val = value
.get("resource")
.cloned()
.ok_or_else(|| serde::de::Error::missing_field("resource"))?;
let resource: ResourceContent =
serde_json::from_value(res_val).map_err(serde::de::Error::custom)?;
Ok(Self::Resource { resource })
}
Some("resource_link") => {
let uri = value
.get("uri")
.and_then(Value::as_str)
.ok_or_else(|| serde::de::Error::missing_field("uri"))?
.to_string();
let name = value
.get("name")
.and_then(Value::as_str)
.map(str::to_string);
let description = value
.get("description")
.and_then(Value::as_str)
.map(str::to_string);
let mime_type = value
.get("mimeType")
.and_then(Value::as_str)
.map(str::to_string);
Ok(Self::ResourceLink {
uri,
name,
description,
mime_type,
})
}
_ => Ok(Self::Other(value)),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolCallResult {
#[serde(default)]
pub content: Vec<ContentBlock>,
#[serde(default)]
pub is_error: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub structured_content: Option<Value>,
}
impl ToolCallResult {
pub fn text_content(&self) -> String {
let mut parts = Vec::new();
for block in &self.content {
match block {
ContentBlock::Text { text } => parts.push(text.clone()),
ContentBlock::Image { mime_type, .. } => {
parts.push(format!("[image: {mime_type}]"));
}
ContentBlock::Audio { mime_type, .. } => {
parts.push(format!("[audio: {mime_type}]"));
}
ContentBlock::Resource { resource } => {
if let Some(text) = &resource.text {
parts.push(text.clone());
} else {
parts.push(format!("[resource: {}]", resource.uri));
}
}
ContentBlock::ResourceLink { uri, name, .. } => {
if let Some(name) = name {
parts.push(format!("[resource_link: {name} ({uri})]"));
} else {
parts.push(format!("[resource_link: {uri}]"));
}
}
ContentBlock::Other(v) => parts.push(v.to_string()),
}
}
parts.join("\n")
}
}
#[derive(Debug, Clone, Serialize)]
pub struct JsonRpcRequest<'a> {
pub jsonrpc: &'static str,
pub id: u64,
pub method: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
pub params: Option<Value>,
}
#[derive(Debug, Clone, Serialize)]
pub struct JsonRpcNotification<'a> {
pub jsonrpc: &'static str,
pub method: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
pub params: Option<Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JsonRpcErrorObject {
pub code: i64,
pub message: String,
#[serde(default)]
pub data: Option<Value>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct JsonRpcResponse {
pub jsonrpc: Option<String>,
#[serde(default)]
pub id: Option<Value>,
#[serde(default)]
pub result: Option<Value>,
#[serde(default)]
pub error: Option<JsonRpcErrorObject>,
}
impl JsonRpcResponse {
pub fn matches_id(&self, expected_id: u64) -> bool {
match &self.id {
Some(Value::Number(n)) => n.as_u64() == Some(expected_id),
Some(Value::String(s)) => s.parse::<u64>().ok() == Some(expected_id),
_ => false,
}
}
pub fn into_result(self) -> Result<Value, McpError> {
if let Some(err) = self.error {
return Err(McpError::Rpc {
code: err.code,
message: err.message,
data: err.data,
});
}
self.result.ok_or_else(|| {
McpError::Protocol(
"JSON-RPC response contained neither 'result' nor 'error'".to_string(),
)
})
}
}
#[derive(Debug)]
pub enum McpError {
Config(McpConfigError),
UntrustedProjectServer {
name: String,
path: PathBuf,
},
NeedsAuth {
www_authenticate: Option<String>,
status: u16,
},
HttpStatus {
status: u16,
body: String,
},
Rpc {
code: i64,
message: String,
data: Option<Value>,
},
Protocol(String),
Timeout {
operation: String,
timeout: Duration,
},
Transport {
message: String,
stderr: Option<String>,
},
Io(std::io::Error),
}
impl From<McpConfigError> for McpError {
fn from(err: McpConfigError) -> Self {
Self::Config(err)
}
}
impl From<std::io::Error> for McpError {
fn from(err: std::io::Error) -> Self {
Self::Io(err)
}
}
impl fmt::Display for McpError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Config(e) => write!(f, "{e}"),
Self::UntrustedProjectServer { name, path } => write!(
f,
"refusing to run untrusted project MCP server '{name}' from {}; explicit user approval is required",
path.display()
),
Self::NeedsAuth {
www_authenticate,
status,
} => match www_authenticate {
Some(header) => write!(f, "MCP server requires authentication (HTTP {status}; WWW-Authenticate: {header})"),
None => write!(f, "MCP server requires authentication (HTTP {status})"),
},
Self::HttpStatus { status, body } => {
if body.trim().is_empty() {
write!(f, "MCP HTTP request failed with status {status}")
} else {
write!(f, "MCP HTTP request failed with status {status}: {body}")
}
}
Self::Rpc {
code,
message,
data,
} => match data {
Some(d) => write!(f, "MCP JSON-RPC error {code}: {message} ({d})"),
None => write!(f, "MCP JSON-RPC error {code}: {message}"),
},
Self::Protocol(msg) => write!(f, "MCP protocol error: {msg}"),
Self::Timeout { operation, timeout } => {
write!(f, "MCP operation '{operation}' timed out after {}ms", timeout.as_millis())
}
Self::Transport { message, stderr } => match stderr {
Some(err) if !err.trim().is_empty() => {
write!(f, "MCP transport error: {message} (stderr: {})", err.trim())
}
_ => write!(f, "MCP transport error: {message}"),
},
Self::Io(e) => write!(f, "MCP I/O error: {e}"),
}
}
}
impl std::error::Error for McpError {}