1mod 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
46const 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct Limits {
55 pub calls_per_second: u32,
57 pub concurrent: u32,
59 pub response_bytes: usize,
61}
62
63impl Limits {
64 pub const DEFAULT: Limits = Limits {
66 calls_per_second: 100,
67 concurrent: 100,
68 response_bytes: 1 << 20,
69 };
70}
71
72#[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
88pub(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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105#[must_use]
106pub(crate) enum Outcome {
107 Arguments,
110 Refused(Problem),
113 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
130pub(crate) type Running<'a> = Pin<Box<dyn Future<Output = Result<Value, Outcome>> + Send + 'a>>;
132
133pub(crate) type Run = for<'a> fn(&'a Server, Caller, JsonObject) -> Running<'a>;
135
136#[derive(Debug, Clone)]
139pub(crate) struct Spec {
140 pub(crate) tool: Tool,
142 pub(crate) action: Action,
144 pub(crate) run: Run,
146}
147
148pub(crate) fn arguments<A: DeserializeOwned>(arguments: JsonObject) -> Result<A, Outcome> {
150 serde_json::from_value(Value::Object(arguments)).map_err(|_| Outcome::Arguments)
151}
152
153pub fn router(app: Arc<App>) -> Router {
156 router_with(app, tools())
157}
158
159pub(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
168pub(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 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
201pub(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
210pub(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 budget::size(&build(piece, more.then_some(text.len()))) <= room
239 });
240 Ok(build(piece, next))
241}
242
243pub(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 .disable_allowed_hosts()
257 .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 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#[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 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
290fn 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
298fn 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 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 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
329fn 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 info.server_info = Implementation::new("vcon-server", env!("CARGO_PKG_VERSION"));
345 info.instructions = Some(INSTRUCTIONS.to_owned());
346 info
347 }
348
349 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 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 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 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
432async 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
443async 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 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;