1use std::sync::Arc;
4
5use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind, AuditRecordOutcome};
6use adk_core::{
7 AdkError, ApprovalScope, ErrorCategory, ErrorComponent, GovernedCall, PolicyDecision, Result,
8 RunConfig, Tool, ToolAuthorization, ToolGate, ToolPolicy, ToolPolicyRequest,
9};
10use async_trait::async_trait;
11use rmcp::model::{InputRequests, InputResponses, Task};
12use serde_json::Value;
13
14use super::{McpCaller, McpRequestPeer};
15use crate::SimpleToolContext;
16
17const SESSIONLESS: &str = "mcp";
20
21#[derive(Clone)]
26#[non_exhaustive]
27pub struct McpToolCall {
28 pub tool: Arc<dyn Tool>,
30 pub arguments: Value,
32 pub caller: McpCaller,
34 pub request_id: String,
36 pub session_id: Option<String>,
38 pub accepts_task: bool,
41 pub accepts_input_required: bool,
44 pub input_responses: Option<InputResponses>,
47 pub request_state: Option<String>,
50 pub peer: Option<McpRequestPeer>,
53}
54
55impl McpToolCall {
56 pub fn new(
75 tool: Arc<dyn Tool>,
76 arguments: Value,
77 caller: McpCaller,
78 request_id: impl Into<String>,
79 ) -> Self {
80 Self {
81 tool,
82 arguments,
83 caller,
84 request_id: request_id.into(),
85 session_id: None,
86 accepts_task: false,
87 accepts_input_required: false,
88 input_responses: None,
89 request_state: None,
90 peer: None,
91 }
92 }
93
94 pub fn with_session_id(mut self, session_id: impl Into<String>) -> Self {
96 self.session_id = Some(session_id.into());
97 self
98 }
99
100 pub fn with_task_support(mut self) -> Self {
102 self.accepts_task = true;
103 self
104 }
105
106 pub fn with_input_responses(
109 mut self,
110 responses: InputResponses,
111 request_state: Option<String>,
112 ) -> Self {
113 self.accepts_input_required = true;
114 self.input_responses = Some(responses);
115 self.request_state = request_state;
116 self
117 }
118}
119
120impl std::fmt::Debug for McpToolCall {
121 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122 f.debug_struct("McpToolCall")
123 .field("tool", &self.tool.name())
124 .field("caller", &self.caller.id())
125 .field("request_id", &self.request_id)
126 .field("session_id", &self.session_id)
127 .field("accepts_task", &self.accepts_task)
128 .field("accepts_input_required", &self.accepts_input_required)
129 .field("request_state", &self.request_state.is_some())
130 .finish_non_exhaustive()
131 }
132}
133
134#[derive(Debug)]
136#[non_exhaustive]
137pub enum McpToolOutcome {
138 Completed(Value),
141 Failed(AdkError),
145 Task(Task),
150 InputRequired {
154 input_requests: InputRequests,
156 request_state: Option<String>,
158 },
159}
160
161#[async_trait]
201pub trait McpCallExecutor: Send + Sync {
202 async fn execute(&self, call: McpToolCall) -> Result<McpToolOutcome>;
208
209 fn is_visible(&self, tool: &dyn Tool, caller: &McpCaller) -> bool {
214 let _ = (tool, caller);
215 true
216 }
217}
218
219#[derive(Debug, Clone)]
262pub struct GovernedExecutor {
263 app_name: String,
264 config: Arc<RunConfig>,
265}
266
267impl GovernedExecutor {
268 pub fn new(app_name: impl Into<String>, mut config: RunConfig) -> Self {
274 config.tool_policy.get_or_insert_with(|| Arc::new(NoToolPolicy));
275 config.tool_confirmation_decisions.clear();
276 config.tool_confirmation_fingerprints.clear();
277 Self { app_name: app_name.into(), config: Arc::new(config) }
278 }
279
280 pub fn app_name(&self) -> &str {
282 &self.app_name
283 }
284
285 pub fn run_config(&self) -> &RunConfig {
287 &self.config
288 }
289}
290
291#[async_trait]
292impl McpCallExecutor for GovernedExecutor {
293 async fn execute(&self, call: McpToolCall) -> Result<McpToolOutcome> {
294 let config = self.config.as_ref();
295 let name = call.tool.name().to_string();
296 let function_call_id = format!("mcp-{}", call.request_id);
297 let session = call.session_id.as_deref().unwrap_or(SESSIONLESS);
298 let scope = ApprovalScope::new(&self.app_name, call.caller.id(), session);
299 let gate = ToolGate::new(config, &self.app_name, &function_call_id, scope);
300 let governed =
301 GovernedCall::for_tool(call.tool.as_ref(), &function_call_id, call.arguments);
302 let args = match adk_core::authorize_tool_call(&gate, governed).await? {
303 ToolAuthorization::Execute { args, .. } => args,
304 ToolAuthorization::Refuse { reason, .. } => {
305 return Err(refused("mcp.server.call_refused", reason));
306 }
307 ToolAuthorization::Pending { reason, .. } if config.approval_store.is_some() => {
308 return Err(refused(
309 "mcp.server.call_held",
310 format!(
311 "{reason}. The call is held for an approver; call it again with the same \
312 arguments once it is approved"
313 ),
314 ));
315 }
316 ToolAuthorization::Pending { reason, .. } => {
317 return Err(refused(
318 "mcp.server.no_approver",
319 format!(
320 "{reason}. This server has no approver to decide it: give its governance \
321 config a `tool_confirmation_handler` or an `approval_store`, or permit \
322 the call in its `tool_policy`"
323 ),
324 ));
325 }
326 };
327
328 let mut context = SimpleToolContext::new(self.app_name.clone())
329 .with_function_call_id(&function_call_id)
330 .with_acting_context(gate.acting_context().clone());
331 if let Some(session) = &call.session_id {
332 context = context.with_session_id(session);
333 }
334 let context = Arc::new(context);
335 let key = match &call.session_id {
336 Some(session) => {
337 format!("mcp/{}/{}/{session}/{}", self.app_name, call.caller.id(), call.request_id)
338 }
339 None => format!("mcp/{}/{}/{}", self.app_name, call.caller.id(), uuid::Uuid::new_v4()),
341 };
342 let ledgered = match adk_core::begin_ledgered_call(
343 config,
344 context.as_ref(),
345 call.tool.effect(),
346 key,
347 &name,
348 &args,
349 )
350 .await?
351 {
352 Ok(ledgered) => ledgered,
353 Err(answer) => {
354 return match answer.cause {
355 Some(cause) => Err(cause),
356 None => Ok(McpToolOutcome::Completed(answer.response)),
357 };
358 }
359 };
360 if let Err(refusal) = config.check_governance() {
363 let text = adk_core::not_run_text(&refusal);
364 if let Some(trail) = &config.audit {
365 let draft = AuditRecordDraft::new(AuditRecordKind::ToolCall, &name)
366 .actor(AuditActor::new(gate.acting_context(), &function_call_id))
367 .args_digest(trail.digest(&args))
368 .outcome(AuditRecordOutcome::NotRun)
369 .ext("reason", Value::String(text.clone()))
370 .ext("sessionId", Value::String(session.to_string()));
371 trail.record(draft).await?;
372 }
373 if let Some(ledgered) = ledgered {
374 ledgered.complete(&name, None, &text).await;
375 }
376 return Err(refusal);
377 }
378
379 let result = call.tool.execute(context, args).await;
380 if let Some(ledgered) = ledgered {
381 let shown = match &result {
383 Ok(_) => Value::Null,
384 Err(error) => adk_core::tool_error_response(&name, error, false)["error"].clone(),
385 };
386 ledgered.complete(&name, result.as_ref().ok(), shown.as_str().unwrap_or("")).await;
387 }
388 Ok(match result {
389 Ok(value) => McpToolOutcome::Completed(value),
390 Err(error) => McpToolOutcome::Failed(error),
391 })
392 }
393}
394
395#[derive(Debug)]
397struct NoToolPolicy;
398
399#[async_trait]
400impl ToolPolicy for NoToolPolicy {
401 async fn evaluate(&self, _request: &ToolPolicyRequest) -> PolicyDecision {
402 PolicyDecision::deny(
403 "this MCP server has no tool policy, so it runs no tool; permit tools with a \
404 `tool_policy` in the config passed to `McpServerBuilder::tool_governance`",
405 )
406 }
407
408 fn policy_ref(&self) -> Option<String> {
409 Some("mcp.server.no_policy".to_string())
410 }
411}
412
413fn refused(code: &'static str, message: impl Into<String>) -> AdkError {
414 AdkError::new(ErrorComponent::Tool, ErrorCategory::Forbidden, code, message)
415}
416
417#[derive(Debug, Clone)]
444pub struct UngovernedExecutor {
445 app_name: String,
446}
447
448impl UngovernedExecutor {
449 pub fn new(app_name: impl Into<String>) -> Self {
451 Self { app_name: app_name.into() }
452 }
453
454 pub fn app_name(&self) -> &str {
456 &self.app_name
457 }
458}
459
460#[async_trait]
461impl McpCallExecutor for UngovernedExecutor {
462 async fn execute(&self, call: McpToolCall) -> Result<McpToolOutcome> {
463 let mut context = SimpleToolContext::new(self.app_name.clone())
464 .with_function_call_id(format!("mcp-{}", call.request_id));
465 if let Some(session) = call.session_id {
466 context = context.with_session_id(session);
467 }
468 Ok(match call.tool.execute(Arc::new(context), call.arguments).await {
469 Ok(value) => McpToolOutcome::Completed(value),
470 Err(error) => McpToolOutcome::Failed(error),
471 })
472 }
473}
474
475#[cfg(test)]
476mod tests {
477 use std::sync::atomic::{AtomicUsize, Ordering};
478
479 use adk_core::audit_log::{AuditDecision, AuditTrail, InMemoryAuditRecorder};
480 use adk_core::{
481 ActionLedger, ApprovalStore, DeclarativePolicy, GOVERNANCE_FROZEN_CODE, GovernanceControl,
482 InMemoryActionLedger, InMemoryApprovalStore, ToolApproval, ToolEffect,
483 };
484 use serde_json::json;
485
486 use super::*;
487 use crate::FunctionTool;
488 use crate::mcp::server::McpServer;
489
490 const APP: &str = "com.example/shop";
491
492 fn counted(name: &str, effect: ToolEffect) -> (Arc<dyn Tool>, Arc<AtomicUsize>) {
494 let runs = Arc::new(AtomicUsize::new(0));
495 let counter = Arc::clone(&runs);
496 let tool = FunctionTool::new(name, "a tool", move |_ctx, _args| {
497 let counter = Arc::clone(&counter);
498 async move {
499 counter.fetch_add(1, Ordering::SeqCst);
500 Ok(json!({ "booked": true }))
501 }
502 })
503 .with_effect(effect);
504 (Arc::new(tool), runs)
505 }
506
507 fn call(tool: &Arc<dyn Tool>, request_id: &str) -> McpToolCall {
508 McpToolCall::new(
509 Arc::clone(tool),
510 json!({ "date": "2026-12-01" }),
511 McpCaller::authenticated("partner:acme"),
512 request_id,
513 )
514 .with_session_id("s1")
515 }
516
517 fn policy(policy: DeclarativePolicy) -> RunConfig {
518 RunConfig::builder().tool_policy(Arc::new(policy)).build()
519 }
520
521 fn completed(outcome: McpToolOutcome) -> Value {
522 match outcome {
523 McpToolOutcome::Completed(value) => value,
524 other => panic!("the call completes: {other:?}"),
525 }
526 }
527
528 #[tokio::test]
529 async fn a_server_without_governance_refuses_every_call() {
530 let (tool, runs) = counted("get_quote", ToolEffect::ReadOnly);
531 let server = McpServer::builder(APP, "1.0.0")
532 .description("Shop")
533 .tool(Arc::clone(&tool))
534 .build()
535 .unwrap();
536 let error = server.inner.executor.execute(call(&tool, "1")).await.unwrap_err();
537 assert_eq!(error.code, "mcp.server.call_refused");
538 assert_eq!(error.category, ErrorCategory::Forbidden);
539 assert!(error.message.contains("no tool policy"), "{}", error.message);
540 assert!(error.message.contains("tool_governance"), "names the fix: {}", error.message);
541 assert_eq!(runs.load(Ordering::SeqCst), 0, "a refused call never runs");
542 }
543
544 #[tokio::test]
545 async fn a_call_no_rule_permits_is_refused() {
546 let (tool, runs) = counted("book_install", ToolEffect::NonIdempotent);
547 let executor = GovernedExecutor::new(
548 APP,
549 policy(DeclarativePolicy::builder().allow("get_quote").build()),
550 );
551 let error = executor.execute(call(&tool, "1")).await.unwrap_err();
552 assert_eq!(error.code, "mcp.server.call_refused");
553 assert!(error.message.contains("no policy rule permits"), "{}", error.message);
554 assert_eq!(runs.load(Ordering::SeqCst), 0);
555 }
556
557 #[tokio::test]
558 async fn a_frozen_control_refuses_the_call_until_unfrozen() {
559 let (tool, runs) = counted("book_install", ToolEffect::Idempotent);
560 let control = GovernanceControl::new();
561 let config = RunConfig::builder()
562 .tool_policy(Arc::new(DeclarativePolicy::builder().allow("*").build()))
563 .governance(control.clone())
564 .build();
565 let executor = GovernedExecutor::new(APP, config);
566
567 control.freeze("incident 4012");
568 let error = executor.execute(call(&tool, "1")).await.unwrap_err();
569 assert_eq!(error.code, GOVERNANCE_FROZEN_CODE);
570 assert!(error.message.contains("incident 4012"), "{}", error.message);
571 assert_eq!(runs.load(Ordering::SeqCst), 0);
572
573 control.unfreeze();
574 completed(executor.execute(call(&tool, "2")).await.unwrap());
575 assert_eq!(runs.load(Ordering::SeqCst), 1);
576 }
577
578 #[tokio::test]
579 async fn an_approval_required_call_with_no_approver_is_refused() {
580 let (tool, runs) = counted("book_install", ToolEffect::NonIdempotent);
581 let executor = GovernedExecutor::new(
582 APP,
583 policy(
584 DeclarativePolicy::builder()
585 .require_approval("book_install", "a person confirms each booking")
586 .build(),
587 ),
588 );
589 let error = executor.execute(call(&tool, "1")).await.unwrap_err();
590 assert_eq!(error.code, "mcp.server.no_approver");
591 assert_eq!(error.category, ErrorCategory::Forbidden);
592 assert!(error.message.contains("a person confirms each booking"), "{}", error.message);
593 assert!(error.message.contains("approval_store"), "names the fix: {}", error.message);
594 assert_eq!(runs.load(Ordering::SeqCst), 0);
595 }
596
597 #[tokio::test]
598 async fn a_client_cannot_claim_a_decision_keyed_by_call_id() {
599 let (tool, runs) = counted("book_install", ToolEffect::NonIdempotent);
600 let mut config = policy(
601 DeclarativePolicy::builder()
602 .require_approval("book_install", "a person confirms each booking")
603 .build(),
604 );
605 config
606 .tool_confirmation_decisions
607 .insert("mcp-1".to_string(), adk_core::ToolConfirmationDecision::Approve);
608 let executor = GovernedExecutor::new(APP, config);
609 let error = executor.execute(call(&tool, "1")).await.unwrap_err();
610 assert_eq!(error.code, "mcp.server.no_approver");
611 assert_eq!(runs.load(Ordering::SeqCst), 0);
612 }
613
614 #[tokio::test]
615 async fn a_held_call_runs_once_an_approver_decides_it() {
616 let (tool, runs) = counted("book_install", ToolEffect::NonIdempotent);
617 let store = Arc::new(InMemoryApprovalStore::new());
618 let config = RunConfig::builder()
619 .tool_policy(Arc::new(
620 DeclarativePolicy::builder()
621 .require_approval("book_install", "a person confirms each booking")
622 .build(),
623 ))
624 .approval_store(store.clone())
625 .build();
626 let executor = GovernedExecutor::new(APP, config);
627
628 let held = executor.execute(call(&tool, "1")).await.unwrap_err();
629 assert_eq!(held.code, "mcp.server.call_held");
630 assert_eq!(runs.load(Ordering::SeqCst), 0);
631
632 let scope = ApprovalScope::new(APP, "partner:acme", "s1");
633 let pending = store.pending(&scope).await.unwrap();
634 assert_eq!(pending.len(), 1, "the call waits in the store");
635 store.decide(&scope, &pending[0].fingerprint, ToolApproval::approve()).await.unwrap();
636
637 completed(executor.execute(call(&tool, "2")).await.unwrap());
638 assert_eq!(runs.load(Ordering::SeqCst), 1, "the decided call runs on its retry");
639 }
640
641 #[tokio::test]
642 async fn an_allowed_call_runs_and_is_recorded() {
643 let (tool, runs) = counted("book_install", ToolEffect::NonIdempotent);
644 let recorder = InMemoryAuditRecorder::new();
645 let ledger = Arc::new(InMemoryActionLedger::new());
646 let config = RunConfig::builder()
647 .tool_policy(Arc::new(DeclarativePolicy::builder().allow("book_install").build()))
648 .action_ledger(ledger.clone())
649 .audit(AuditTrail::new(Arc::new(recorder.clone())))
650 .build();
651 let executor = GovernedExecutor::new(APP, config);
652
653 let value = completed(executor.execute(call(&tool, "7")).await.unwrap());
654 assert_eq!(value, json!({ "booked": true }));
655 assert_eq!(runs.load(Ordering::SeqCst), 1);
656
657 let decisions: Vec<(String, Option<AuditDecision>)> =
658 recorder.records().into_iter().map(|record| (record.action, record.decision)).collect();
659 assert_eq!(decisions, vec![("book_install".to_string(), Some(AuditDecision::Allowed))]);
660 let record = ledger.get("mcp/com.example/shop/partner:acme/s1/7").await.unwrap();
661 assert!(record.is_some_and(|record| record.is_completed()), "the call is ledgered");
662
663 let replay = completed(executor.execute(call(&tool, "7")).await.unwrap());
664 assert_eq!(replay["status"], "already_succeeded");
665 assert_eq!(runs.load(Ordering::SeqCst), 1, "a replayed request is not run again");
666 }
667
668 #[tokio::test]
669 async fn the_ungoverned_executor_runs_every_call() {
670 let (tool, runs) = counted("book_install", ToolEffect::NonIdempotent);
671 let executor = UngovernedExecutor::new(APP);
672 let value = completed(executor.execute(call(&tool, "1")).await.unwrap());
673 assert_eq!(value, json!({ "booked": true }));
674 assert_eq!(runs.load(Ordering::SeqCst), 1);
675 }
676
677 #[test]
678 fn an_executor_and_a_governance_config_are_exclusive() {
679 let error = McpServer::builder(APP, "1.0.0")
680 .description("Shop")
681 .executor(Arc::new(UngovernedExecutor::new(APP)))
682 .tool_governance(RunConfig::default())
683 .build()
684 .unwrap_err();
685 assert_eq!(error.code, "mcp.server.executor_and_governance");
686 }
687}