Skip to main content

blyte_cli/mcp/
protocol.rs

1//! JSON-RPC 2.0 and Model Context Protocol data types and errors.
2
3use std::fmt;
4use std::path::PathBuf;
5use std::time::Duration;
6
7use serde::{Deserialize, Deserializer, Serialize, Serializer};
8use serde_json::Value;
9
10use crate::mcp::config::McpConfigError;
11
12/// MCP protocol version advertised by blyte during `initialize`.
13pub const MCP_PROTOCOL_VERSION: &str = "2025-03-26";
14
15/// JSON-RPC 2.0 version constant.
16pub const JSONRPC_VERSION: &str = "2.0";
17
18/// Client identity sent during `initialize`.
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20pub struct ImplementationInfo {
21    pub name: String,
22    pub version: String,
23}
24
25impl ImplementationInfo {
26    pub fn blyte() -> Self {
27        Self {
28            name: "blyte".to_string(),
29            version: env!("CARGO_PKG_VERSION").to_string(),
30        }
31    }
32}
33
34/// Result returned by the server from `initialize`.
35#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
36#[serde(rename_all = "camelCase")]
37pub struct InitializeResult {
38    pub protocol_version: String,
39    #[serde(default)]
40    pub capabilities: Value,
41    #[serde(default)]
42    pub server_info: Option<ImplementationInfo>,
43    #[serde(default)]
44    pub instructions: Option<String>,
45}
46
47/// Behavioral annotations advertised by an MCP tool.
48#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(rename_all = "camelCase")]
50pub struct ToolAnnotations {
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub title: Option<String>,
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub read_only_hint: Option<bool>,
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub destructive_hint: Option<bool>,
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub idempotent_hint: Option<bool>,
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub open_world_hint: Option<bool>,
61}
62
63fn default_input_schema() -> Value {
64    serde_json::json!({ "type": "object", "properties": {} })
65}
66
67/// Definition of a tool returned by `tools/list`.
68#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
69#[serde(rename_all = "camelCase")]
70pub struct Tool {
71    pub name: String,
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub description: Option<String>,
74    #[serde(default = "default_input_schema")]
75    pub input_schema: Value,
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub annotations: Option<ToolAnnotations>,
78}
79
80impl Tool {
81    /// Returns true only when the server explicitly marked `annotations.readOnlyHint == true`.
82    pub fn is_read_only(&self) -> bool {
83        self.annotations
84            .as_ref()
85            .and_then(|a| a.read_only_hint)
86            .unwrap_or(false)
87    }
88}
89
90/// Single page returned by `tools/list`.
91#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
92#[serde(rename_all = "camelCase")]
93pub struct ToolsListResult {
94    #[serde(default)]
95    pub tools: Vec<Tool>,
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub next_cursor: Option<String>,
98}
99
100/// Embedded resource payload inside a `ContentBlock::Resource`.
101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
102#[serde(rename_all = "camelCase")]
103pub struct ResourceContent {
104    pub uri: String,
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub mime_type: Option<String>,
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub text: Option<String>,
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub blob: Option<String>,
111}
112
113/// Structured content block returned by `tools/call`.
114#[derive(Debug, Clone, PartialEq)]
115pub enum ContentBlock {
116    Text {
117        text: String,
118    },
119    Image {
120        data: String,
121        mime_type: String,
122    },
123    Audio {
124        data: String,
125        mime_type: String,
126    },
127    Resource {
128        resource: ResourceContent,
129    },
130    ResourceLink {
131        uri: String,
132        name: Option<String>,
133        description: Option<String>,
134        mime_type: Option<String>,
135    },
136    Other(Value),
137}
138
139impl Serialize for ContentBlock {
140    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
141        let value = match self {
142            Self::Text { text } => serde_json::json!({
143                "type": "text",
144                "text": text,
145            }),
146            Self::Image { data, mime_type } => serde_json::json!({
147                "type": "image",
148                "data": data,
149                "mimeType": mime_type,
150            }),
151            Self::Audio { data, mime_type } => serde_json::json!({
152                "type": "audio",
153                "data": data,
154                "mimeType": mime_type,
155            }),
156            Self::Resource { resource } => serde_json::json!({
157                "type": "resource",
158                "resource": resource,
159            }),
160            Self::ResourceLink {
161                uri,
162                name,
163                description,
164                mime_type,
165            } => {
166                let mut obj = serde_json::Map::new();
167                obj.insert(
168                    "type".to_string(),
169                    Value::String("resource_link".to_string()),
170                );
171                obj.insert("uri".to_string(), Value::String(uri.clone()));
172                if let Some(name) = name {
173                    obj.insert("name".to_string(), Value::String(name.clone()));
174                }
175                if let Some(description) = description {
176                    obj.insert(
177                        "description".to_string(),
178                        Value::String(description.clone()),
179                    );
180                }
181                if let Some(mime_type) = mime_type {
182                    obj.insert("mimeType".to_string(), Value::String(mime_type.clone()));
183                }
184                Value::Object(obj)
185            }
186            Self::Other(v) => v.clone(),
187        };
188        value.serialize(serializer)
189    }
190}
191
192impl<'de> Deserialize<'de> for ContentBlock {
193    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
194        let value = Value::deserialize(deserializer)?;
195        let kind = value.get("type").and_then(Value::as_str);
196        match kind {
197            Some("text") => {
198                let text = value
199                    .get("text")
200                    .and_then(Value::as_str)
201                    .ok_or_else(|| serde::de::Error::missing_field("text"))?
202                    .to_string();
203                Ok(Self::Text { text })
204            }
205            Some("image") => {
206                let data = value
207                    .get("data")
208                    .and_then(Value::as_str)
209                    .ok_or_else(|| serde::de::Error::missing_field("data"))?
210                    .to_string();
211                let mime_type = value
212                    .get("mimeType")
213                    .and_then(Value::as_str)
214                    .ok_or_else(|| serde::de::Error::missing_field("mimeType"))?
215                    .to_string();
216                Ok(Self::Image { data, mime_type })
217            }
218            Some("audio") => {
219                let data = value
220                    .get("data")
221                    .and_then(Value::as_str)
222                    .ok_or_else(|| serde::de::Error::missing_field("data"))?
223                    .to_string();
224                let mime_type = value
225                    .get("mimeType")
226                    .and_then(Value::as_str)
227                    .ok_or_else(|| serde::de::Error::missing_field("mimeType"))?
228                    .to_string();
229                Ok(Self::Audio { data, mime_type })
230            }
231            Some("resource") => {
232                let res_val = value
233                    .get("resource")
234                    .cloned()
235                    .ok_or_else(|| serde::de::Error::missing_field("resource"))?;
236                let resource: ResourceContent =
237                    serde_json::from_value(res_val).map_err(serde::de::Error::custom)?;
238                Ok(Self::Resource { resource })
239            }
240            Some("resource_link") => {
241                let uri = value
242                    .get("uri")
243                    .and_then(Value::as_str)
244                    .ok_or_else(|| serde::de::Error::missing_field("uri"))?
245                    .to_string();
246                let name = value
247                    .get("name")
248                    .and_then(Value::as_str)
249                    .map(str::to_string);
250                let description = value
251                    .get("description")
252                    .and_then(Value::as_str)
253                    .map(str::to_string);
254                let mime_type = value
255                    .get("mimeType")
256                    .and_then(Value::as_str)
257                    .map(str::to_string);
258                Ok(Self::ResourceLink {
259                    uri,
260                    name,
261                    description,
262                    mime_type,
263                })
264            }
265            _ => Ok(Self::Other(value)),
266        }
267    }
268}
269
270/// Result returned by `tools/call`.
271#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
272#[serde(rename_all = "camelCase")]
273pub struct ToolCallResult {
274    #[serde(default)]
275    pub content: Vec<ContentBlock>,
276    #[serde(default)]
277    pub is_error: bool,
278    #[serde(default, skip_serializing_if = "Option::is_none")]
279    pub structured_content: Option<Value>,
280}
281
282impl ToolCallResult {
283    /// Renders a plain-text representation of the returned content blocks.
284    pub fn text_content(&self) -> String {
285        let mut parts = Vec::new();
286        for block in &self.content {
287            match block {
288                ContentBlock::Text { text } => parts.push(text.clone()),
289                ContentBlock::Image { mime_type, .. } => {
290                    parts.push(format!("[image: {mime_type}]"));
291                }
292                ContentBlock::Audio { mime_type, .. } => {
293                    parts.push(format!("[audio: {mime_type}]"));
294                }
295                ContentBlock::Resource { resource } => {
296                    if let Some(text) = &resource.text {
297                        parts.push(text.clone());
298                    } else {
299                        parts.push(format!("[resource: {}]", resource.uri));
300                    }
301                }
302                ContentBlock::ResourceLink { uri, name, .. } => {
303                    if let Some(name) = name {
304                        parts.push(format!("[resource_link: {name} ({uri})]"));
305                    } else {
306                        parts.push(format!("[resource_link: {uri}]"));
307                    }
308                }
309                ContentBlock::Other(v) => parts.push(v.to_string()),
310            }
311        }
312        parts.join("\n")
313    }
314}
315
316/// Outbound JSON-RPC 2.0 request envelope.
317#[derive(Debug, Clone, Serialize)]
318pub struct JsonRpcRequest<'a> {
319    pub jsonrpc: &'static str,
320    pub id: u64,
321    pub method: &'a str,
322    #[serde(skip_serializing_if = "Option::is_none")]
323    pub params: Option<Value>,
324}
325
326/// Outbound JSON-RPC 2.0 notification envelope (no `id`).
327#[derive(Debug, Clone, Serialize)]
328pub struct JsonRpcNotification<'a> {
329    pub jsonrpc: &'static str,
330    pub method: &'a str,
331    #[serde(skip_serializing_if = "Option::is_none")]
332    pub params: Option<Value>,
333}
334
335/// Inbound JSON-RPC 2.0 error object.
336#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
337pub struct JsonRpcErrorObject {
338    pub code: i64,
339    pub message: String,
340    #[serde(default)]
341    pub data: Option<Value>,
342}
343
344/// Inbound JSON-RPC 2.0 response envelope.
345#[derive(Debug, Clone, PartialEq, Deserialize)]
346pub struct JsonRpcResponse {
347    pub jsonrpc: Option<String>,
348    #[serde(default)]
349    pub id: Option<Value>,
350    #[serde(default)]
351    pub result: Option<Value>,
352    #[serde(default)]
353    pub error: Option<JsonRpcErrorObject>,
354}
355
356impl JsonRpcResponse {
357    pub fn matches_id(&self, expected_id: u64) -> bool {
358        match &self.id {
359            Some(Value::Number(n)) => n.as_u64() == Some(expected_id),
360            Some(Value::String(s)) => s.parse::<u64>().ok() == Some(expected_id),
361            _ => false,
362        }
363    }
364
365    pub fn into_result(self) -> Result<Value, McpError> {
366        if let Some(err) = self.error {
367            return Err(McpError::Rpc {
368                code: err.code,
369                message: err.message,
370                data: err.data,
371            });
372        }
373        self.result.ok_or_else(|| {
374            McpError::Protocol(
375                "JSON-RPC response contained neither 'result' nor 'error'".to_string(),
376            )
377        })
378    }
379}
380
381/// Errors returned by MCP transports and client operations.
382#[derive(Debug)]
383pub enum McpError {
384    Config(McpConfigError),
385    UntrustedProjectServer {
386        name: String,
387        path: PathBuf,
388    },
389    NeedsAuth {
390        www_authenticate: Option<String>,
391        status: u16,
392    },
393    HttpStatus {
394        status: u16,
395        body: String,
396    },
397    Rpc {
398        code: i64,
399        message: String,
400        data: Option<Value>,
401    },
402    Protocol(String),
403    Timeout {
404        operation: String,
405        timeout: Duration,
406    },
407    Transport {
408        message: String,
409        stderr: Option<String>,
410    },
411    Io(std::io::Error),
412}
413
414impl From<McpConfigError> for McpError {
415    fn from(err: McpConfigError) -> Self {
416        Self::Config(err)
417    }
418}
419
420impl From<std::io::Error> for McpError {
421    fn from(err: std::io::Error) -> Self {
422        Self::Io(err)
423    }
424}
425
426impl fmt::Display for McpError {
427    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
428        match self {
429            Self::Config(e) => write!(f, "{e}"),
430            Self::UntrustedProjectServer { name, path } => write!(
431                f,
432                "refusing to run untrusted project MCP server '{name}' from {}; explicit user approval is required",
433                path.display()
434            ),
435            Self::NeedsAuth {
436                www_authenticate,
437                status,
438            } => match www_authenticate {
439                Some(header) => write!(f, "MCP server requires authentication (HTTP {status}; WWW-Authenticate: {header})"),
440                None => write!(f, "MCP server requires authentication (HTTP {status})"),
441            },
442            Self::HttpStatus { status, body } => {
443                if body.trim().is_empty() {
444                    write!(f, "MCP HTTP request failed with status {status}")
445                } else {
446                    write!(f, "MCP HTTP request failed with status {status}: {body}")
447                }
448            }
449            Self::Rpc {
450                code,
451                message,
452                data,
453            } => match data {
454                Some(d) => write!(f, "MCP JSON-RPC error {code}: {message} ({d})"),
455                None => write!(f, "MCP JSON-RPC error {code}: {message}"),
456            },
457            Self::Protocol(msg) => write!(f, "MCP protocol error: {msg}"),
458            Self::Timeout { operation, timeout } => {
459                write!(f, "MCP operation '{operation}' timed out after {}ms", timeout.as_millis())
460            }
461            Self::Transport { message, stderr } => match stderr {
462                Some(err) if !err.trim().is_empty() => {
463                    write!(f, "MCP transport error: {message} (stderr: {})", err.trim())
464                }
465                _ => write!(f, "MCP transport error: {message}"),
466            },
467            Self::Io(e) => write!(f, "MCP I/O error: {e}"),
468        }
469    }
470}
471
472impl std::error::Error for McpError {}