Skip to main content

active_rpc/
tool.rs

1//! Tool handles: MCP sessions, HTTP/OpenAPI endpoints, local processes.
2//!
3//! Tools are capabilities like everything else, which means a tool handle
4//! inherits the same guarantees: no ambient authority, attenuation-only
5//! narrowing, budget accounting and drop notification.
6//!
7//! | Adapter | What it talks to |
8//! |---------|------------------|
9//! | [`McpSession`] | an MCP server, over an injected line transport (stdio or in-memory) |
10//! | [`HttpTool`] | an HTTP endpoint restricted to an allowlist of `METHOD path` pairs |
11//! | [`LocalProcess`] | a sandboxed child process: allowlisted program, no shell, scrubbed environment |
12//!
13//! Every adapter returns a [`Response::Value`] built from JSON, never a raw
14//! string dump, and every adapter refuses a call outside its policy with
15//! `rpc/tool-policy`.
16
17use std::collections::{BTreeMap, BTreeSet};
18use std::io::{BufRead, BufReader, Read, Write};
19use std::net::TcpStream;
20use std::process::{Child, Command, Stdio};
21
22use serde_json::{json, Value as Json};
23
24use crate::cap::ToolPolicy;
25use crate::error::{Error, Result};
26use crate::kernel::Provider;
27use crate::value::Response;
28use crate::value::{Arg, Call, Value};
29
30/// Convert JSON into an RPC value.
31pub fn json_to_value(value: &Json) -> Value {
32    match value {
33        Json::Null => Value::Null,
34        Json::Bool(flag) => Value::Bool(*flag),
35        Json::Number(number) => {
36            if let Some(int) = number.as_i64() {
37                Value::Int(int)
38            } else {
39                Value::Float(number.as_f64().unwrap_or(0.0))
40            }
41        }
42        Json::String(text) => Value::Text(text.clone()),
43        Json::Array(items) => Value::List(items.iter().map(json_to_value).collect()),
44        Json::Object(entries) => Value::Map(
45            entries
46                .iter()
47                .map(|(key, value)| (key.clone(), json_to_value(value)))
48                .collect(),
49        ),
50    }
51}
52
53/// Convert an RPC value into JSON.
54pub fn value_to_json(value: &Value) -> Json {
55    match value {
56        Value::Null => Json::Null,
57        Value::Bool(flag) => Json::Bool(*flag),
58        Value::Int(number) => json!(number),
59        Value::Float(number) => json!(number),
60        Value::Text(text) => Json::String(text.clone()),
61        Value::List(items) => Json::Array(items.iter().map(value_to_json).collect()),
62        Value::Map(entries) => Json::Object(
63            entries
64                .iter()
65                .map(|(key, value)| (key.clone(), value_to_json(value)))
66                .collect(),
67        ),
68        Value::Secret => Json::String("***SECRET***".to_string()),
69        Value::Module(bytes) => json!({ "$module_bytes": bytes.len() }),
70        Value::Path(path) => Json::String(path.clone()),
71    }
72}
73
74// ---------------------------------------------------------------------------
75// MCP
76// ---------------------------------------------------------------------------
77
78/// A line-oriented JSON-RPC transport used by [`McpSession`].
79pub trait McpTransport {
80    /// Send one JSON line.
81    fn send_line(&mut self, line: &str) -> Result<()>;
82    /// Read one JSON line (blocking).
83    fn recv_line(&mut self) -> Result<String>;
84}
85
86/// An in-memory transport: requests are answered by a closure.
87pub struct MemoryTransport {
88    responses: BTreeMap<String, String>,
89    queue: Vec<String>,
90    sent: Vec<String>,
91}
92
93impl MemoryTransport {
94    /// Build from `method -> response` pairs.
95    pub fn new(responses: BTreeMap<String, String>) -> Self {
96        Self {
97            responses,
98            queue: Vec::new(),
99            sent: Vec::new(),
100        }
101    }
102
103    /// Lines sent by the client (tests).
104    pub fn sent(&self) -> &[String] {
105        &self.sent
106    }
107}
108
109impl McpTransport for MemoryTransport {
110    fn send_line(&mut self, line: &str) -> Result<()> {
111        self.sent.push(line.to_string());
112        let request: Json = serde_json::from_str(line).map_err(|_| Error::Provider {
113            code: "mcp/bad-json".to_string(),
114        })?;
115        let method = request.get("method").and_then(Json::as_str).unwrap_or("");
116        let id = request.get("id").cloned().unwrap_or(Json::Null);
117        let response = self.responses.get(method).cloned().unwrap_or_else(|| {
118            json!({
119                "jsonrpc": "2.0",
120                "id": id,
121                "error": { "code": -32601, "message": "method not found" }
122            })
123            .to_string()
124        });
125        self.queue.push(response);
126        Ok(())
127    }
128
129    fn recv_line(&mut self) -> Result<String> {
130        if self.queue.is_empty() {
131            return Err(Error::Provider {
132                code: "mcp/no-response".to_string(),
133            });
134        }
135        Ok(self.queue.remove(0))
136    }
137}
138
139/// A child-process MCP transport speaking JSON-RPC over stdin/stdout.
140pub struct StdioTransport {
141    child: Child,
142    stdin: std::process::ChildStdin,
143    stdout: BufReader<std::process::ChildStdout>,
144}
145
146impl StdioTransport {
147    /// Spawn an MCP server process (no shell, no inherited environment beyond
148    /// what the caller passes).
149    pub fn spawn(program: &str, args: &[&str], env: &BTreeMap<String, String>) -> Result<Self> {
150        let mut command = Command::new(program);
151        command
152            .args(args)
153            .stdin(Stdio::piped())
154            .stdout(Stdio::piped())
155            .stderr(Stdio::null())
156            .env_clear();
157        for (key, value) in env {
158            command.env(key, value);
159        }
160        let mut child = command.spawn().map_err(|error| Error::Provider {
161            code: format!("mcp/spawn:{error}"),
162        })?;
163        let stdin = child.stdin.take().ok_or(Error::Provider {
164            code: "mcp/stdin".to_string(),
165        })?;
166        let stdout = child.stdout.take().ok_or(Error::Provider {
167            code: "mcp/stdout".to_string(),
168        })?;
169        Ok(Self {
170            child,
171            stdin,
172            stdout: BufReader::new(stdout),
173        })
174    }
175}
176
177impl McpTransport for StdioTransport {
178    fn send_line(&mut self, line: &str) -> Result<()> {
179        self.stdin
180            .write_all(line.as_bytes())
181            .and_then(|_| self.stdin.write_all(b"\n"))
182            .and_then(|_| self.stdin.flush())
183            .map_err(|error| Error::Provider {
184                code: format!("mcp/write:{error}"),
185            })
186    }
187
188    fn recv_line(&mut self) -> Result<String> {
189        let mut line = String::new();
190        let read = self
191            .stdout
192            .read_line(&mut line)
193            .map_err(|error| Error::Provider {
194                code: format!("mcp/read:{error}"),
195            })?;
196        if read == 0 {
197            return Err(Error::Provider {
198                code: "mcp/eof".to_string(),
199            });
200        }
201        Ok(line.trim_end().to_string())
202    }
203}
204
205impl Drop for StdioTransport {
206    fn drop(&mut self) {
207        let _ = self.child.kill();
208        let _ = self.child.wait();
209    }
210}
211
212/// One tool exposed by an MCP server.
213#[derive(Debug, Clone, PartialEq, Eq)]
214pub struct McpToolDef {
215    /// Tool name.
216    pub name: String,
217    /// Free-form description.
218    pub description: String,
219}
220
221/// A provider backed by an MCP session.
222///
223/// `object` selects the tool index; `method` is the tool name. The session
224/// performs the real JSON-RPC handshake (`initialize`, `tools/list`) and then
225/// `tools/call` per invocation.
226pub struct McpSession<T: McpTransport> {
227    transport: T,
228    tools: Vec<McpToolDef>,
229    next_id: u64,
230    /// Calls issued through this session.
231    pub calls: u64,
232}
233
234impl<T: McpTransport> McpSession<T> {
235    /// Perform the MCP handshake and discover tools.
236    pub fn handshake(transport: T) -> Result<Self> {
237        let mut session = McpSession {
238            transport,
239            tools: Vec::new(),
240            next_id: 0,
241            calls: 0,
242        };
243        let initialize = session.request(
244            "initialize",
245            json!({
246                "protocolVersion": "2025-06-18",
247                "capabilities": {},
248                "clientInfo": { "name": "active-rpc", "version": env!("CARGO_PKG_VERSION") }
249            }),
250        )?;
251        if initialize.get("error").is_some() {
252            return Err(Error::Provider {
253                code: "mcp/initialize".to_string(),
254            });
255        }
256        let list = session.request("tools/list", json!({}))?;
257        if let Some(items) = list
258            .get("result")
259            .and_then(|result| result.get("tools"))
260            .and_then(Json::as_array)
261        {
262            for item in items {
263                let name = item.get("name").and_then(Json::as_str).unwrap_or("");
264                if name.is_empty() {
265                    continue;
266                }
267                session.tools.push(McpToolDef {
268                    name: name.to_string(),
269                    description: item
270                        .get("description")
271                        .and_then(Json::as_str)
272                        .unwrap_or("")
273                        .to_string(),
274                });
275            }
276        }
277        Ok(session)
278    }
279
280    fn request(&mut self, method: &str, params: Json) -> Result<Json> {
281        self.next_id += 1;
282        let payload = json!({
283            "jsonrpc": "2.0",
284            "id": self.next_id,
285            "method": method,
286            "params": params,
287        });
288        self.transport.send_line(&payload.to_string())?;
289        let line = self.transport.recv_line()?;
290        serde_json::from_str(&line).map_err(|_| Error::Provider {
291            code: "mcp/bad-response".to_string(),
292        })
293    }
294
295    /// Discovered tools.
296    pub fn tools(&self) -> &[McpToolDef] {
297        &self.tools
298    }
299
300    /// A policy allowing exactly the discovered tools.
301    pub fn policy(&self) -> ToolPolicy {
302        let mut policy = ToolPolicy::default();
303        for tool in &self.tools {
304            policy.allowed.insert(tool.name.clone());
305        }
306        policy.max_arg_bytes = 1 << 20;
307        policy
308    }
309}
310
311impl<T: McpTransport> Provider for McpSession<T> {
312    fn name(&self) -> &'static str {
313        "mcp"
314    }
315
316    fn methods(&self) -> Vec<String> {
317        self.tools.iter().map(|tool| tool.name.clone()).collect()
318    }
319
320    fn mutating(&self, _method: &str) -> bool {
321        true
322    }
323
324    fn invoke(&mut self, object: u64, call: &Call) -> Result<Response> {
325        self.calls += 1;
326        let tool = self
327            .tools
328            .get(object as usize)
329            .ok_or(Error::InvalidArgument("unknown MCP tool"))?;
330        if tool.name != call.method {
331            return Err(Error::MethodNotGranted {
332                method: call.method.clone(),
333            });
334        }
335        let mut arguments = serde_json::Map::new();
336        for (index, arg) in call.args.iter().enumerate() {
337            if let Arg::Value(value) = arg {
338                arguments.insert(format!("arg{index}"), value_to_json(value));
339            }
340        }
341        let response = self.request(
342            "tools/call",
343            json!({ "name": tool.name, "arguments": Json::Object(arguments) }),
344        )?;
345        if let Some(error) = response.get("error") {
346            return Err(Error::Provider {
347                code: format!(
348                    "mcp/{}",
349                    error.get("code").and_then(Json::as_i64).unwrap_or(0)
350                ),
351            });
352        }
353        let result = response.get("result").cloned().unwrap_or(Json::Null);
354        Ok(Response::Value(json_to_value(&result)))
355    }
356}
357
358// ---------------------------------------------------------------------------
359// HTTP / OpenAPI
360// ---------------------------------------------------------------------------
361
362/// An HTTP endpoint restricted to an allowlist.
363///
364/// The allowlist is `(METHOD, path)` pairs. There is no redirect following, no
365/// chunked encoding, and the body is bounded by `max_body`. A URL outside the
366/// allowlist is `rpc/tool-policy`.
367#[derive(Debug)]
368pub struct HttpTool {
369    /// Base URL, e.g. `http://127.0.0.1:8080`.
370    pub base: String,
371    /// Allowed `(method, path)` pairs.
372    pub allow: BTreeSet<(String, String)>,
373    /// Maximum response bytes.
374    pub max_body: usize,
375    /// Maximum request bytes.
376    pub max_request: usize,
377    /// Calls served.
378    pub calls: u64,
379}
380
381impl HttpTool {
382    /// Build a tool for `base` with an allowlist.
383    pub fn new(base: impl Into<String>, allow: &[(&str, &str)]) -> Self {
384        Self {
385            base: base.into(),
386            allow: allow
387                .iter()
388                .map(|(method, path)| (method.to_string(), path.to_string()))
389                .collect(),
390            max_body: 1 << 20,
391            max_request: 1 << 20,
392            calls: 0,
393        }
394    }
395
396    /// Build a tool policy for a capability.
397    pub fn policy(&self) -> ToolPolicy {
398        ToolPolicy {
399            allowed: ["get", "post", "request"]
400                .iter()
401                .map(|method| method.to_string())
402                .collect(),
403            max_arg_bytes: self.max_request as u64,
404            allow_process: false,
405        }
406    }
407
408    fn perform(&self, method: &str, path: &str, body: &[u8]) -> Result<(u16, Vec<u8>)> {
409        let base = self
410            .base
411            .strip_prefix("http://")
412            .ok_or(Error::ToolPolicy("only http:// endpoints are supported"))?;
413        let mut stream = TcpStream::connect(base).map_err(|error| Error::Provider {
414            code: format!("http/connect:{error}"),
415        })?;
416        stream
417            .set_read_timeout(Some(std::time::Duration::from_secs(10)))
418            .ok();
419        let head = format!(
420            "{method} {path} HTTP/1.1\r\nhost: {base}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
421            body.len()
422        );
423        stream
424            .write_all(head.as_bytes())
425            .and_then(|_| stream.write_all(body))
426            .and_then(|_| stream.flush())
427            .map_err(|error| Error::Provider {
428                code: format!("http/write:{error}"),
429            })?;
430        let mut reader = BufReader::new(stream);
431        let mut status_line = String::new();
432        reader
433            .read_line(&mut status_line)
434            .map_err(|error| Error::Provider {
435                code: format!("http/read:{error}"),
436            })?;
437        let status: u16 = status_line
438            .split_whitespace()
439            .nth(1)
440            .and_then(|code| code.parse().ok())
441            .ok_or(Error::Provider {
442                code: "http/status".to_string(),
443            })?;
444        let mut content_length: Option<usize> = None;
445        loop {
446            let mut line = String::new();
447            let read = reader
448                .read_line(&mut line)
449                .map_err(|error| Error::Provider {
450                    code: format!("http/read:{error}"),
451                })?;
452            if read == 0 || line.trim().is_empty() {
453                break;
454            }
455            if let Some((name, value)) = line.split_once(':') {
456                if name.eq_ignore_ascii_case("content-length") {
457                    content_length = value.trim().parse().ok();
458                }
459            }
460        }
461        let mut body = Vec::new();
462        match content_length {
463            Some(length) => {
464                if length > self.max_body {
465                    return Err(Error::ToolPolicy("response too large"));
466                }
467                body.resize(length, 0);
468                reader
469                    .read_exact(&mut body)
470                    .map_err(|error| Error::Provider {
471                        code: format!("http/body:{error}"),
472                    })?;
473            }
474            None => {
475                let mut rest = Vec::new();
476                reader
477                    .take(self.max_body as u64 + 1)
478                    .read_to_end(&mut rest)
479                    .map_err(|error| Error::Provider {
480                        code: format!("http/body:{error}"),
481                    })?;
482                if rest.len() > self.max_body {
483                    return Err(Error::ToolPolicy("response too large"));
484                }
485                body = rest;
486            }
487        }
488        Ok((status, body))
489    }
490}
491
492impl Provider for HttpTool {
493    fn name(&self) -> &'static str {
494        "http"
495    }
496
497    fn methods(&self) -> Vec<String> {
498        ["get", "post", "request"]
499            .iter()
500            .map(|method| method.to_string())
501            .collect()
502    }
503
504    fn mutating(&self, method: &str) -> bool {
505        method != "get"
506    }
507
508    fn invoke(&mut self, _object: u64, call: &Call) -> Result<Response> {
509        self.calls += 1;
510        let method: String = match call.method.as_str() {
511            "get" => "GET".to_string(),
512            "post" => "POST".to_string(),
513            "request" => call
514                .args
515                .iter()
516                .find_map(|arg| match arg {
517                    Arg::Value(Value::Text(text)) => Some(text.to_uppercase()),
518                    _ => None,
519                })
520                .unwrap_or_else(|| "GET".to_string()),
521            other => {
522                return Err(Error::MethodNotGranted {
523                    method: other.to_string(),
524                })
525            }
526        };
527        let path = call
528            .args
529            .iter()
530            .find_map(|arg| match arg {
531                Arg::Value(Value::Text(text)) if text.starts_with('/') => Some(text.clone()),
532                Arg::Value(Value::Path(path)) => Some(path.clone()),
533                _ => None,
534            })
535            .ok_or(Error::InvalidArgument("an HTTP path argument is required"))?;
536        if !self.allow.contains(&(method.to_string(), path.clone())) {
537            return Err(Error::ToolPolicy("path is not on the allowlist"));
538        }
539        let body = serde_json::to_vec(
540            &call
541                .args
542                .iter()
543                .filter_map(|arg| match arg {
544                    Arg::Value(Value::Map(entries)) => {
545                        Some(value_to_json(&Value::Map(entries.clone())))
546                    }
547                    _ => None,
548                })
549                .next()
550                .unwrap_or(Json::Null),
551        )
552        .unwrap_or_default();
553        if body.len() > self.max_request {
554            return Err(Error::ToolPolicy("request too large"));
555        }
556        let (status, response) = self.perform(&method, &path, &body)?;
557        if status >= 400 {
558            return Err(Error::Provider {
559                code: format!("http/{status}"),
560            });
561        }
562        let text = String::from_utf8_lossy(&response).to_string();
563        let value = serde_json::from_str::<Json>(&text)
564            .map(|json| json_to_value(&json))
565            .unwrap_or(Value::Text(text));
566        Ok(Response::Value(value))
567    }
568}
569
570// ---------------------------------------------------------------------------
571// Local process
572// ---------------------------------------------------------------------------
573
574/// A sandboxed local process tool.
575///
576/// The allowlist is the program plus its permitted argument prefixes. The child
577/// gets a scrubbed environment (only what the caller allows), no shell, and a
578/// byte-bounded stdout. Anything else is `rpc/tool-policy`.
579#[derive(Debug)]
580pub struct LocalProcess {
581    /// Absolute program path or allowlisted name.
582    pub program: String,
583    /// Arguments the caller may pass (each must be an exact match or a prefix
584    /// when it ends with `*`).
585    pub allow_args: Vec<String>,
586    /// Environment variables the child inherits.
587    pub env: BTreeMap<String, String>,
588    /// Maximum output bytes.
589    pub max_output: usize,
590    /// Calls served.
591    pub calls: u64,
592}
593
594impl LocalProcess {
595    /// Build a tool for `program` with an argument allowlist.
596    pub fn new(program: impl Into<String>, allow_args: &[&str]) -> Self {
597        Self {
598            program: program.into(),
599            allow_args: allow_args.iter().map(|arg| arg.to_string()).collect(),
600            env: BTreeMap::new(),
601            max_output: 1 << 20,
602            calls: 0,
603        }
604    }
605
606    /// Policy for a capability: process execution must be granted explicitly.
607    pub fn policy(&self) -> ToolPolicy {
608        ToolPolicy {
609            allowed: ["run"].iter().map(|method| method.to_string()).collect(),
610            max_arg_bytes: 64 << 10,
611            allow_process: true,
612        }
613    }
614
615    fn permitted(&self, arg: &str) -> bool {
616        self.allow_args.iter().any(|allowed| {
617            if let Some(prefix) = allowed.strip_suffix('*') {
618                arg.starts_with(prefix)
619            } else {
620                allowed == arg
621            }
622        })
623    }
624}
625
626impl Provider for LocalProcess {
627    fn name(&self) -> &'static str {
628        "local-process"
629    }
630
631    fn methods(&self) -> Vec<String> {
632        vec!["run".to_string()]
633    }
634
635    fn mutating(&self, _method: &str) -> bool {
636        true
637    }
638
639    fn invoke(&mut self, _object: u64, call: &Call) -> Result<Response> {
640        self.calls += 1;
641        if call.method != "run" {
642            return Err(Error::MethodNotGranted {
643                method: call.method.clone(),
644            });
645        }
646        let mut args = Vec::new();
647        for arg in &call.args {
648            if let Arg::Value(Value::Text(text)) = arg {
649                if !self.permitted(text) {
650                    return Err(Error::ToolPolicy("argument is not allowed"));
651                }
652                args.push(text.clone());
653            }
654        }
655        // The policy in the capability must have granted process execution.
656        if !call.tool_allows_process {
657            return Err(Error::ToolPolicy("process execution not granted"));
658        }
659        let mut command = Command::new(&self.program);
660        command
661            .args(&args)
662            .env_clear()
663            .stdin(Stdio::null())
664            .stderr(Stdio::piped())
665            .stdout(Stdio::piped());
666        for (key, value) in &self.env {
667            command.env(key, value);
668        }
669        let output = command.output().map_err(|error| Error::Provider {
670            code: format!("process/spawn:{error}"),
671        })?;
672        if output.stdout.len() > self.max_output {
673            return Err(Error::ToolPolicy("output too large"));
674        }
675        let mut map = BTreeMap::new();
676        map.insert(
677            "status".to_string(),
678            Value::Int(output.status.code().unwrap_or(-1) as i64),
679        );
680        map.insert(
681            "stdout".to_string(),
682            Value::Text(String::from_utf8_lossy(&output.stdout).to_string()),
683        );
684        map.insert(
685            "stderr".to_string(),
686            Value::Text(String::from_utf8_lossy(&output.stderr).to_string()),
687        );
688        Ok(Response::Value(Value::Map(map)))
689    }
690}