blyte 0.88.1

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
//! JSON-RPC 2.0 and Model Context Protocol data types and errors.

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;

/// MCP protocol version advertised by blyte during `initialize`.
pub const MCP_PROTOCOL_VERSION: &str = "2025-03-26";

/// JSON-RPC 2.0 version constant.
pub const JSONRPC_VERSION: &str = "2.0";

/// Client identity sent during `initialize`.
#[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(),
        }
    }
}

/// Result returned by the server from `initialize`.
#[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>,
}

/// Behavioral annotations advertised by an MCP tool.
#[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": {} })
}

/// Definition of a tool returned by `tools/list`.
#[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 {
    /// Returns true only when the server explicitly marked `annotations.readOnlyHint == true`.
    pub fn is_read_only(&self) -> bool {
        self.annotations
            .as_ref()
            .and_then(|a| a.read_only_hint)
            .unwrap_or(false)
    }
}

/// Single page returned by `tools/list`.
#[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>,
}

/// Embedded resource payload inside a `ContentBlock::Resource`.
#[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>,
}

/// Structured content block returned by `tools/call`.
#[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)),
        }
    }
}

/// Result returned by `tools/call`.
#[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 {
    /// Renders a plain-text representation of the returned content blocks.
    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")
    }
}

/// Outbound JSON-RPC 2.0 request envelope.
#[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>,
}

/// Outbound JSON-RPC 2.0 notification envelope (no `id`).
#[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>,
}

/// Inbound JSON-RPC 2.0 error object.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JsonRpcErrorObject {
    pub code: i64,
    pub message: String,
    #[serde(default)]
    pub data: Option<Value>,
}

/// Inbound JSON-RPC 2.0 response envelope.
#[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(),
            )
        })
    }
}

/// Errors returned by MCP transports and client operations.
#[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 {}