corrosive_agents 0.0.1

Build verifiable, interactive AI agents powered by NVIDIA Nemotron free LLM models — MCP, skills, Ed25519 identity, REST/WebSocket/gRPC transports, and pluggable vector stores (Pinecone, Qdrant, custom).
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
//! MCP client over stdio (JSON-RPC, newline-delimited) or streamable
//! HTTP/SSE.

use std::process::Stdio;
use std::sync::atomic::{AtomicI64, Ordering};

use serde_json::{json, Value};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStdin, ChildStdout, Command};
use tokio::sync::{Mutex, RwLock};

use crate::error::{Error, Result};
use crate::mcp::{McpPrompt, McpResource, McpServerConfig, McpTool};

const PROTOCOL_VERSION: &str = "2024-11-05";

struct McpIo {
    stdin: ChildStdin,
    stdout: BufReader<ChildStdout>,
}

enum Transport {
    Stdio {
        io: Mutex<McpIo>,
        // Boxed: tokio's Child is large, and Http must not pay for it
        // (clippy::large_enum_variant).
        child: Box<Mutex<Child>>,
    },
    Http {
        http: reqwest::Client,
        url: String,
        headers: std::collections::HashMap<String, String>,
        session_id: RwLock<Option<String>>,
    },
}

/// A connected MCP server (stdio child process or streamable-HTTP endpoint).
pub struct McpClient {
    name: String,
    transport: Transport,
    next_id: AtomicI64,
    server_info: Value,
}

impl std::fmt::Debug for McpClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("McpClient")
            .field("name", &self.name)
            .field(
                "transport",
                &match &self.transport {
                    Transport::Stdio { .. } => "stdio",
                    Transport::Http { .. } => "http",
                },
            )
            .field("server_info", &self.server_info)
            .finish_non_exhaustive()
    }
}

impl McpClient {
    /// Connect to the configured server (spawn + handshake for stdio, POST
    /// handshake for HTTP) and perform the MCP `initialize` exchange.
    pub async fn connect(config: &McpServerConfig) -> Result<Self> {
        let transport = if let Some(url) = &config.url {
            Transport::Http {
                http: reqwest::Client::new(),
                url: url.clone(),
                headers: config.headers.clone(),
                session_id: RwLock::new(None),
            }
        } else {
            if config.command.trim().is_empty() {
                return Err(Error::Mcp(format!(
                    "MCP server '{}' has neither a command nor a url",
                    config.name
                )));
            }
            let mut command = Command::new(&config.command);
            command
                .args(&config.args)
                .envs(&config.env)
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .stderr(Stdio::null())
                .kill_on_drop(true);

            let mut child = command
                .spawn()
                .map_err(|e| Error::Mcp(format!("failed to spawn '{}': {e}", config.command)))?;
            let stdin = child
                .stdin
                .take()
                .ok_or_else(|| Error::Mcp("child stdin unavailable".into()))?;
            let stdout = child
                .stdout
                .take()
                .ok_or_else(|| Error::Mcp("child stdout unavailable".into()))?;
            Transport::Stdio {
                io: Mutex::new(McpIo {
                    stdin,
                    stdout: BufReader::new(stdout),
                }),
                child: Box::new(Mutex::new(child)),
            }
        };

        let client = Self {
            name: config.name.clone(),
            transport,
            next_id: AtomicI64::new(1),
            server_info: Value::Null,
        };

        let init_result = client
            .request(
                "initialize",
                json!({
                    "protocolVersion": PROTOCOL_VERSION,
                    "capabilities": {},
                    "clientInfo": {
                        "name": "corrosive_agents",
                        "version": env!("CARGO_PKG_VERSION"),
                    },
                }),
            )
            .await?;
        client
            .notify("notifications/initialized", json!({}))
            .await?;

        Ok(Self {
            server_info: init_result,
            ..client
        })
    }

    /// The local name of this server (from its config).
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The server's `initialize` response (implementation name, version,
    /// capabilities).
    pub fn server_info(&self) -> &Value {
        &self.server_info
    }

    // ── Tools ────────────────────────────────────────────────────────────

    /// List the tools this server offers.
    pub async fn list_tools(&self) -> Result<Vec<McpTool>> {
        let result = self.request("tools/list", json!({})).await?;
        let tools = result
            .get("tools")
            .cloned()
            .ok_or_else(|| Error::Mcp("tools/list response missing 'tools'".into()))?;
        Ok(serde_json::from_value(tools)?)
    }

    /// Invoke a tool by name with JSON arguments and return its result
    /// content.
    pub async fn call_tool(&self, tool: &str, arguments: Value) -> Result<Value> {
        let result = self
            .request(
                "tools/call",
                json!({ "name": tool, "arguments": arguments }),
            )
            .await?;
        if result
            .get("isError")
            .and_then(Value::as_bool)
            .unwrap_or(false)
        {
            return Err(Error::Mcp(format!(
                "tool '{tool}' reported an error: {result}"
            )));
        }
        Ok(result.get("content").cloned().unwrap_or(result))
    }

    // ── Resources ────────────────────────────────────────────────────────

    /// List the resources this server offers.
    pub async fn list_resources(&self) -> Result<Vec<McpResource>> {
        let result = self.request("resources/list", json!({})).await?;
        let resources = result
            .get("resources")
            .cloned()
            .ok_or_else(|| Error::Mcp("resources/list response missing 'resources'".into()))?;
        Ok(serde_json::from_value(resources)?)
    }

    /// Read a resource by URI; returns the `contents` array (text or blob
    /// entries).
    pub async fn read_resource(&self, uri: &str) -> Result<Value> {
        let result = self
            .request("resources/read", json!({ "uri": uri }))
            .await?;
        Ok(result.get("contents").cloned().unwrap_or(result))
    }

    // ── Prompts ──────────────────────────────────────────────────────────

    /// List the prompt templates this server offers.
    pub async fn list_prompts(&self) -> Result<Vec<McpPrompt>> {
        let result = self.request("prompts/list", json!({})).await?;
        let prompts = result
            .get("prompts")
            .cloned()
            .ok_or_else(|| Error::Mcp("prompts/list response missing 'prompts'".into()))?;
        Ok(serde_json::from_value(prompts)?)
    }

    /// Expand a prompt template with arguments; returns the rendered
    /// `messages` array.
    pub async fn get_prompt(&self, name: &str, arguments: Value) -> Result<Value> {
        let result = self
            .request(
                "prompts/get",
                json!({ "name": name, "arguments": arguments }),
            )
            .await?;
        Ok(result.get("messages").cloned().unwrap_or(result))
    }

    /// Terminate the connection (kills the child process for stdio; ends the
    /// HTTP session best-effort).
    pub async fn shutdown(&self) -> Result<()> {
        match &self.transport {
            Transport::Stdio { child, .. } => {
                let mut child = child.lock().await;
                child
                    .kill()
                    .await
                    .map_err(|e| Error::Mcp(format!("failed to kill server: {e}")))
            }
            Transport::Http {
                http,
                url,
                headers,
                session_id,
            } => {
                if let Some(sid) = session_id.read().await.clone() {
                    let mut request = http.delete(url).header("Mcp-Session-Id", sid);
                    for (name, value) in headers {
                        request = request.header(name, value);
                    }
                    let _ = request.send().await; // best-effort per spec
                }
                Ok(())
            }
        }
    }

    // ── JSON-RPC plumbing ────────────────────────────────────────────────

    async fn notify(&self, method: &str, params: Value) -> Result<()> {
        let message = json!({ "jsonrpc": "2.0", "method": method, "params": params });
        match &self.transport {
            Transport::Stdio { io, .. } => {
                let mut io = io.lock().await;
                Self::write_message(&mut io.stdin, &message).await
            }
            Transport::Http { .. } => {
                // Notifications over HTTP get a 202 with no body.
                self.http_post(&message, None).await.map(|_| ())
            }
        }
    }

    async fn request(&self, method: &str, params: Value) -> Result<Value> {
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        let message = json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params });

        let value = match &self.transport {
            Transport::Stdio { io, .. } => {
                let mut io = io.lock().await;
                Self::write_message(&mut io.stdin, &message).await?;
                Self::read_response_stdio(&mut io.stdout, id, method, &self.name).await?
            }
            Transport::Http { .. } => self
                .http_post(&message, Some(id))
                .await?
                .ok_or_else(|| Error::Mcp(format!("'{method}' returned no response")))?,
        };

        if let Some(error) = value.get("error") {
            return Err(Error::Mcp(format!("'{method}' failed: {error}")));
        }
        Ok(value.get("result").cloned().unwrap_or(Value::Null))
    }

    /// POST one JSON-RPC message over the streamable-HTTP transport. Returns
    /// the matching response envelope (or `None` for notifications).
    async fn http_post(&self, message: &Value, expect_id: Option<i64>) -> Result<Option<Value>> {
        let Transport::Http {
            http,
            url,
            headers,
            session_id,
        } = &self.transport
        else {
            unreachable!("http_post called on stdio transport");
        };

        let mut request = http
            .post(url)
            .header("Content-Type", "application/json")
            .header("Accept", "application/json, text/event-stream")
            .json(message);
        for (name, value) in headers {
            request = request.header(name, value);
        }
        if let Some(sid) = session_id.read().await.clone() {
            request = request.header("Mcp-Session-Id", sid);
        }

        let response = request
            .send()
            .await
            .map_err(|e| Error::Mcp(format!("HTTP request to '{}' failed: {e}", self.name)))?;

        let status = response.status();
        // The server assigns a session id on initialize; echo it afterwards.
        if let Some(sid) = response
            .headers()
            .get("mcp-session-id")
            .and_then(|v| v.to_str().ok())
        {
            *session_id.write().await = Some(sid.to_string());
        }
        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(Error::Mcp(format!(
                "server '{}' returned {status}: {body}",
                self.name
            )));
        }
        let Some(expect_id) = expect_id else {
            return Ok(None); // notification — 202/200 with ignorable body
        };

        let content_type = response
            .headers()
            .get(reqwest::header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("")
            .to_string();
        let body = response
            .text()
            .await
            .map_err(|e| Error::Mcp(format!("failed to read response body: {e}")))?;

        if content_type.starts_with("text/event-stream") {
            // Scan SSE events for the JSON-RPC response with our id.
            for line in body.lines() {
                let Some(data) = line.trim().strip_prefix("data:") else {
                    continue;
                };
                let Ok(value) = serde_json::from_str::<Value>(data.trim()) else {
                    continue;
                };
                if value.get("id").and_then(Value::as_i64) == Some(expect_id) {
                    return Ok(Some(value));
                }
            }
            Err(Error::Mcp(format!(
                "SSE stream from '{}' ended without a response for id {expect_id}",
                self.name
            )))
        } else {
            let value: Value = serde_json::from_str(&body)
                .map_err(|e| Error::Mcp(format!("invalid JSON from '{}': {e}", self.name)))?;
            Ok(Some(value))
        }
    }

    async fn read_response_stdio(
        stdout: &mut BufReader<ChildStdout>,
        id: i64,
        method: &str,
        name: &str,
    ) -> Result<Value> {
        // Read newline-delimited JSON until our response id shows up,
        // skipping notifications and unrelated messages.
        let mut line = String::new();
        loop {
            line.clear();
            let read = stdout
                .read_line(&mut line)
                .await
                .map_err(|e| Error::Mcp(format!("read from server failed: {e}")))?;
            if read == 0 {
                return Err(Error::Mcp(format!(
                    "server '{name}' closed the connection during '{method}'"
                )));
            }
            let trimmed = line.trim();
            if trimmed.is_empty() {
                continue;
            }
            let Ok(value) = serde_json::from_str::<Value>(trimmed) else {
                continue;
            };
            if value.get("id").and_then(Value::as_i64) != Some(id) {
                continue;
            }
            return Ok(value);
        }
    }

    async fn write_message(stdin: &mut ChildStdin, message: &Value) -> Result<()> {
        let mut payload = serde_json::to_vec(message)?;
        payload.push(b'\n');
        stdin
            .write_all(&payload)
            .await
            .map_err(|e| Error::Mcp(format!("write to server failed: {e}")))?;
        stdin
            .flush()
            .await
            .map_err(|e| Error::Mcp(format!("flush to server failed: {e}")))
    }
}