Skip to main content

nachalnik_mcp/
lib.rs

1#![deny(missing_docs)]
2#![deny(unsafe_code)]
3
4//! An [MCP](https://modelcontextprotocol.io) bridge for [`nachalnik`]: a tool somebody else wrote,
5//! as a [`Tool`](nachalnik::Tool) like any other.
6//!
7// the example calls `Server::spawn`, so it is documented under the feature that has it: a build
8// without `child-process` bridges to a server someone else opened the transport to, and a doctest
9// calling a function that build lacks fails for nothing
10#![cfg_attr(
11    feature = "child-process",
12    doc = r#"
13```no_run
14use nachalnik::{Config, Kernel};
15use nachalnik_mcp::Server;
16use tokio::process::Command;
17
18# async fn example() -> Result<(), Box<dyn std::error::Error>> {
19let kernel = Kernel::new(Config::default());
20
21let files = Server::spawn("files", Command::new("mcp-server-filesystem")).await?;
22let installed = files.install(&kernel).await?;
23println!("{} tools: {}", installed.added.len(), installed.added.join(", "));
24# Ok(())
25# }
26```
27"#
28)]
29
30//! # why this is not in the runtime
31//!
32//! `nachalnik` promises to spawn no processes, open no sockets and run nothing in the background,
33//! and speaking MCP needs all three. MCP also revises faster than a context library's version
34//! should, so the runtime is not tied to it.
35//!
36//! It needs nothing the runtime does not already expose. An MCP tool is a `Tool` that forwards to a
37//! server. Tools arriving and leaving use [`Kernel::add_tool`](nachalnik::Kernel::add_tool) and
38//! [`remove_tool`](nachalnik::Kernel::remove_tool), which put them on the event stream. A stop is
39//! read off the tool's [`OutputSink`](nachalnik::OutputSink) before a call goes out and while the
40//! server has it, and the server is then sent MCP's cancellation. A structured result is
41//! [`Content::Json`](nachalnik::Content). A server's progress notifications are not forwarded yet:
42//! `rmcp` puts a progress token on every request, and what a server sends against it is dropped.
43//!
44//! # what it decides, and what it refuses to
45//!
46//! These are judgement calls with defaults here, and yours to change rather than the kernel's:
47//!
48//! - **What a tool is allowed to do.** MCP tools carry hints. The specification says a client
49//!   should never make tool-use decisions based on hints from an untrusted server. [`Trust`]
50//!   defaults to believing none of them; read its documentation before changing that.
51//! - **What a tool is called.** Two servers may both offer `read`, and a kernel holds one tool per
52//!   identifier, so names are prefixed with the server's unless [`Server::without_prefix`] says
53//!   otherwise. Nothing is ever replaced quietly: [`Installed::replaced`] says what was displaced.
54
55mod server;
56mod tool;
57
58pub use crate::{
59    server::{Installed, Server},
60    tool::{LARGEST_IMAGE, Trust},
61};
62
63/// The MCP SDK this bridge is built on, re-exported.
64///
65/// note: not a convenience. [`Server::connect`] is generic over `rmcp`'s transports and
66/// [`Server::info`] returns one of its types, so without this a caller would add `rmcp` and guess
67/// the version, and a mismatch fails to compile with an error about two types of the same name.
68/// Re-exporting says which SDK this crate holds and makes an SDK bump visible here rather than in
69/// somebody's build.
70///
71/// note: [`Server::spawn`] takes a `tokio::process::Command`, which is not re-exported: anything
72/// using this runtime already has `tokio`.
73pub use rmcp;
74
75use std::fmt;
76
77/// The result of talking to an MCP server.
78pub type Result<T> = std::result::Result<T, Error>;
79
80/// Something an MCP server did, or failed to do.
81///
82/// note: not a tool that runs and reports a failure, which is an ordinary
83/// [`ToolOutput::error`](nachalnik::ToolOutput::error) the model needs to see. These mean the
84/// server will not answer.
85#[derive(Debug)]
86#[non_exhaustive]
87pub enum Error {
88    /// The server could not be reached, or refused the handshake.
89    Connect(Box<dyn std::error::Error + Send + Sync>),
90    /// The server was reached, but would not answer a request.
91    Request(Box<dyn std::error::Error + Send + Sync>),
92}
93
94impl fmt::Display for Error {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        match self {
97            Self::Connect(e) => write!(f, "could not connect to the MCP server: {e}"),
98            Self::Request(e) => write!(f, "the MCP server would not answer: {e}"),
99        }
100    }
101}
102
103impl std::error::Error for Error {
104    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
105        match self {
106            Self::Connect(e) | Self::Request(e) => Some(&**e),
107        }
108    }
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114
115    /// Both failure kinds keep the underlying error for a caller to walk or downcast.
116    ///
117    /// note: `Display` reads the same with or without it, so the chain is the only place its loss
118    /// would show.
119    #[test]
120    fn an_error_keeps_the_failure_underneath_it() {
121        let underneath = || -> Box<dyn std::error::Error + Send + Sync> {
122            Box::new(std::io::Error::new(
123                std::io::ErrorKind::NotFound,
124                "no such server",
125            ))
126        };
127
128        for (kind, e) in [
129            ("connect", Error::Connect(underneath())),
130            ("request", Error::Request(underneath())),
131        ] {
132            let source = std::error::Error::source(&e)
133                .unwrap_or_else(|| panic!("a {kind} failure says what is under it"));
134            assert!(source.downcast_ref::<std::io::Error>().is_some(), "{kind}");
135        }
136    }
137}