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