1#![expect(deprecated)]
21
22use crate::caller::Caller;
23use crate::credential::Credential;
24use crate::jwt::Claims;
25use axum::http::request::Parts;
26use chrono::{SecondsFormat, Utc};
27use rmcp::model::*;
28use rmcp::service::{
29 MaybeSendFuture, NotificationContext, RequestContext, RoleServer, SubscriptionContext,
30};
31use rmcp::{ErrorData as McpError, ServerHandler};
32use serde::Serialize;
33use std::borrow::Cow;
34use std::fs::{File, OpenOptions};
35use std::io::Write;
36#[cfg(unix)]
37use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
38use std::path::PathBuf;
39use std::sync::{Arc, Mutex, PoisonError};
40use std::time::{Duration, Instant};
41
42pub const AUDIT_TARGET: &str = "audit";
44const WARN_EVERY: Duration = Duration::from_secs(60);
45
46#[derive(Clone)]
48pub struct ToolPolicy {
49 pub service: String,
51 pub endpoint: String,
53 pub read_only: bool,
55 pub audit: Arc<AuditLog>,
57}
58
59#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
61pub struct AuditLine {
62 pub ts: String,
64 pub service: String,
66 pub endpoint: String,
68 pub tool: String,
70 pub outcome: &'static str,
72 pub error_kind: Option<String>,
74 pub caller: Option<String>,
78 pub subject: Option<String>,
81 pub elapsed_ms: u64,
83}
84
85pub struct AuditLog {
87 file: Option<Mutex<AuditFile>>,
88}
89
90struct AuditFile {
91 path: PathBuf,
92 file: Option<File>,
93 last_warn: Option<Instant>,
94}
95
96impl AuditLog {
97 pub fn new(path: Option<PathBuf>) -> Self {
100 Self {
101 file: path.map(|path| {
102 Mutex::new(AuditFile {
103 path,
104 file: None,
105 last_warn: None,
106 })
107 }),
108 }
109 }
110
111 pub fn record(&self, line: &AuditLine) {
114 tracing::info!(
115 target: AUDIT_TARGET,
116 service = %line.service,
117 endpoint = %line.endpoint,
118 tool = %line.tool,
119 outcome = line.outcome,
120 error_kind = line.error_kind.as_deref(),
121 caller = line.caller.as_deref(),
122 subject = line.subject.as_deref(),
123 elapsed_ms = line.elapsed_ms,
124 "tool write"
125 );
126 if let Some(file) = &self.file {
127 file.lock()
128 .unwrap_or_else(PoisonError::into_inner)
129 .append(line);
130 }
131 }
132}
133
134impl AuditFile {
135 fn append(&mut self, line: &AuditLine) {
137 let mut text = serde_json::to_string(line).expect("audit lines serialize");
138 text.push('\n');
139 let written = self.open().and_then(|f| f.write_all(text.as_bytes()));
140 let Err(e) = written else {
141 return;
142 };
143 self.file = None;
144 let now = Instant::now();
145 if self
146 .last_warn
147 .is_some_and(|t| now.duration_since(t) < WARN_EVERY)
148 {
149 return;
150 }
151 self.last_warn = Some(now);
152 tracing::warn!(path = %self.path.display(), error = %e, "could not write the audit log");
153 }
154
155 fn open(&mut self) -> std::io::Result<&mut File> {
156 if self.file.is_none() {
157 let mut options = OpenOptions::new();
158 options.create(true).append(true);
159 #[cfg(unix)]
160 options.mode(0o600);
161 let file = options.open(&self.path)?;
162 #[cfg(unix)]
163 file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
164 self.file = Some(file);
165 }
166 Ok(self.file.as_mut().expect("opened above"))
167 }
168}
169
170fn parts(ctx: &RequestContext<RoleServer>) -> Option<&Parts> {
171 ctx.extensions.get::<Parts>()
172}
173
174fn request_policy(ctx: &RequestContext<RoleServer>) -> Option<ToolPolicy> {
175 parts(ctx)?.extensions.get::<ToolPolicy>().cloned()
176}
177
178fn caller(ctx: &RequestContext<RoleServer>) -> Option<String> {
181 let parts = parts(ctx)?;
182 if let Some(c) = parts.extensions.get::<Caller>() {
183 return Some(c.audit_label());
184 }
185 Some(match parts.extensions.get::<Claims>() {
186 Some(claims) => match &claims.payload.client_id {
187 Some(id) => format!("oauth:{id}"),
188 None => "oauth".into(),
189 },
190 None if parts.extensions.get::<Credential>().is_some() => "credential".into(),
191 None => "static".into(),
192 })
193}
194
195pub fn is_read_only(tool: Option<&Tool>) -> bool {
198 tool.and_then(|t| t.annotations.as_ref())
199 .and_then(|a| a.read_only_hint)
200 == Some(true)
201}
202
203fn error_kind(result: &CallToolResult) -> Option<String> {
205 let text = result.content.first()?.as_text()?.text.as_str();
206 let (kind, _) = text.split_once(": ")?;
207 let valid = !kind.is_empty() && kind.bytes().all(|b| b.is_ascii_lowercase() || b == b'_');
208 valid.then(|| kind.to_string())
209}
210
211fn outcome(response: &Result<CallToolResponse, McpError>) -> (&'static str, Option<String>) {
212 match response {
213 Ok(CallToolResponse::Complete(r)) if r.is_error == Some(true) => ("error", error_kind(r)),
214 Ok(_) => ("ok", None),
215 Err(_) => ("error", Some("protocol".into())),
216 }
217}
218
219pub fn visible_tools(mut tools: Vec<Tool>, read_only: bool) -> Vec<Tool> {
221 if read_only {
222 tools.retain(|t| is_read_only(Some(t)));
223 }
224 tools
225}
226
227pub struct Guarded<S> {
229 inner: S,
230 policy: Option<ToolPolicy>,
231}
232
233impl<S> Guarded<S> {
234 pub fn new(inner: S) -> Self {
236 Self {
237 inner,
238 policy: None,
239 }
240 }
241
242 pub fn with_policy(inner: S, policy: ToolPolicy) -> Self {
244 Self {
245 inner,
246 policy: Some(policy),
247 }
248 }
249
250 fn policy(&self, ctx: &RequestContext<RoleServer>) -> Option<ToolPolicy> {
251 self.policy.clone().or_else(|| request_policy(ctx))
252 }
253}
254
255impl<S: ServerHandler> ServerHandler for Guarded<S> {
256 fn ping(
257 &self,
258 context: RequestContext<RoleServer>,
259 ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_ {
260 self.inner.ping(context)
261 }
262
263 fn initialize(
264 &self,
265 request: InitializeRequestParams,
266 context: RequestContext<RoleServer>,
267 ) -> impl Future<Output = Result<InitializeResult, McpError>> + MaybeSendFuture + '_ {
268 self.inner.initialize(request, context)
269 }
270
271 fn negotiate_initialize(
272 &self,
273 request: &InitializeRequestParams,
274 ) -> Result<InitializeResult, McpError> {
275 self.inner.negotiate_initialize(request)
276 }
277
278 fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> {
279 self.inner.supported_protocol_versions()
280 }
281
282 fn discover(
283 &self,
284 context: RequestContext<RoleServer>,
285 ) -> impl Future<Output = Result<DiscoverResult, McpError>> + MaybeSendFuture + '_ {
286 self.inner.discover(context)
287 }
288
289 fn complete(
290 &self,
291 request: CompleteRequestParams,
292 context: RequestContext<RoleServer>,
293 ) -> impl Future<Output = Result<CompleteResult, McpError>> + MaybeSendFuture + '_ {
294 self.inner.complete(request, context)
295 }
296
297 fn set_level(
298 &self,
299 request: SetLevelRequestParams,
300 context: RequestContext<RoleServer>,
301 ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_ {
302 self.inner.set_level(request, context)
303 }
304
305 fn get_prompt(
306 &self,
307 request: GetPromptRequestParams,
308 context: RequestContext<RoleServer>,
309 ) -> impl Future<Output = Result<GetPromptResponse, McpError>> + MaybeSendFuture + '_ {
310 self.inner.get_prompt(request, context)
311 }
312
313 fn list_prompts(
314 &self,
315 request: Option<PaginatedRequestParams>,
316 context: RequestContext<RoleServer>,
317 ) -> impl Future<Output = Result<ListPromptsResult, McpError>> + MaybeSendFuture + '_ {
318 self.inner.list_prompts(request, context)
319 }
320
321 fn list_resources(
322 &self,
323 request: Option<PaginatedRequestParams>,
324 context: RequestContext<RoleServer>,
325 ) -> impl Future<Output = Result<ListResourcesResult, McpError>> + MaybeSendFuture + '_ {
326 self.inner.list_resources(request, context)
327 }
328
329 fn list_resource_templates(
330 &self,
331 request: Option<PaginatedRequestParams>,
332 context: RequestContext<RoleServer>,
333 ) -> impl Future<Output = Result<ListResourceTemplatesResult, McpError>> + MaybeSendFuture + '_
334 {
335 self.inner.list_resource_templates(request, context)
336 }
337
338 fn read_resource(
339 &self,
340 request: ReadResourceRequestParams,
341 context: RequestContext<RoleServer>,
342 ) -> impl Future<Output = Result<ReadResourceResponse, McpError>> + MaybeSendFuture + '_ {
343 self.inner.read_resource(request, context)
344 }
345
346 fn read_resource_directory(
347 &self,
348 request: ReadResourceDirectoryRequestParams,
349 context: RequestContext<RoleServer>,
350 ) -> impl Future<Output = Result<ReadResourceDirectoryResult, McpError>> + MaybeSendFuture + '_
351 {
352 self.inner.read_resource_directory(request, context)
353 }
354
355 fn list_skills(
356 &self,
357 request: Option<PaginatedRequestParams>,
358 context: RequestContext<RoleServer>,
359 ) -> impl Future<Output = Result<ListSkillsResult, McpError>> + MaybeSendFuture + '_ {
360 self.inner.list_skills(request, context)
361 }
362
363 fn get_skill(
364 &self,
365 request: GetSkillRequestParams,
366 context: RequestContext<RoleServer>,
367 ) -> impl Future<Output = Result<GetSkillResult, McpError>> + MaybeSendFuture + '_ {
368 self.inner.get_skill(request, context)
369 }
370
371 fn accepted_subscription_filter(
372 &self,
373 requested: &SubscriptionFilter,
374 ) -> Option<SubscriptionFilter> {
375 self.inner.accepted_subscription_filter(requested)
376 }
377
378 fn listen(
379 &self,
380 context: SubscriptionContext,
381 ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_ {
382 self.inner.listen(context)
383 }
384
385 fn subscribe(
386 &self,
387 request: SubscribeRequestParams,
388 context: RequestContext<RoleServer>,
389 ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_ {
390 self.inner.subscribe(request, context)
391 }
392
393 fn unsubscribe(
394 &self,
395 request: UnsubscribeRequestParams,
396 context: RequestContext<RoleServer>,
397 ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_ {
398 self.inner.unsubscribe(request, context)
399 }
400
401 async fn call_tool(
404 &self,
405 request: CallToolRequestParams,
406 context: RequestContext<RoleServer>,
407 ) -> Result<CallToolResponse, McpError> {
408 let Some(policy) = self.policy(&context) else {
409 return self.inner.call_tool(request, context).await;
410 };
411 if is_read_only(self.inner.get_tool(&request.name).as_ref()) {
412 return self.inner.call_tool(request, context).await;
413 }
414 let tool = request.name.to_string();
415 let caller = caller(&context);
416 let subject = parts(&context)
417 .and_then(|p| p.extensions.get::<Caller>())
418 .map(|c| c.subject.clone());
419 let started = Instant::now();
420 let (outcome, error_kind, response) = if policy.read_only {
421 let text = format!(
422 "read_only: the {} service is read-only on this server",
423 policy.service
424 );
425 let refused = CallToolResult::error(vec![ContentBlock::text(text)]);
426 ("refused", Some("read_only".to_string()), Ok(refused.into()))
427 } else {
428 let response = self.inner.call_tool(request, context).await;
429 let (outcome, kind) = outcome(&response);
430 (outcome, kind, response)
431 };
432 policy.audit.record(&AuditLine {
433 ts: Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true),
434 service: policy.service.clone(),
435 endpoint: policy.endpoint.clone(),
436 tool,
437 outcome,
438 error_kind,
439 caller,
440 subject,
441 elapsed_ms: started.elapsed().as_millis() as u64,
442 });
443 response
444 }
445
446 async fn list_tools(
448 &self,
449 request: Option<PaginatedRequestParams>,
450 context: RequestContext<RoleServer>,
451 ) -> Result<ListToolsResult, McpError> {
452 let read_only = self.policy(&context).is_some_and(|p| p.read_only);
453 let mut result = self.inner.list_tools(request, context).await?;
454 result.tools = visible_tools(result.tools, read_only);
455 Ok(result)
456 }
457
458 fn get_tool(&self, name: &str) -> Option<Tool> {
459 self.inner.get_tool(name)
460 }
461
462 fn on_custom_request(
463 &self,
464 request: CustomRequest,
465 context: RequestContext<RoleServer>,
466 ) -> impl Future<Output = Result<CustomResult, McpError>> + MaybeSendFuture + '_ {
467 self.inner.on_custom_request(request, context)
468 }
469
470 fn on_cancelled(
471 &self,
472 notification: CancelledNotificationParam,
473 context: NotificationContext<RoleServer>,
474 ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
475 self.inner.on_cancelled(notification, context)
476 }
477
478 fn on_progress(
479 &self,
480 notification: ProgressNotificationParam,
481 context: NotificationContext<RoleServer>,
482 ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
483 self.inner.on_progress(notification, context)
484 }
485
486 fn on_initialized(
487 &self,
488 context: NotificationContext<RoleServer>,
489 ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
490 self.inner.on_initialized(context)
491 }
492
493 fn on_roots_list_changed(
494 &self,
495 context: NotificationContext<RoleServer>,
496 ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
497 self.inner.on_roots_list_changed(context)
498 }
499
500 fn on_custom_notification(
501 &self,
502 notification: CustomNotification,
503 context: NotificationContext<RoleServer>,
504 ) -> impl Future<Output = ()> + MaybeSendFuture + '_ {
505 self.inner.on_custom_notification(notification, context)
506 }
507
508 fn get_info(&self) -> ServerConfig {
509 self.inner.get_info()
510 }
511
512 fn get_task(
513 &self,
514 request: GetTaskParams,
515 context: RequestContext<RoleServer>,
516 ) -> impl Future<Output = Result<GetTaskResult, McpError>> + MaybeSendFuture + '_ {
517 self.inner.get_task(request, context)
518 }
519
520 fn update_task(
521 &self,
522 request: UpdateTaskParams,
523 context: RequestContext<RoleServer>,
524 ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_ {
525 self.inner.update_task(request, context)
526 }
527
528 fn cancel_task(
529 &self,
530 request: CancelTaskParams,
531 context: RequestContext<RoleServer>,
532 ) -> impl Future<Output = Result<(), McpError>> + MaybeSendFuture + '_ {
533 self.inner.cancel_task(request, context)
534 }
535}
536
537#[cfg(test)]
538mod tests {
539 use super::*;
540
541 fn line() -> AuditLine {
542 AuditLine {
543 ts: "2026-10-18T10:00:00.000Z".into(),
544 service: "svc".into(),
545 endpoint: "/svc".into(),
546 tool: "change".into(),
547 outcome: "ok",
548 error_kind: None,
549 caller: Some("static".into()),
550 subject: Some("static".into()),
551 elapsed_ms: 1,
552 }
553 }
554
555 #[test]
556 fn write_failures_warn_at_most_once_a_minute() {
557 let dir = tempfile::tempdir().unwrap();
558 let mut file = AuditFile {
559 path: dir.path().join("missing").join("audit.jsonl"),
560 file: None,
561 last_warn: None,
562 };
563 file.append(&line());
564 let first = file.last_warn.expect("the first failure warns");
565 file.append(&line());
566 assert_eq!(
567 file.last_warn,
568 Some(first),
569 "a second failure within a minute is quiet"
570 );
571 file.last_warn = Some(first - WARN_EVERY);
572 file.append(&line());
573 assert!(
574 file.last_warn.unwrap() > first,
575 "warns again after a minute"
576 );
577 }
578
579 #[cfg(unix)]
580 #[test]
581 fn an_existing_audit_file_is_narrowed_to_0600() {
582 use std::fs::Permissions;
583 let dir = tempfile::tempdir().unwrap();
584 let path = dir.path().join("audit.jsonl");
585 std::fs::write(&path, "").unwrap();
586 std::fs::set_permissions(&path, Permissions::from_mode(0o644)).unwrap();
587 let mut file = AuditFile {
588 path: path.clone(),
589 file: None,
590 last_warn: None,
591 };
592 file.append(&line());
593 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
594 assert_eq!(mode & 0o777, 0o600);
595 }
596
597 #[test]
598 fn a_failed_write_reopens_the_file_next_time() {
599 let dir = tempfile::tempdir().unwrap();
600 let path = dir.path().join("later").join("audit.jsonl");
601 let mut file = AuditFile {
602 path: path.clone(),
603 file: None,
604 last_warn: None,
605 };
606 file.append(&line());
607 assert!(file.file.is_none());
608 std::fs::create_dir(dir.path().join("later")).unwrap();
609 file.append(&line());
610 assert_eq!(std::fs::read_to_string(&path).unwrap().lines().count(), 1);
611 }
612
613 #[test]
614 fn error_kinds_are_read_from_the_tool_error_text() {
615 let r = |t: &str| CallToolResult::error(vec![ContentBlock::text(t)]);
616 assert_eq!(
617 error_kind(&r("not_found: no such id")).as_deref(),
618 Some("not_found")
619 );
620 assert_eq!(error_kind(&r("Something: else")), None);
621 assert_eq!(error_kind(&r("no colon")), None);
622 }
623
624 #[test]
625 fn visible_tools_keeps_only_read_only_tools_when_read_only() {
626 let tool = |name: &'static str, ro: Option<bool>| {
627 let mut t = Tool::new(name, "d", Arc::new(serde_json::Map::new()));
628 t.annotations = ro.map(|r| ToolAnnotations::new().read_only(r));
629 t
630 };
631 let tools = vec![
632 tool("look", Some(true)),
633 tool("change", Some(false)),
634 tool("plain", None),
635 ];
636 let names = |v: Vec<Tool>| {
637 v.into_iter()
638 .map(|t| t.name.to_string())
639 .collect::<Vec<_>>()
640 };
641 assert_eq!(
642 names(visible_tools(tools.clone(), false)),
643 ["look", "change", "plain"]
644 );
645 assert_eq!(names(visible_tools(tools, true)), ["look"]);
646 }
647}