Skip to main content

vcon_server/
mcp.rs

1//! The MCP server: the HTTP API's operations as MCP tools for AI agents.
2//!
3//! It is served at `/mcp` on the TLS listener, in rmcp's stateless mode with
4//! JSON answers, behind the same authentication as every route. The stdio
5//! command in [`stdio`] forwards to it, so both transports pass one gate.
6
7mod admin;
8mod audit;
9pub mod budget;
10pub mod fence;
11mod gate;
12mod legal;
13pub mod stdio;
14mod vcons;
15
16use std::future::Future;
17use std::pin::Pin;
18use std::sync::Arc;
19use std::time::Instant;
20
21use axum::Router;
22use axum::body::Body;
23use axum::extract::{Request, State};
24use axum::middleware::Next;
25use axum::response::{IntoResponse, Response};
26use rmcp::handler::server::common::schema_for_type;
27use rmcp::model::{
28    CallToolRequestParams, CallToolResponse, CallToolResult, Extensions, Implementation,
29    JsonObject, ListToolsResult, PaginatedRequestParams, ServerCapabilities, ServerConfig, Tool,
30    ToolAnnotations,
31};
32use rmcp::service::{RequestContext, RoleServer};
33use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
34use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
35use rmcp::{ErrorData, ServerHandler};
36use serde::de::DeserializeOwned;
37use serde_json::Value;
38
39pub use gate::scope;
40
41use crate::access::{self, Caller};
42use crate::api::{self, App, Problem};
43use crate::audit::{Action, Actor, Entry};
44use crate::ids::TenantId;
45
46/// What every client is told the server holds.
47const INSTRUCTIONS: &str = "vcon-server stores vCons, encrypted at rest, and \
48keeps an audit log of every action. Its tools act only within the tenant of \
49the API key that calls them, and only within that key's scopes; each call is \
50recorded in the audit log.";
51
52/// The limits from configuration that the MCP server applies.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct Limits {
55    /// Tool calls one key may make in a one-second window.
56    pub calls_per_second: u32,
57    /// Tool calls in flight on the server.
58    pub concurrent: u32,
59    /// The largest result, in bytes.
60    pub response_bytes: usize,
61}
62
63impl Limits {
64    /// sipnab's defaults for the same limits.
65    pub const DEFAULT: Limits = Limits {
66        calls_per_second: 100,
67        concurrent: 100,
68        response_bytes: 1 << 20,
69    };
70}
71
72/// The hints a tool states besides `openWorldHint: false`.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub(crate) struct Hints {
75    pub(crate) read_only: bool,
76    pub(crate) destructive: bool,
77    pub(crate) idempotent: bool,
78}
79
80impl Hints {
81    pub(crate) const NONE: Hints = Hints {
82        read_only: false,
83        destructive: false,
84        idempotent: false,
85    };
86}
87
88/// A tool named `name` taking `A` as its arguments, with `hints`.
89pub(crate) fn tool<A: rmcp::schemars::JsonSchema + 'static>(
90    name: &'static str,
91    description: &'static str,
92    hints: Hints,
93) -> Tool {
94    Tool::new(name, description, schema_for_type::<A>()).with_annotations(
95        ToolAnnotations::new()
96            .read_only(hints.read_only)
97            .destructive(hints.destructive)
98            .idempotent(hints.idempotent)
99            .open_world(false),
100    )
101}
102
103/// Why a tool did not answer with a result.
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105#[must_use]
106pub(crate) enum Outcome {
107    /// Its arguments do not fit its type, or a value in them names nothing
108    /// the tool can read; the gate records invalid-arguments.
109    Arguments,
110    /// The tool refused before the layer it calls saw the call; the gate
111    /// records the problem, and the result carries it.
112    Refused(Problem),
113    /// The layer the tool calls refused or failed, and recorded it; the
114    /// result carries the problem.
115    Answered(Problem),
116}
117
118impl std::fmt::Display for Outcome {
119    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120        match self {
121            Outcome::Arguments => f.write_str("the arguments do not fit the tool"),
122            Outcome::Refused(problem) => write!(f, "refused: {}", problem.name().1),
123            Outcome::Answered(problem) => write!(f, "answered: {}", problem.name().1),
124        }
125    }
126}
127
128impl std::error::Error for Outcome {}
129
130/// A tool's running call.
131pub(crate) type Running<'a> = Pin<Box<dyn Future<Output = Result<Value, Outcome>> + Send + 'a>>;
132
133/// What a tool does with its caller and arguments.
134pub(crate) type Run = for<'a> fn(&'a Server, Caller, JsonObject) -> Running<'a>;
135
136/// One registered tool: what clients are shown, the action it is recorded
137/// under, and what it runs.
138#[derive(Debug, Clone)]
139pub(crate) struct Spec {
140    /// The tool as `tools/list` shows it.
141    pub(crate) tool: Tool,
142    /// The action its calls are recorded under.
143    pub(crate) action: Action,
144    /// What a call runs.
145    pub(crate) run: Run,
146}
147
148/// A tool's arguments as its type, or the refusal when they do not fit.
149pub(crate) fn arguments<A: DeserializeOwned>(arguments: JsonObject) -> Result<A, Outcome> {
150    serde_json::from_value(Value::Object(arguments)).map_err(|_| Outcome::Arguments)
151}
152
153/// The MCP server's routes: `/mcp`, behind authentication and counting,
154/// with every tool.
155pub fn router(app: Arc<App>) -> Router {
156    router_with(app, tools())
157}
158
159/// Every tool, by area.
160pub(crate) fn tools() -> Vec<Spec> {
161    let mut all = vcons::specs();
162    all.extend(legal::specs());
163    all.extend(audit::specs());
164    all.extend(admin::specs());
165    all
166}
167
168/// The caller's Store and its caller for Store, for a tool needing `scope`;
169/// a tenant being removed is unavailable.
170pub(crate) struct Opened {
171    pub(crate) store: Arc<crate::store::Store>,
172    pub(crate) who: crate::store::Caller,
173}
174
175impl std::fmt::Debug for Opened {
176    // The store holds the tenant's keys; only the caller is shown.
177    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178        f.debug_struct("Opened")
179            .field("who", &self.who)
180            .finish_non_exhaustive()
181    }
182}
183
184pub(crate) async fn opened(
185    server: &Server,
186    caller: Caller,
187    scope: access::Scope,
188) -> Result<Opened, Outcome> {
189    let tenant =
190        access::tenant_for(&caller, scope).map_err(|_| Outcome::Refused(Problem::Forbidden))?;
191    let tenants = server.app.tenants.clone();
192    let store = api::blocking(move || tenants.store(tenant))
193        .await
194        .map_err(|_| Outcome::Refused(Problem::Unavailable))?;
195    Ok(Opened {
196        store,
197        who: crate::store::Caller { key: caller.key },
198    })
199}
200
201/// A stored version's JSON text, inflated within `limit` when it was
202/// stored gzipped, with the characters the fence never holds raw escaped.
203pub(crate) fn vcon_text(stored: &crate::store::Stored, limit: u64) -> Result<String, Outcome> {
204    let damaged = || Outcome::Answered(Problem::Store(crate::store::StoreError::Damaged));
205    let text = api::inflated(stored, limit).map_err(Outcome::Answered)?;
206    let text = String::from_utf8(text).map_err(|_| damaged())?;
207    Ok(fence::escape_json(&text))
208}
209
210/// A result holding a piece of `text`: `head`'s members, the piece fenced,
211/// whether more follows and where, and the provenance sentence; the piece
212/// from `cursor`, a byte offset an earlier page gave, as long as `room`
213/// allows.
214pub(crate) fn text_result(
215    head: Value,
216    text: &str,
217    cursor: Option<&str>,
218    room: usize,
219) -> Result<Value, Outcome> {
220    let start = match cursor {
221        None => 0,
222        Some(cursor) => cursor
223            .parse::<usize>()
224            .ok()
225            .filter(|&at| at <= text.len() && text.is_char_boundary(at))
226            .ok_or(Outcome::Arguments)?,
227    };
228    let build = |piece: &str, next: Option<usize>| {
229        let mut result = head.clone();
230        result["vcon"] = fence::fence(piece).into();
231        result["truncated"] = next.is_some().into();
232        result["next_cursor"] = next.map(|at| at.to_string()).into();
233        result["provenance"] = fence::PROVENANCE.into();
234        result
235    };
236    let (piece, next) = budget::piece(text, start, |piece, more| {
237        // A following page's cursor is at most the text's length.
238        budget::size(&build(piece, more.then_some(text.len()))) <= room
239    });
240    Ok(build(piece, next))
241}
242
243/// The MCP server's routes with the tools in `specs`.
244pub(crate) fn router_with(app: Arc<App>, specs: Vec<Spec>) -> Router {
245    let server = Server {
246        app: app.clone(),
247        specs: Arc::new(specs),
248        gate: Arc::new(gate::Gate::new(app.mcp)),
249    };
250    let config = StreamableHttpServerConfig::default()
251        .with_legacy_session_mode(false)
252        .with_json_response(true)
253        .with_sse_keep_alive(None)
254        // TLS and the bearer key already stop a page that rebinds a name to
255        // this server, and a deployment's host name is its own.
256        .disable_allowed_hosts()
257        // A web page sends an Origin header; no page may call /mcp.
258        .enforce_origin_validation()
259        .with_max_request_body_bytes(app.limits.body);
260    let service: StreamableHttpService<Server, LocalSessionManager> =
261        StreamableHttpService::new(move || Ok(server.clone()), Default::default(), config);
262    // POST only: GET and DELETE answer 405 before any key is asked for, and
263    // the layer wraps this one route, never the router's fallback.
264    Router::new().route(
265        "/mcp",
266        axum::routing::post_service(service)
267            .route_layer(axum::middleware::from_fn_with_state(app, admit)),
268    )
269}
270
271/// The MCP request handler: the tools, and the gate every call passes.
272#[derive(Clone)]
273pub(crate) struct Server {
274    pub(crate) app: Arc<App>,
275    specs: Arc<Vec<Spec>>,
276    gate: Arc<gate::Gate>,
277}
278
279impl std::fmt::Debug for Server {
280    // The app holds keys and stores; the tools and the gate are shown.
281    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
282        let tools: Vec<&str> = self.specs.iter().map(|spec| &*spec.tool.name).collect();
283        f.debug_struct("Server")
284            .field("tools", &tools)
285            .field("gate", &self.gate)
286            .finish_non_exhaustive()
287    }
288}
289
290/// The caller a request to `/mcp` was admitted with.
291fn caller_of(extensions: &Extensions) -> Option<Caller> {
292    extensions
293        .get::<axum::http::request::Parts>()
294        .and_then(|parts| parts.extensions.get::<Caller>())
295        .copied()
296}
297
298/// Whether `caller` may call the tool, by the scope rule.
299fn allows(caller: &Caller, tool: &Tool) -> bool {
300    scope(&tool.name, tool.annotations.as_ref())
301        .is_some_and(|scope| access::require(caller, scope).is_ok())
302}
303
304impl Server {
305    /// Records a refusal in the caller's log and returns it, or audit-failed
306    /// when the record cannot be written.
307    async fn recorded(&self, caller: Caller, action: Action, problem: Problem) -> ErrorData {
308        let entry = refusal(caller, action, problem);
309        gate::refused(self.app.refuse(caller.tenant, entry, problem).await, None)
310    }
311
312    /// Counts a refusal in the caller's log and returns it, or audit-failed
313    /// when the count cannot be written.
314    async fn counted(
315        &self,
316        caller: Caller,
317        action: Action,
318        problem: Problem,
319        retry: Option<std::time::Duration>,
320    ) -> ErrorData {
321        if count(&self.app, caller.tenant, refusal(caller, action, problem)).await {
322            gate::refused(problem, retry)
323        } else {
324            gate::refused(Problem::AuditFailed, None)
325        }
326    }
327}
328
329/// The record of a call the gate refused.
330fn refusal(caller: Caller, action: Action, problem: Problem) -> Entry {
331    Entry {
332        actor: Actor::Key(caller.key),
333        action,
334        target: None,
335        version: None,
336        status: problem.status().as_u16(),
337    }
338}
339
340impl ServerHandler for Server {
341    fn get_info(&self) -> ServerConfig {
342        let mut info = ServerConfig::new(ServerCapabilities::builder().enable_tools().build());
343        // rmcp's default names rmcp itself; the server names itself.
344        info.server_info = Implementation::new("vcon-server", env!("CARGO_PKG_VERSION"));
345        info.instructions = Some(INSTRUCTIONS.to_owned());
346        info
347    }
348
349    /// The tools the caller's key may call, by the scope rule.
350    async fn list_tools(
351        &self,
352        _request: Option<PaginatedRequestParams>,
353        context: RequestContext<RoleServer>,
354    ) -> Result<ListToolsResult, ErrorData> {
355        let caller = caller_of(&context.extensions);
356        let mut tools: Vec<Tool> = self
357            .specs
358            .iter()
359            .filter(|spec| caller.is_some_and(|caller| allows(&caller, &spec.tool)))
360            .map(|spec| spec.tool.clone())
361            .collect();
362        tools.sort_by(|a, b| a.name.cmp(&b.name));
363        Ok(ListToolsResult::with_all_items(tools))
364    }
365
366    /// The gate every tool call passes, in order: the key's rate, a free
367    /// slot, a known tool, the tool's scope, then the tool with arguments
368    /// that fit it. Each refusal is recorded, or counted for rate and
369    /// capacity, before it is sent.
370    async fn call_tool(
371        &self,
372        request: CallToolRequestParams,
373        context: RequestContext<RoleServer>,
374    ) -> Result<CallToolResponse, ErrorData> {
375        let Some(caller) = caller_of(&context.extensions) else {
376            // Every request reaches here through admit, which sets it.
377            return Err(gate::refused(Problem::Unauthorized, None));
378        };
379        let spec = self
380            .specs
381            .iter()
382            .find(|spec| spec.tool.name == request.name);
383        let action = spec.map_or(Action::Mcp, |spec| spec.action);
384        let limit = self.gate.limits.calls_per_second;
385        if let Err(retry) = self.gate.windows.take(caller.key, limit, Instant::now()) {
386            return Err(self
387                .counted(caller, action, Problem::RateLimited, Some(retry))
388                .await);
389        }
390        let Some(_slot) = self.gate.slot() else {
391            return Err(self
392                .counted(caller, action, Problem::AtCapacity, None)
393                .await);
394        };
395        let Some(spec) = spec else {
396            return Err(self.recorded(caller, action, Problem::UnknownTool).await);
397        };
398        if !allows(&caller, &spec.tool) {
399            return Err(self.recorded(caller, action, Problem::Forbidden).await);
400        }
401        // The tool runs in its own task, so a panic in it is answered and
402        // recorded as internal instead of leaving the request unanswered.
403        let (run, server, arguments) = (
404            spec.run,
405            self.clone(),
406            request.arguments.unwrap_or_default(),
407        );
408        let ran = tokio::spawn(async move { (run)(&server, caller, arguments).await }).await;
409        let Ok(ran) = ran else {
410            let failed = Problem::Store(crate::store::StoreError::Io);
411            let entry = refusal(caller, action, failed);
412            let problem = self.app.refuse(caller.tenant, entry, failed).await;
413            return Ok(CallToolResult::structured_error(problem.document()).into());
414        };
415        match ran {
416            Ok(value) => Ok(CallToolResult::structured(value).into()),
417            Err(Outcome::Arguments) => Err(self
418                .recorded(caller, action, Problem::InvalidArguments)
419                .await),
420            Err(Outcome::Refused(problem)) => {
421                let entry = refusal(caller, action, problem);
422                let problem = self.app.refuse(caller.tenant, entry, problem).await;
423                Ok(CallToolResult::structured_error(problem.document()).into())
424            }
425            Err(Outcome::Answered(problem)) => {
426                Ok(CallToolResult::structured_error(problem.document()).into())
427            }
428        }
429    }
430}
431
432/// Counts `entry` in `tenant`'s log, or in the admin log for an operator key
433/// or a tenant whose log cannot be opened; false when it cannot be.
434async fn count(app: &Arc<App>, tenant: Option<TenantId>, entry: Entry) -> bool {
435    let tenants = app.tenants.clone();
436    api::blocking(move || match tenant.and_then(|t| tenants.store(t).ok()) {
437        Some(store) => store.count(&entry).is_ok(),
438        None => tenants.count_admin(&entry).is_ok(),
439    })
440    .await
441}
442
443/// Every request to `/mcp`, before rmcp reads it: the bearer key is
444/// authenticated as on every route, the caller's tenant opened, the body
445/// read within the limits, and the caller passed on inside the request.
446/// Each answered request is then counted in the key's log; one that cannot
447/// be counted answers audit-failed.
448async fn admit(State(app): State<Arc<App>>, request: Request, next: Next) -> Response {
449    let (mut parts, body) = request.into_parts();
450    let caller = match api::authenticated(&app, &parts.headers).await {
451        Ok(caller) => caller,
452        Err(refused) => return refused.into_response(),
453    };
454    // A tenant being removed answers 503, as on every route, and is counted
455    // in the admin log, since its own may already be gone.
456    let tenants = app.tenants.clone();
457    let closing = caller
458        .tenant
459        .is_some_and(|tenant| tenants.store(tenant).is_err());
460    let answer = if closing {
461        Problem::Unavailable.into_response()
462    } else {
463        match api::read_body(body, &parts.headers, &app.limits).await {
464            Ok(body) => {
465                parts.extensions.insert(caller);
466                next.run(Request::from_parts(parts, Body::from(body))).await
467            }
468            Err(refused) => refused.into_response(),
469        }
470    };
471    let entry = Entry {
472        actor: Actor::Key(caller.key),
473        action: Action::Mcp,
474        target: None,
475        version: None,
476        status: answer.status().as_u16(),
477    };
478    if count(&app, caller.tenant, entry).await {
479        answer
480    } else {
481        Problem::AuditFailed.into_response()
482    }
483}
484
485#[cfg(test)]
486mod tests;