yoagent 0.26.0

The agent loop for Rust: stream from 7 LLM protocols, run tools, loop until done. Native or wasm32 (Cloudflare Workers).
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
//! MCP (Model Context Protocol) JSON-RPC 2.0 types.

use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicU64, Ordering};

static REQUEST_ID_COUNTER: AtomicU64 = AtomicU64::new(1);

/// Generate a unique JSON-RPC request ID.
pub fn next_request_id() -> u64 {
    REQUEST_ID_COUNTER.fetch_add(1, Ordering::Relaxed)
}

// ---------------------------------------------------------------------------
// JSON-RPC 2.0
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcRequest {
    pub jsonrpc: String,
    pub id: u64,
    pub method: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub params: Option<serde_json::Value>,
}

impl JsonRpcRequest {
    pub fn new(method: impl Into<String>, params: Option<serde_json::Value>) -> Self {
        Self {
            jsonrpc: "2.0".into(),
            id: next_request_id(),
            method: method.into(),
            params,
        }
    }
}

/// A JSON-RPC notification: no `id`, and no response is expected (or sent).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcNotification {
    pub jsonrpc: String,
    pub method: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub params: Option<serde_json::Value>,
}

impl JsonRpcNotification {
    pub fn new(method: impl Into<String>, params: Option<serde_json::Value>) -> Self {
        Self {
            jsonrpc: "2.0".into(),
            method: method.into(),
            params,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcResponse {
    pub jsonrpc: String,
    pub id: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<JsonRpcError>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcError {
    pub code: i64,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,
}

// ---------------------------------------------------------------------------
// MCP Protocol types
// ---------------------------------------------------------------------------

/// Client info sent during initialization.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClientInfo {
    pub name: String,
    pub version: String,
}

impl Default for ClientInfo {
    fn default() -> Self {
        Self {
            name: "yoagent".into(),
            version: env!("CARGO_PKG_VERSION").into(),
        }
    }
}

/// Server info received during initialization.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ServerInfo {
    pub name: String,
    #[serde(default)]
    pub version: String,
}

/// Server capabilities received during initialization.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ServerCapabilities {
    #[serde(default)]
    pub tools: Option<serde_json::Value>,
    #[serde(default)]
    pub resources: Option<serde_json::Value>,
    #[serde(default)]
    pub prompts: Option<serde_json::Value>,
}

/// Initialize result from the server.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InitializeResult {
    pub protocol_version: String,
    pub capabilities: ServerCapabilities,
    pub server_info: ServerInfo,
}

/// MCP tool as returned by tools/list.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct McpToolInfo {
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub input_schema: serde_json::Value,
}

/// tools/list result.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolsListResult {
    pub tools: Vec<McpToolInfo>,
}

/// Content item in a tool call result.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum McpContent {
    #[serde(rename = "text")]
    Text { text: String },
    #[serde(rename = "image")]
    Image {
        data: String,
        #[serde(rename = "mimeType")]
        mime_type: String,
    },
}

/// tools/call result.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct McpToolCallResult {
    /// Content kinds this crate does not model (`resource`, `resource_link`,
    /// `audio`, anything newer) arrive as [`McpContent::Text`] holding the
    /// block's JSON, rather than failing the whole call.
    #[serde(deserialize_with = "lenient_content")]
    pub content: Vec<McpContent>,
    #[serde(default)]
    pub is_error: bool,
}

/// Read each content block, keeping one this crate does not model as text
/// the model can use: a `resource`'s own text, or the block's JSON with any
/// large `data` / `blob` payload replaced by its size (base64 audio would
/// otherwise go into the context verbatim).
fn lenient_content<'de, D>(deserializer: D) -> Result<Vec<McpContent>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let blocks = Vec::<serde_json::Value>::deserialize(deserializer)?;
    Ok(blocks
        .into_iter()
        .map(
            |block| match serde_json::from_value::<McpContent>(block.clone()) {
                Ok(content) => content,
                Err(e) => {
                    let kind = block
                        .get("type")
                        .and_then(|t| t.as_str())
                        .unwrap_or("(none)")
                        .to_string();
                    warn_unmodelled(&kind, &e);
                    McpContent::Text {
                        text: unmodelled_text(block),
                    }
                }
            },
        )
        .collect())
}

/// Warn once per content type that had to be passed through as text.
fn warn_unmodelled(kind: &str, error: &serde_json::Error) {
    use std::collections::HashSet;
    use std::sync::{Mutex, OnceLock};
    static SEEN: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
    let first = SEEN
        .get_or_init(|| Mutex::new(HashSet::new()))
        .lock()
        .map(|mut seen| seen.insert(kind.to_string()))
        .unwrap_or(true);
    if first {
        tracing::warn!(
            "MCP content of type '{kind}' is not modelled ({error}); passing it to the model as text"
        );
    }
}

/// Payloads longer than this are replaced by a note of their size.
const MAX_INLINE_PAYLOAD: usize = 1024;

fn unmodelled_text(mut block: serde_json::Value) -> String {
    // A text resource: its own text is what the model wants.
    if let Some(resource) = block.get("resource") {
        if let Some(text) = resource.get("text").and_then(|t| t.as_str()) {
            let uri = resource.get("uri").and_then(|u| u.as_str()).unwrap_or("");
            return format!("[resource {uri}]\n{text}");
        }
    }
    shrink_payloads(&mut block);
    block.to_string()
}

fn shrink_payloads(value: &mut serde_json::Value) {
    match value {
        serde_json::Value::Object(map) => {
            for (key, v) in map.iter_mut() {
                match v {
                    serde_json::Value::String(s)
                        if (key == "data" || key == "blob") && s.len() > MAX_INLINE_PAYLOAD =>
                    {
                        *v = serde_json::Value::String(format!(
                            "[{} bytes of base64 omitted]",
                            s.len()
                        ));
                    }
                    other => shrink_payloads(other),
                }
            }
        }
        serde_json::Value::Array(items) => items.iter_mut().for_each(shrink_payloads),
        _ => {}
    }
}

// ---------------------------------------------------------------------------
// MCP Error
// ---------------------------------------------------------------------------

/// What went wrong talking to an MCP server. `#[non_exhaustive]`: match
/// with a wildcard arm.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum McpError {
    #[error("Transport error: {0}")]
    Transport(String),
    /// The server answered with a non-success HTTP status (the HTTP
    /// transport). `status` is its code: 401 or 403, it wants a credential or
    /// a sign-in; 404, the session expired when one was held (a call's
    /// message says so), else most likely a wrong URL. `message` is the whole report
    /// as a `Transport` error read before — the server's body (first 200
    /// chars) included when there was one.
    ///
    /// `#[non_exhaustive]`: match with `Http { status, .. }` and build one
    /// with [`McpError::http`], so fields can be added (a 401's
    /// `WWW-Authenticate`, say) without a breaking change.
    #[error("Transport error: {message}")]
    #[non_exhaustive]
    Http { status: u16, message: String },
    #[error("Protocol error: {0}")]
    Protocol(String),
    #[error("JSON-RPC error {code}: {message}")]
    JsonRpc { code: i64, message: String },
    #[error("Serialization error: {0}")]
    Serialization(#[from] serde_json::Error),
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    #[error("Connection closed")]
    ConnectionClosed,
}

impl McpError {
    /// An [`Http`](Self::Http) error, for a custom [`McpTransport`](super::McpTransport)
    /// reporting a non-success HTTP status.
    pub fn http(status: u16, message: impl Into<String>) -> Self {
        Self::Http {
            status,
            message: message.into(),
        }
    }

    /// The HTTP status of an [`Http`](Self::Http) error; `None` for any other.
    pub fn http_status(&self) -> Option<u16> {
        match self {
            Self::Http { status, .. } => Some(*status),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn http_errors_carry_their_status() {
        let err = McpError::http(401, "HTTP 401 Unauthorized from server on 'tools/list'");
        assert_eq!(err.http_status(), Some(401));
        assert_eq!(
            err.to_string(),
            "Transport error: HTTP 401 Unauthorized from server on 'tools/list'"
        );
        assert_eq!(McpError::Transport("x".into()).http_status(), None);
    }

    #[test]
    fn test_json_rpc_request_serialization() {
        let req = JsonRpcRequest {
            jsonrpc: "2.0".into(),
            id: 1,
            method: "initialize".into(),
            params: Some(serde_json::json!({"protocolVersion": "2024-11-05"})),
        };
        let json = serde_json::to_string(&req).unwrap();
        assert!(json.contains("\"jsonrpc\":\"2.0\""));
        assert!(json.contains("\"method\":\"initialize\""));

        let parsed: JsonRpcRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.id, 1);
        assert_eq!(parsed.method, "initialize");
    }

    #[test]
    fn test_json_rpc_response_deserialization() {
        let json = r#"{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2024-11-05","capabilities":{},"serverInfo":{"name":"test","version":"1.0"}}}"#;
        let resp: JsonRpcResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.id, Some(1));
        assert!(resp.result.is_some());
        assert!(resp.error.is_none());
    }

    #[test]
    fn test_json_rpc_error_response() {
        let json =
            r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32601,"message":"Method not found"}}"#;
        let resp: JsonRpcResponse = serde_json::from_str(json).unwrap();
        assert!(resp.error.is_some());
        let err = resp.error.unwrap();
        assert_eq!(err.code, -32601);
    }

    #[test]
    fn test_initialize_result_deserialization() {
        let json = r#"{"protocolVersion":"2024-11-05","capabilities":{"tools":{}},"serverInfo":{"name":"test-server","version":"0.1.0"}}"#;
        let result: InitializeResult = serde_json::from_str(json).unwrap();
        assert_eq!(result.server_info.name, "test-server");
        assert!(result.capabilities.tools.is_some());
    }

    #[test]
    fn test_mcp_tool_info_deserialization() {
        let json = r#"{"name":"read_file","description":"Read a file","inputSchema":{"type":"object","properties":{"path":{"type":"string"}}}}"#;
        let tool: McpToolInfo = serde_json::from_str(json).unwrap();
        assert_eq!(tool.name, "read_file");
        assert_eq!(tool.description.as_deref(), Some("Read a file"));
    }

    #[test]
    fn test_mcp_tool_call_result() {
        let json = r#"{"content":[{"type":"text","text":"file contents here"}],"isError":false}"#;
        let result: McpToolCallResult = serde_json::from_str(json).unwrap();
        assert_eq!(result.content.len(), 1);
        assert!(!result.is_error);
    }

    #[test]
    fn unknown_content_blocks_are_kept_as_json_text() {
        let json = r#"{"content":[
            {"type":"text","text":"hi"},
            {"type":"resource","resource":{"uri":"file:///a.txt","text":"body"}},
            {"type":"audio","data":"AAAA","mimeType":"audio/wav"}
        ]}"#;
        let result: McpToolCallResult = serde_json::from_str(json).unwrap();
        assert_eq!(result.content.len(), 3);
        assert!(matches!(&result.content[0], McpContent::Text { text } if text == "hi"));
        assert!(
            matches!(&result.content[1], McpContent::Text { text } if text == "[resource file:///a.txt]\nbody")
        );
        assert!(matches!(&result.content[2], McpContent::Text { text } if text.contains("audio")));
    }

    #[test]
    fn large_unmodelled_payloads_are_replaced_by_their_size() {
        let blob = "A".repeat(5000);
        let json = format!(
            r#"{{"content":[{{"type":"audio","data":"{blob}","mimeType":"audio/wav"}},{{"type":"resource","resource":{{"uri":"file:///b.bin","blob":"{blob}"}}}}]}}"#
        );
        let result: McpToolCallResult = serde_json::from_str(&json).unwrap();
        for content in &result.content {
            let McpContent::Text { text } = content else {
                panic!("expected text")
            };
            assert!(text.contains("[5000 bytes of base64 omitted]"), "{text}");
            assert!(text.len() < 500, "{} bytes kept", text.len());
        }
    }

    #[test]
    fn a_notification_has_no_id() {
        let json =
            serde_json::to_string(&JsonRpcNotification::new("notifications/initialized", None))
                .unwrap();
        assert_eq!(
            json,
            r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#
        );
    }

    #[test]
    fn test_unique_request_ids() {
        let id1 = next_request_id();
        let id2 = next_request_id();
        assert_ne!(id1, id2);
    }
}