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    pub calls: u64,
231}
232
233impl<T: McpTransport> McpSession<T> {
234    /// Perform the MCP handshake and discover tools.
235    pub fn handshake(transport: T) -> Result<Self> {
236        let mut session = McpSession {
237            transport,
238            tools: Vec::new(),
239            next_id: 0,
240            calls: 0,
241        };
242        let initialize = session.request(
243            "initialize",
244            json!({
245                "protocolVersion": "2025-06-18",
246                "capabilities": {},
247                "clientInfo": { "name": "active-rpc", "version": env!("CARGO_PKG_VERSION") }
248            }),
249        )?;
250        if initialize.get("error").is_some() {
251            return Err(Error::Provider {
252                code: "mcp/initialize".to_string(),
253            });
254        }
255        let list = session.request("tools/list", json!({}))?;
256        if let Some(items) = list
257            .get("result")
258            .and_then(|result| result.get("tools"))
259            .and_then(Json::as_array)
260        {
261            for item in items {
262                let name = item.get("name").and_then(Json::as_str).unwrap_or("");
263                if name.is_empty() {
264                    continue;
265                }
266                session.tools.push(McpToolDef {
267                    name: name.to_string(),
268                    description: item
269                        .get("description")
270                        .and_then(Json::as_str)
271                        .unwrap_or("")
272                        .to_string(),
273                });
274            }
275        }
276        Ok(session)
277    }
278
279    fn request(&mut self, method: &str, params: Json) -> Result<Json> {
280        self.next_id += 1;
281        let payload = json!({
282            "jsonrpc": "2.0",
283            "id": self.next_id,
284            "method": method,
285            "params": params,
286        });
287        self.transport.send_line(&payload.to_string())?;
288        let line = self.transport.recv_line()?;
289        serde_json::from_str(&line).map_err(|_| Error::Provider {
290            code: "mcp/bad-response".to_string(),
291        })
292    }
293
294    /// Discovered tools.
295    pub fn tools(&self) -> &[McpToolDef] {
296        &self.tools
297    }
298
299    /// A policy allowing exactly the discovered tools.
300    pub fn policy(&self) -> ToolPolicy {
301        let mut policy = ToolPolicy::default();
302        for tool in &self.tools {
303            policy.allowed.insert(tool.name.clone());
304        }
305        policy.max_arg_bytes = 1 << 20;
306        policy
307    }
308}
309
310impl<T: McpTransport> Provider for McpSession<T> {
311    fn name(&self) -> &'static str {
312        "mcp"
313    }
314
315    fn methods(&self) -> Vec<String> {
316        self.tools.iter().map(|tool| tool.name.clone()).collect()
317    }
318
319    fn mutating(&self, _method: &str) -> bool {
320        true
321    }
322
323    fn invoke(&mut self, object: u64, call: &Call) -> Result<Response> {
324        self.calls += 1;
325        let tool = self
326            .tools
327            .get(object as usize)
328            .ok_or(Error::InvalidArgument("unknown MCP tool"))?;
329        if tool.name != call.method {
330            return Err(Error::MethodNotGranted {
331                method: call.method.clone(),
332            });
333        }
334        let mut arguments = serde_json::Map::new();
335        for (index, arg) in call.args.iter().enumerate() {
336            if let Arg::Value(value) = arg {
337                arguments.insert(format!("arg{index}"), value_to_json(value));
338            }
339        }
340        let response = self.request(
341            "tools/call",
342            json!({ "name": tool.name, "arguments": Json::Object(arguments) }),
343        )?;
344        if let Some(error) = response.get("error") {
345            return Err(Error::Provider {
346                code: format!(
347                    "mcp/{}",
348                    error.get("code").and_then(Json::as_i64).unwrap_or(0)
349                ),
350            });
351        }
352        let result = response.get("result").cloned().unwrap_or(Json::Null);
353        Ok(Response::Value(json_to_value(&result)))
354    }
355}
356
357// ---------------------------------------------------------------------------
358// HTTP / OpenAPI
359// ---------------------------------------------------------------------------
360
361/// An HTTP endpoint restricted to an allowlist.
362///
363/// The allowlist is `(METHOD, path)` pairs. There is no redirect following, no
364/// chunked encoding, and the body is bounded by `max_body`. A URL outside the
365/// allowlist is `rpc/tool-policy`.
366#[derive(Debug)]
367pub struct HttpTool {
368    /// Base URL, e.g. `http://127.0.0.1:8080`.
369    pub base: String,
370    /// Allowed `(method, path)` pairs.
371    pub allow: BTreeSet<(String, String)>,
372    /// Maximum response bytes.
373    pub max_body: usize,
374    /// Maximum request bytes.
375    pub max_request: usize,
376    /// Calls served.
377    pub calls: u64,
378}
379
380impl HttpTool {
381    /// Build a tool for `base` with an allowlist.
382    pub fn new(base: impl Into<String>, allow: &[(&str, &str)]) -> Self {
383        Self {
384            base: base.into(),
385            allow: allow
386                .iter()
387                .map(|(method, path)| (method.to_string(), path.to_string()))
388                .collect(),
389            max_body: 1 << 20,
390            max_request: 1 << 20,
391            calls: 0,
392        }
393    }
394
395    /// Build a tool policy for a capability.
396    pub fn policy(&self) -> ToolPolicy {
397        ToolPolicy {
398            allowed: ["get", "post", "request"]
399                .iter()
400                .map(|method| method.to_string())
401                .collect(),
402            max_arg_bytes: self.max_request as u64,
403            allow_process: false,
404        }
405    }
406
407    fn perform(&self, method: &str, path: &str, body: &[u8]) -> Result<(u16, Vec<u8>)> {
408        let base = self
409            .base
410            .strip_prefix("http://")
411            .ok_or(Error::ToolPolicy("only http:// endpoints are supported"))?;
412        let mut stream = TcpStream::connect(base).map_err(|error| Error::Provider {
413            code: format!("http/connect:{error}"),
414        })?;
415        stream
416            .set_read_timeout(Some(std::time::Duration::from_secs(10)))
417            .ok();
418        let head = format!(
419            "{method} {path} HTTP/1.1\r\nhost: {base}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
420            body.len()
421        );
422        stream
423            .write_all(head.as_bytes())
424            .and_then(|_| stream.write_all(body))
425            .and_then(|_| stream.flush())
426            .map_err(|error| Error::Provider {
427                code: format!("http/write:{error}"),
428            })?;
429        let mut reader = BufReader::new(stream);
430        let mut status_line = String::new();
431        reader
432            .read_line(&mut status_line)
433            .map_err(|error| Error::Provider {
434                code: format!("http/read:{error}"),
435            })?;
436        let status: u16 = status_line
437            .split_whitespace()
438            .nth(1)
439            .and_then(|code| code.parse().ok())
440            .ok_or(Error::Provider {
441                code: "http/status".to_string(),
442            })?;
443        let mut content_length: Option<usize> = None;
444        loop {
445            let mut line = String::new();
446            let read = reader
447                .read_line(&mut line)
448                .map_err(|error| Error::Provider {
449                    code: format!("http/read:{error}"),
450                })?;
451            if read == 0 || line.trim().is_empty() {
452                break;
453            }
454            if let Some((name, value)) = line.split_once(':') {
455                if name.eq_ignore_ascii_case("content-length") {
456                    content_length = value.trim().parse().ok();
457                }
458            }
459        }
460        let mut body = Vec::new();
461        match content_length {
462            Some(length) => {
463                if length > self.max_body {
464                    return Err(Error::ToolPolicy("response too large"));
465                }
466                body.resize(length, 0);
467                reader
468                    .read_exact(&mut body)
469                    .map_err(|error| Error::Provider {
470                        code: format!("http/body:{error}"),
471                    })?;
472            }
473            None => {
474                let mut rest = Vec::new();
475                reader
476                    .take(self.max_body as u64 + 1)
477                    .read_to_end(&mut rest)
478                    .map_err(|error| Error::Provider {
479                        code: format!("http/body:{error}"),
480                    })?;
481                if rest.len() > self.max_body {
482                    return Err(Error::ToolPolicy("response too large"));
483                }
484                body = rest;
485            }
486        }
487        Ok((status, body))
488    }
489}
490
491impl Provider for HttpTool {
492    fn name(&self) -> &'static str {
493        "http"
494    }
495
496    fn methods(&self) -> Vec<String> {
497        ["get", "post", "request"]
498            .iter()
499            .map(|method| method.to_string())
500            .collect()
501    }
502
503    fn mutating(&self, method: &str) -> bool {
504        method != "get"
505    }
506
507    fn invoke(&mut self, _object: u64, call: &Call) -> Result<Response> {
508        self.calls += 1;
509        let method: String = match call.method.as_str() {
510            "get" => "GET".to_string(),
511            "post" => "POST".to_string(),
512            "request" => call
513                .args
514                .iter()
515                .find_map(|arg| match arg {
516                    Arg::Value(Value::Text(text)) => Some(text.to_uppercase()),
517                    _ => None,
518                })
519                .unwrap_or_else(|| "GET".to_string()),
520            other => {
521                return Err(Error::MethodNotGranted {
522                    method: other.to_string(),
523                })
524            }
525        };
526        let path = call
527            .args
528            .iter()
529            .find_map(|arg| match arg {
530                Arg::Value(Value::Text(text)) if text.starts_with('/') => Some(text.clone()),
531                Arg::Value(Value::Path(path)) => Some(path.clone()),
532                _ => None,
533            })
534            .ok_or(Error::InvalidArgument("an HTTP path argument is required"))?;
535        if !self.allow.contains(&(method.to_string(), path.clone())) {
536            return Err(Error::ToolPolicy("path is not on the allowlist"));
537        }
538        let body = serde_json::to_vec(
539            &call
540                .args
541                .iter()
542                .filter_map(|arg| match arg {
543                    Arg::Value(Value::Map(entries)) => {
544                        Some(value_to_json(&Value::Map(entries.clone())))
545                    }
546                    _ => None,
547                })
548                .next()
549                .unwrap_or(Json::Null),
550        )
551        .unwrap_or_default();
552        if body.len() > self.max_request {
553            return Err(Error::ToolPolicy("request too large"));
554        }
555        let (status, response) = self.perform(&method, &path, &body)?;
556        if status >= 400 {
557            return Err(Error::Provider {
558                code: format!("http/{status}"),
559            });
560        }
561        let text = String::from_utf8_lossy(&response).to_string();
562        let value = serde_json::from_str::<Json>(&text)
563            .map(|json| json_to_value(&json))
564            .unwrap_or(Value::Text(text));
565        Ok(Response::Value(value))
566    }
567}
568
569// ---------------------------------------------------------------------------
570// Local process
571// ---------------------------------------------------------------------------
572
573/// A sandboxed local process tool.
574///
575/// The allowlist is the program plus its permitted argument prefixes. The child
576/// gets a scrubbed environment (only what the caller allows), no shell, and a
577/// byte-bounded stdout. Anything else is `rpc/tool-policy`.
578#[derive(Debug)]
579pub struct LocalProcess {
580    /// Absolute program path or allowlisted name.
581    pub program: String,
582    /// Arguments the caller may pass (each must be an exact match or a prefix
583    /// when it ends with `*`).
584    pub allow_args: Vec<String>,
585    /// Environment variables the child inherits.
586    pub env: BTreeMap<String, String>,
587    /// Maximum output bytes.
588    pub max_output: usize,
589    /// Calls served.
590    pub calls: u64,
591}
592
593impl LocalProcess {
594    /// Build a tool for `program` with an argument allowlist.
595    pub fn new(program: impl Into<String>, allow_args: &[&str]) -> Self {
596        Self {
597            program: program.into(),
598            allow_args: allow_args.iter().map(|arg| arg.to_string()).collect(),
599            env: BTreeMap::new(),
600            max_output: 1 << 20,
601            calls: 0,
602        }
603    }
604
605    /// Policy for a capability: process execution must be granted explicitly.
606    pub fn policy(&self) -> ToolPolicy {
607        ToolPolicy {
608            allowed: ["run"].iter().map(|method| method.to_string()).collect(),
609            max_arg_bytes: 64 << 10,
610            allow_process: true,
611        }
612    }
613
614    fn permitted(&self, arg: &str) -> bool {
615        self.allow_args.iter().any(|allowed| {
616            if let Some(prefix) = allowed.strip_suffix('*') {
617                arg.starts_with(prefix)
618            } else {
619                allowed == arg
620            }
621        })
622    }
623}
624
625impl Provider for LocalProcess {
626    fn name(&self) -> &'static str {
627        "local-process"
628    }
629
630    fn methods(&self) -> Vec<String> {
631        vec!["run".to_string()]
632    }
633
634    fn mutating(&self, _method: &str) -> bool {
635        true
636    }
637
638    fn invoke(&mut self, _object: u64, call: &Call) -> Result<Response> {
639        self.calls += 1;
640        if call.method != "run" {
641            return Err(Error::MethodNotGranted {
642                method: call.method.clone(),
643            });
644        }
645        let mut args = Vec::new();
646        for arg in &call.args {
647            if let Arg::Value(Value::Text(text)) = arg {
648                if !self.permitted(text) {
649                    return Err(Error::ToolPolicy("argument is not allowed"));
650                }
651                args.push(text.clone());
652            }
653        }
654        // The policy in the capability must have granted process execution.
655        if !call.tool_allows_process {
656            return Err(Error::ToolPolicy("process execution not granted"));
657        }
658        let mut command = Command::new(&self.program);
659        command
660            .args(&args)
661            .env_clear()
662            .stdin(Stdio::null())
663            .stderr(Stdio::piped())
664            .stdout(Stdio::piped());
665        for (key, value) in &self.env {
666            command.env(key, value);
667        }
668        let output = command.output().map_err(|error| Error::Provider {
669            code: format!("process/spawn:{error}"),
670        })?;
671        if output.stdout.len() > self.max_output {
672            return Err(Error::ToolPolicy("output too large"));
673        }
674        let mut map = BTreeMap::new();
675        map.insert(
676            "status".to_string(),
677            Value::Int(output.status.code().unwrap_or(-1) as i64),
678        );
679        map.insert(
680            "stdout".to_string(),
681            Value::Text(String::from_utf8_lossy(&output.stdout).to_string()),
682        );
683        map.insert(
684            "stderr".to_string(),
685            Value::Text(String::from_utf8_lossy(&output.stderr).to_string()),
686        );
687        Ok(Response::Value(Value::Map(map)))
688    }
689}