Skip to main content

vcon_server/mcp/
stdio.rs

1//! `vcon-server mcp`: MCP on stdin and stdout, for an agent that starts the
2//! server as a command. Each request is forwarded to a running server's
3//! `/mcp` with the one key the client file names, so stdio passes the same
4//! authentication, gate and audit as HTTP. The command opens no data
5//! directory and no master key.
6
7use std::fmt;
8use std::path::{Path, PathBuf};
9
10use rmcp::model::{
11    CallToolRequestParams, CallToolResponse, ListToolsResult, PaginatedRequestParams, ServerConfig,
12};
13use rmcp::service::{
14    ClientInitializeError, Peer, RequestContext, RoleClient, RoleServer, RunningService,
15    ServiceError,
16};
17use rmcp::transport::streamable_http_client::{
18    StreamableHttpClientTransport, StreamableHttpClientTransportConfig, StreamableHttpError,
19};
20use rmcp::{ErrorData, ServerHandler, ServiceExt};
21use serde::Deserialize;
22
23use crate::config::ConfigError;
24
25/// The client file `vcon-server mcp` and `vcon-server tui` read.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct ClientConfig {
28    /// The server's address: for `vcon-server mcp` its MCP address,
29    /// `https://host:port/mcp`; for `vcon-server tui` the server itself,
30    /// `https://host:port`, with no path.
31    pub url: String,
32    /// A file holding one API token and nothing else.
33    pub key_file: PathBuf,
34    /// PEM certificates to trust for the server; the system's roots when
35    /// absent.
36    pub ca: Option<PathBuf>,
37}
38
39#[derive(Debug, Deserialize)]
40#[serde(deny_unknown_fields)]
41struct Raw {
42    url: String,
43    key_file: PathBuf,
44    ca: Option<PathBuf>,
45}
46
47/// Reads the client file at `path`.
48///
49/// # Errors
50///
51/// [`ConfigError`] when the file cannot be read or does not parse as a
52/// client file.
53pub fn client_config(path: &Path) -> Result<ClientConfig, ConfigError> {
54    let text = std::fs::read_to_string(path)
55        .map_err(|e| ConfigError(format!("{}: {e}", path.display())))?;
56    parse_client(&text)
57}
58
59/// Reads a client file from its TOML text. The URL must be `https`: the
60/// server speaks TLS only.
61///
62/// # Errors
63///
64/// [`ConfigError`] when the text is not TOML, has a key a client file
65/// does not take, or names a URL that is not `https`.
66pub fn parse_client(text: &str) -> Result<ClientConfig, ConfigError> {
67    let raw: Raw = toml::from_str(text).map_err(|e| ConfigError(e.to_string()))?;
68    if !raw.url.starts_with("https://") {
69        return Err(ConfigError(format!(
70            "url: {:?} is not an https:// URL",
71            raw.url
72        )));
73    }
74    Ok(ClientConfig {
75        url: raw.url,
76        key_file: raw.key_file,
77        ca: raw.ca,
78    })
79}
80
81/// Why the command stopped. None of these holds the token.
82#[derive(Debug, Clone, PartialEq, Eq)]
83#[must_use]
84pub enum StdioError {
85    /// The key file could not be read, or holds no single token.
86    KeyFile(String),
87    /// The CA file could not be read, or the TLS client not made.
88    Tls(String),
89    /// The server refused the key with this status.
90    Refused(u16),
91    /// The server could not be reached, or answered something other than
92    /// MCP.
93    Server(String),
94    /// stdin or stdout failed.
95    Io(String),
96}
97
98impl std::error::Error for StdioError {}
99
100impl fmt::Display for StdioError {
101    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102        match self {
103            StdioError::KeyFile(why) => f.write_str(why),
104            StdioError::Tls(why) => write!(f, "ca: {why}"),
105            StdioError::Refused(status) => {
106                write!(f, "the server refused the key ({status})")
107            }
108            StdioError::Server(why) => write!(f, "the server: {why}"),
109            StdioError::Io(why) => write!(f, "stdio: {why}"),
110        }
111    }
112}
113
114/// The one token a key file holds, with white space at either end removed.
115/// The file is held to the one secret-file rule (`crate::secret_file`).
116pub(crate) fn token(key_file: &Path) -> Result<String, StdioError> {
117    let refused =
118        |why: &str| StdioError::KeyFile(format!("key_file {}: {why}", key_file.display()));
119    let bytes = crate::secret_file::read(key_file, "key_file").map_err(StdioError::KeyFile)?;
120    let text = std::str::from_utf8(&bytes).map_err(|_| refused("the file is not UTF-8"))?;
121    let token = text.trim();
122    if token.is_empty() || token.contains(char::is_whitespace) {
123        return Err(refused("holds no single token"));
124    }
125    Ok(token.to_owned())
126}
127
128/// An HTTPS client trusting `ca`, or the system's roots without it. It
129/// connects directly, through no proxy.
130pub(crate) fn https_client(ca: Option<&Path>) -> Result<reqwest::Client, StdioError> {
131    let mut builder = reqwest::Client::builder().no_proxy();
132    if let Some(ca) = ca {
133        let pem =
134            std::fs::read(ca).map_err(|e| StdioError::Tls(format!("{}: {e}", ca.display())))?;
135        let roots = reqwest::Certificate::from_pem_bundle(&pem)
136            .map_err(|e| StdioError::Tls(format!("{}: {e}", ca.display())))?;
137        if roots.is_empty() {
138            return Err(StdioError::Tls(format!(
139                "{}: holds no certificate",
140                ca.display()
141            )));
142        }
143        builder = builder.tls_certs_only(roots);
144    }
145    builder.build().map_err(|e| StdioError::Tls(e.to_string()))
146}
147
148/// Why the handshake with the server failed: the 401 when the server
149/// refused the key, else the error's text.
150fn refusal(error: &ClientInitializeError) -> StdioError {
151    if let ClientInitializeError::TransportError { error, .. } = error
152        && let Some(StreamableHttpError::AuthRequired(_)) = error
153            .error
154            .downcast_ref::<StreamableHttpError<reqwest::Error>>()
155    {
156        return StdioError::Refused(401);
157    }
158    StdioError::Server(error.to_string())
159}
160
161/// The handshake the stdio side answers: the server's own name,
162/// capabilities and instructions.
163fn identity(peer: &rmcp::model::ServerPeerInfo) -> Result<ServerConfig, StdioError> {
164    let Some(name) = peer.server_info.clone() else {
165        return Err(StdioError::Server("no server name".to_owned()));
166    };
167    let mut info = ServerConfig::new(peer.capabilities.clone());
168    info.server_info = name;
169    info.instructions = peer.instructions.clone();
170    Ok(info)
171}
172
173/// Runs the command until stdin ends.
174///
175/// # Errors
176///
177/// [`StdioError`] when the key file or the CA cannot be read, when the
178/// server cannot be reached or refuses the key, or when stdin or stdout
179/// fails.
180pub async fn stdio(config: &ClientConfig) -> Result<(), StdioError> {
181    let token = token(&config.key_file)?;
182    let client = https_client(config.ca.as_deref())?;
183    let transport = StreamableHttpClientTransport::with_client(
184        client,
185        StreamableHttpClientTransportConfig::with_uri(config.url.as_str()).auth_header(token),
186    );
187    let upstream: RunningService<RoleClient, rmcp::model::ClientConfig> =
188        rmcp::model::ClientConfig::default()
189            .serve(transport)
190            .await
191            .map_err(|e| refusal(&e))?;
192    // The server's own identity and capabilities, as it gave them.
193    let peer = upstream
194        .peer_info()
195        .ok_or_else(|| StdioError::Server("no server information".to_owned()))?;
196    let info = identity(&peer)?;
197    let forward = Forward {
198        upstream: upstream.peer().clone(),
199        info,
200    };
201    let served = forward
202        .serve(rmcp::transport::io::stdio())
203        .await
204        .map_err(|e| StdioError::Io(e.to_string()))?;
205    served
206        .waiting()
207        .await
208        .map_err(|e| StdioError::Io(e.to_string()))?;
209    upstream
210        .cancel()
211        .await
212        .map_err(|e| StdioError::Server(e.to_string()))?;
213    Ok(())
214}
215
216/// The stdio side: answers the handshake as the server answered it, and
217/// sends each tool listing and tool call to the server.
218#[derive(Clone)]
219struct Forward {
220    upstream: Peer<RoleClient>,
221    info: ServerConfig,
222}
223
224/// The server's own refusal as it sent it; any other failure as an
225/// internal error that says what failed.
226fn forwarded(error: ServiceError) -> ErrorData {
227    match error {
228        ServiceError::McpError(error) => error,
229        other => ErrorData::internal_error(format!("the server: {other}"), None),
230    }
231}
232
233impl ServerHandler for Forward {
234    fn get_info(&self) -> ServerConfig {
235        self.info.clone()
236    }
237
238    async fn list_tools(
239        &self,
240        request: Option<PaginatedRequestParams>,
241        _context: RequestContext<RoleServer>,
242    ) -> Result<ListToolsResult, ErrorData> {
243        self.upstream.list_tools(request).await.map_err(forwarded)
244    }
245
246    async fn call_tool(
247        &self,
248        request: CallToolRequestParams,
249        _context: RequestContext<RoleServer>,
250    ) -> Result<CallToolResponse, ErrorData> {
251        self.upstream
252            .call_tool_once(request)
253            .await
254            .map_err(forwarded)
255    }
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261
262    #[test]
263    fn a_client_file_is_read_and_its_url_must_be_https() {
264        assert_eq!(
265            parse_client(
266                "url = \"https://vcon.example.com:8443/mcp\"\nkey_file = \"/etc/agent.token\"\nca = \"/etc/ca.pem\"\n"
267            ),
268            Ok(ClientConfig {
269                url: "https://vcon.example.com:8443/mcp".to_owned(),
270                key_file: PathBuf::from("/etc/agent.token"),
271                ca: Some(PathBuf::from("/etc/ca.pem")),
272            })
273        );
274        let without_ca =
275            parse_client("url = \"https://vcon.example.com/mcp\"\nkey_file = \"k\"\n").expect("ok");
276        assert_eq!(without_ca.ca, None);
277        for (text, named) in [
278            (
279                "url = \"http://vcon.example.com/mcp\"\nkey_file = \"k\"\n",
280                "url",
281            ),
282            ("key_file = \"k\"\n", "url"),
283            ("url = \"https://vcon.example.com/mcp\"\n", "key_file"),
284            (
285                "url = \"https://vcon.example.com/mcp\"\nkey_file = \"k\"\ntoken = \"t\"\n",
286                "token",
287            ),
288        ] {
289            let error = parse_client(text).expect_err(text);
290            assert!(error.0.contains(named), "{text}: {}", error.0);
291        }
292    }
293
294    /// The client file the website's command-line page shows reads.
295    #[test]
296    fn the_client_file_on_the_command_line_page_reads() {
297        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
298            .join("../../website/content/docs/command-line.md");
299        let text = std::fs::read_to_string(&path).expect("the page");
300        let section = text
301            .split("## MCP for an AI agent\n")
302            .nth(1)
303            .expect("an MCP section")
304            .split("\n## ")
305            .next()
306            .expect("its text");
307        let examples: Vec<&str> = section
308            .split("```toml\n")
309            .skip(1)
310            .map(|block| block.split("```").next().expect("a block"))
311            .collect();
312        assert_eq!(examples.len(), 1);
313        let read = parse_client(examples[0]).expect("reads");
314        assert_eq!(read.url, "https://vcon.example.com:8443/mcp");
315        assert!(read.ca.is_some());
316    }
317
318    #[test]
319    fn each_error_names_what_failed() {
320        for (error, text) in [
321            (
322                StdioError::KeyFile("key_file k: gone".to_owned()),
323                "key_file k: gone",
324            ),
325            (StdioError::Tls("c: bad".to_owned()), "ca: c: bad"),
326            (StdioError::Refused(401), "the server refused the key (401)"),
327            (StdioError::Server("down".to_owned()), "the server: down"),
328            (StdioError::Io("closed".to_owned()), "stdio: closed"),
329        ] {
330            assert_eq!(error.to_string(), text);
331        }
332    }
333
334    #[test]
335    fn the_handshake_answers_with_the_servers_name_or_not_at_all() {
336        use rmcp::model::{Implementation, ProtocolVersion, ServerCapabilities, ServerPeerInfo};
337        let capabilities = ServerCapabilities::builder().enable_tools().build();
338        let peer = ServerPeerInfo::new(ProtocolVersion::LATEST, capabilities.clone())
339            .with_server_info(Implementation::new("vcon-server", "9.9.9"))
340            .with_instructions("held");
341        let info = identity(&peer).expect("named");
342        assert_eq!(info.server_info.name, "vcon-server");
343        assert_eq!(info.server_info.version, "9.9.9");
344        assert_eq!(info.capabilities, capabilities);
345        assert_eq!(info.instructions.as_deref(), Some("held"));
346        let nameless = ServerPeerInfo::new(ProtocolVersion::LATEST, capabilities);
347        assert!(matches!(identity(&nameless), Err(StdioError::Server(_))));
348    }
349
350    #[test]
351    fn a_key_file_holds_exactly_one_token() {
352        let dir = tempfile::tempdir().expect("temp dir");
353        let file = dir.path().join("agent.token");
354        std::fs::write(&file, "  vcs_0011223344556677_secret \n").expect("write");
355        key_mode(&file, 0o600);
356        assert_eq!(token(&file).expect("read"), "vcs_0011223344556677_secret");
357        for text in ["", " \n", "vcs_a b"] {
358            std::fs::write(&file, text).expect("write");
359            assert!(
360                matches!(token(&file), Err(StdioError::KeyFile(_))),
361                "{text:?}"
362            );
363        }
364        assert!(matches!(
365            token(&dir.path().join("missing")),
366            Err(StdioError::KeyFile(_))
367        ));
368    }
369
370    /// A TLS server for one test: to each request, after its headers, it
371    /// answers 200 with a chunked `application/json` body of spaces that
372    /// never ends, until the client closes or `cap` bytes are sent. It
373    /// returns how many body bytes it sent, over every connection.
374    fn endless_json_server(
375        cert: &rcgen::CertifiedKey<rcgen::KeyPair>,
376        cap: usize,
377    ) -> (u16, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
378        use std::io::{Read, Write};
379        use std::sync::Arc;
380        use std::sync::atomic::{AtomicUsize, Ordering};
381        let chain = vec![cert.cert.der().clone()];
382        let key = rustls::pki_types::PrivateKeyDer::Pkcs8(cert.signing_key.serialize_der().into());
383        let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
384        let mut config = rustls::ServerConfig::builder_with_provider(provider)
385            .with_safe_default_protocol_versions()
386            .expect("versions")
387            .with_no_client_auth()
388            .with_single_cert(chain, key)
389            .expect("a server config");
390        config.alpn_protocols = vec![b"http/1.1".to_vec()];
391        let config = Arc::new(config);
392        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("binds");
393        let port = listener.local_addr().expect("an address").port();
394        let sent = Arc::new(AtomicUsize::new(0));
395        let counter = sent.clone();
396        std::thread::spawn(move || {
397            for stream in listener.incoming() {
398                let Ok(tcp) = stream else { return };
399                let conn = rustls::ServerConnection::new(config.clone()).expect("a connection");
400                let mut tls = rustls::StreamOwned::new(conn, tcp);
401                let mut head = Vec::new();
402                let mut byte = [0u8; 1];
403                while !head.ends_with(b"\r\n\r\n") {
404                    match tls.read(&mut byte) {
405                        Ok(1) => head.push(byte[0]),
406                        _ => break,
407                    }
408                }
409                let reply = b"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ntransfer-encoding: chunked\r\n\r\n";
410                if tls.write_all(reply).is_err() {
411                    continue;
412                }
413                let chunk = vec![b' '; 64 * 1024];
414                let framed = [
415                    format!("{:x}\r\n", chunk.len()).into_bytes(),
416                    chunk,
417                    b"\r\n".to_vec(),
418                ]
419                .concat();
420                while counter.load(Ordering::SeqCst) < cap {
421                    if tls.write_all(&framed).is_err() {
422                        break;
423                    }
424                    counter.fetch_add(64 * 1024, Ordering::SeqCst);
425                }
426            }
427        });
428        (port, sent)
429    }
430
431    /// RUSTSEC-2026-0462: before rmcp 3.9.0 its Streamable HTTP client read
432    /// a JSON answer whole, with no limit, so an endless one from a
433    /// malicious or broken server held the bridge, and its host's memory,
434    /// until the process ran out. The bridge must give up on it instead.
435    #[tokio::test(flavor = "multi_thread")]
436    async fn an_endless_json_answer_to_the_handshake_is_given_up_not_buffered() {
437        use std::sync::atomic::Ordering;
438        const CAP: usize = 128 * 1024 * 1024;
439        let cert = rcgen::generate_simple_self_signed(vec!["localhost".to_owned()])
440            .expect("a certificate");
441        let (port, sent) = endless_json_server(&cert, CAP);
442        let dir = tempfile::tempdir().expect("temp dir");
443        let ca = dir.path().join("ca.pem");
444        std::fs::write(&ca, cert.cert.pem()).expect("write the CA");
445        let key_file = dir.path().join("agent.token");
446        std::fs::write(&key_file, "vcs_0011223344556677_secret\n").expect("write the key file");
447        std::fs::set_permissions(
448            &key_file,
449            <std::fs::Permissions as std::os::unix::fs::PermissionsExt>::from_mode(0o600),
450        )
451        .expect("chmod 0600");
452        let config = parse_client(&format!(
453            "url = \"https://localhost:{port}/mcp\"\nkey_file = {key_file:?}\nca = {ca:?}\n"
454        ))
455        .expect("a client configuration");
456        let outcome = tokio::time::timeout(std::time::Duration::from_secs(120), stdio(&config))
457            .await
458            .expect("the bridge gives up within two minutes");
459        assert!(
460            matches!(outcome, Err(StdioError::Server(_))),
461            "the handshake fails: {outcome:?}"
462        );
463        let bytes = sent.load(Ordering::SeqCst);
464        assert!(
465            bytes < 32 * 1024 * 1024,
466            "the bridge stopped reading near rmcp's 16 MiB limit, not after {bytes} bytes"
467        );
468    }
469
470    fn key_mode(path: &Path, mode: u32) {
471        use std::os::unix::fs::PermissionsExt;
472        std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).expect("chmod");
473    }
474
475    fn key_file_of_mode(dir: &tempfile::TempDir, mode: u32) -> std::path::PathBuf {
476        let file = dir.path().join("agent.token");
477        std::fs::write(&file, "vcs_0011223344556677_secret\n").expect("write");
478        key_mode(&file, mode);
479        file
480    }
481
482    #[test]
483    fn a_key_file_other_users_may_read_is_refused_with_the_fix() {
484        let dir = tempfile::tempdir().expect("temp dir");
485        let file = key_file_of_mode(&dir, 0o644);
486        let error = token(&file).expect_err("refused");
487        let path = file.display();
488        assert_eq!(
489            error.to_string(),
490            format!(
491                "key_file {path}: other users may read or change the file (mode 0644); run \
492                 `chmod 600 {path}`, or `chmod 640 {path}` for a group that only reads it"
493            ),
494            "the refusal names key_file, the file, its mode and the fix"
495        );
496        assert!(!error.to_string().contains("vcs_0011"), "{error}");
497    }
498
499    #[test]
500    fn a_key_file_its_group_may_read_is_used() {
501        let dir = tempfile::tempdir().expect("temp dir");
502        let file = key_file_of_mode(&dir, 0o640);
503        assert_eq!(
504            token(&file).expect("read"),
505            "vcs_0011223344556677_secret",
506            "a group may read a 0640 key file"
507        );
508    }
509
510    #[test]
511    fn a_missing_key_file_names_the_key_and_the_file() {
512        let error = token(Path::new("/nonexistent/agent.token")).expect_err("refused");
513        assert_eq!(
514            error.to_string(),
515            "key_file /nonexistent/agent.token: No such file or directory (os error 2)",
516            "a missing key file is named with its key and path"
517        );
518    }
519}