Skip to main content

adk_tool/mcp/server/
executor.rs

1//! The executor hook every `tools/call` goes through (spec 3.5 §7.4, §7.9).
2
3use 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
17/// The approval-scope session of a call that arrived outside an MCP session, such as over stdio
18/// or on a stateless endpoint.
19const SESSIONLESS: &str = "mcp";
20
21/// One `tools/call` the server is about to run: the tool, its arguments, the caller and the
22/// request that carried it.
23///
24/// The arguments are a JSON object that already matched the tool's parameters schema.
25#[derive(Clone)]
26#[non_exhaustive]
27pub struct McpToolCall {
28    /// The tool the call names.
29    pub tool: Arc<dyn Tool>,
30    /// The call's arguments, a JSON object.
31    pub arguments: Value,
32    /// The caller the server's [`McpCallerResolver`](super::McpCallerResolver) resolved.
33    pub caller: McpCaller,
34    /// The JSON-RPC request id, as a string; unique within its session, not across them.
35    pub request_id: String,
36    /// The MCP session the request belongs to, for stateful sessions.
37    pub session_id: Option<String>,
38    /// Whether the request declared the tasks extension (SEP-2663), so the executor may
39    /// answer with [`McpToolOutcome::Task`].
40    pub accepts_task: bool,
41    /// Whether the client negotiated MCP `2026-07-28` or later, so the executor may answer
42    /// with [`McpToolOutcome::InputRequired`].
43    pub accepts_input_required: bool,
44    /// The answers to the input requests an earlier [`McpToolOutcome::InputRequired`] asked,
45    /// sent with the retried call (SEP-2322).
46    pub input_responses: Option<InputResponses>,
47    /// The `requestState` the client echoed back with the retried call. The client may have
48    /// changed it, so an executor treats it as untrusted.
49    pub request_state: Option<String>,
50    /// The client end of the request, for progress notifications and, before `2026-07-28`,
51    /// elicitation on the live connection; `None` for a call made outside a server.
52    pub peer: Option<McpRequestPeer>,
53}
54
55impl McpToolCall {
56    /// Creates a call, outside a session, for exercising an executor directly.
57    ///
58    /// # Example
59    ///
60    /// ```rust
61    /// use std::sync::Arc;
62    ///
63    /// use adk_tool::FunctionTool;
64    /// use adk_tool::mcp::server::{McpCaller, McpToolCall};
65    /// use serde_json::json;
66    ///
67    /// let tool = Arc::new(FunctionTool::new("ping", "Answers pong", |_ctx, _args| async {
68    ///     Ok(json!("pong"))
69    /// }));
70    /// let call = McpToolCall::new(tool, json!({}), McpCaller::anonymous(), "1")
71    ///     .with_session_id("session-1");
72    /// assert_eq!(call.session_id.as_deref(), Some("session-1"));
73    /// ```
74    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    /// Sets the MCP session the call belongs to.
95    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    /// Marks the call as made by a client that takes a task in answer (SEP-2663).
101    pub fn with_task_support(mut self) -> Self {
102        self.accepts_task = true;
103        self
104    }
105
106    /// Marks the call as a retry carrying `responses` to an earlier `input_required` result
107    /// and the `request_state` it echoed back (SEP-2322); the client takes `input_required`.
108    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/// How a call that ran ended.
135#[derive(Debug)]
136#[non_exhaustive]
137pub enum McpToolOutcome {
138    /// The tool returned this value. An object becomes the result's `structuredContent`; every
139    /// value is also sent as text.
140    Completed(Value),
141    /// The tool ran and failed. The result carries `isError: true` and the error as
142    /// `adk_core::tool_error_response` describes it: a rejection's message, otherwise only its
143    /// category and code.
144    Failed(AdkError),
145    /// The call continues as this task (SEP-2663), which the client follows through
146    /// `tasks/get`, `tasks/update` and `tasks/cancel` on the server's
147    /// [`McpTaskHost`](super::McpTaskHost). Only for a call that
148    /// [accepts a task](McpToolCall::accepts_task); otherwise the call is refused.
149    Task(Task),
150    /// The call needs answers to `input_requests` before it can finish (SEP-2322): the client
151    /// calls again with the answers and `request_state`. Only for a call that
152    /// [accepts it](McpToolCall::accepts_input_required); otherwise the call is refused.
153    InputRequired {
154        /// The questions, keyed as the answers must be.
155        input_requests: InputRequests,
156        /// Echoed back by the client with the answers.
157        request_state: Option<String>,
158    },
159}
160
161/// Runs, or refuses, each call the server receives (spec 3.5 §7.9).
162///
163/// The server hands every `tools/call` to a listed, visible tool whose arguments match its
164/// schema to [`execute`](Self::execute), so an executor is the one place to route calls
165/// through `adk_core::authorize_tool_call` and the action ledger, as [`GovernedExecutor`]
166/// does. An `Err` refuses the call: the client receives a JSON-RPC error whose message keeps
167/// the error's details back unless the error is a rejection
168/// ([`ErrorCategory::is_rejection`]).
169///
170/// # Example
171///
172/// ```rust
173/// use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result, Tool, ToolEffect};
174/// use adk_tool::mcp::server::{
175///     GovernedExecutor, McpCallExecutor, McpCaller, McpToolCall, McpToolOutcome,
176/// };
177///
178/// /// Anonymous callers may only read; every call still goes through the governed path.
179/// struct ReadOnlyForAnonymous(GovernedExecutor);
180///
181/// #[async_trait::async_trait]
182/// impl McpCallExecutor for ReadOnlyForAnonymous {
183///     async fn execute(&self, call: McpToolCall) -> Result<McpToolOutcome> {
184///         if !call.caller.is_authenticated() && call.tool.effect() != ToolEffect::ReadOnly {
185///             return Err(AdkError::new(
186///                 ErrorComponent::Tool,
187///                 ErrorCategory::Forbidden,
188///                 "mcp.caller.read_only",
189///                 "sign in to make changes",
190///             ));
191///         }
192///         self.0.execute(call).await
193///     }
194///
195///     fn is_visible(&self, tool: &dyn Tool, caller: &McpCaller) -> bool {
196///         caller.is_authenticated() || tool.effect() == ToolEffect::ReadOnly
197///     }
198/// }
199/// ```
200#[async_trait]
201pub trait McpCallExecutor: Send + Sync {
202    /// Runs `call`, or refuses it with an error.
203    ///
204    /// # Errors
205    ///
206    /// Returns the error the call is refused with; the client receives it as a JSON-RPC error.
207    async fn execute(&self, call: McpToolCall) -> Result<McpToolOutcome>;
208
209    /// Whether `caller` may see and call `tool`.
210    ///
211    /// `tools/list` lists only the tools this allows, and a call to any other tool is answered
212    /// as a call to an unknown tool. The default shows every tool.
213    fn is_visible(&self, tool: &dyn Tool, caller: &McpCaller) -> bool {
214        let _ = (tool, caller);
215        true
216    }
217}
218
219/// The default executor: every call goes through [`adk_core::authorize_tool_call`] under a
220/// [`RunConfig`], then the action ledger, before [`Tool::execute`].
221///
222/// | Step | From the config | A call it stops |
223/// |------|-----------------|-----------------|
224/// | Kill switch | `governance` | Refused with `governance.frozen` (or `governance.stale`), before and after the ledger write |
225/// | Consent, egress, policy | `consent_gate`, `egress_policy`, `tool_policy` | Refused with `mcp.server.call_refused` and the reason |
226/// | Confirmation | `tool_approvals`, `approval_store`, `tool_reviewer`, `tool_confirmation_handler` | Held with `mcp.server.call_held` when the config has an approval store, else refused with `mcp.server.no_approver` |
227/// | Action ledger | `action_ledger`, for `NonIdempotent` tools | A replayed request is answered from its record and not run again |
228/// | Audit | `audit` | Each decision is recorded before it takes effect |
229///
230/// A config without a `tool_policy` refuses every call: a server's callers are remote, so a
231/// server with no rule runs no tool. The MCP client never decides a confirmation: only the
232/// server's own handler, reviewer, standing approvals or approval store do, and a held call
233/// runs when the client calls it again, with the same arguments in the same session, after an
234/// approver decided it in the approval store.
235///
236/// A call is evaluated as the agent `app_name` of the app `app_name`, for the user the
237/// caller's id — which the server's [`McpCallerResolver`](super::McpCallerResolver) or
238/// [`local_caller`](super::McpServerBuilder::local_caller) sets, never the client — in the MCP
239/// session (`mcp` for a call outside one), with function call id `mcp-{request id}`; a
240/// ledgered call is keyed by the app, caller, session and request id. A confirmation
241/// handler's wait counts against the server's call timeout.
242///
243/// # Example
244///
245/// ```rust
246/// use std::sync::Arc;
247///
248/// use adk_core::{DeclarativePolicy, GovernanceControl, RunConfig};
249/// use adk_tool::mcp::server::GovernedExecutor;
250///
251/// let control = GovernanceControl::new();
252/// let executor = GovernedExecutor::new(
253///     "com.example/shop",
254///     RunConfig::builder()
255///         .tool_policy(Arc::new(DeclarativePolicy::builder().allow_read_only().build()))
256///         .governance(control.clone())
257///         .build(),
258/// );
259/// assert_eq!(executor.app_name(), "com.example/shop");
260/// ```
261#[derive(Debug, Clone)]
262pub struct GovernedExecutor {
263    app_name: String,
264    config: Arc<RunConfig>,
265}
266
267impl GovernedExecutor {
268    /// Creates an executor that governs each call of the app `app_name` under `config`.
269    ///
270    /// A `config` without a `tool_policy` gets one that refuses every call. The config's
271    /// decisions keyed by call ID (`tool_confirmation_decisions`) are dropped: the client
272    /// chooses the request id a call ID is made from, so it could claim one.
273    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    /// The app, and acting agent, name calls are evaluated under.
281    pub fn app_name(&self) -> &str {
282        &self.app_name
283    }
284
285    /// The config every call is governed under.
286    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            // Outside a session a request id repeats across requests, so it identifies nothing.
340            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        // The ledger write can take long enough for a freeze to arrive: a call refused now
361        // never starts, and its begun record is completed as not run (spec 3.1 I20).
362        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            // The record keeps the text the client is shown, never the error's own message.
382            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/// The policy of a [`GovernedExecutor`] whose config sets none: no rule permits any call.
396#[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/// Calls [`Tool::execute`] with a [`SimpleToolContext`] and nothing else: no tool policy, kill
418/// switch, confirmation, action ledger or audit record.
419///
420/// **Important:** with this executor any caller that reaches the server runs any tool it can
421/// see. It is the explicit opt-out from [`GovernedExecutor`], for an executor that decides
422/// each call itself before delegating to it, or a test fixture; it never fronts a reachable
423/// server on its own.
424///
425/// The context's app and agent name are the executor's `app_name`, its session is the MCP
426/// session, and its function call id is `mcp-{request id}`. A tool error is reported as
427/// [`McpToolOutcome::Failed`]; nothing is refused.
428///
429/// # Example
430///
431/// ```rust
432/// use std::sync::Arc;
433///
434/// use adk_tool::mcp::server::{McpServer, UngovernedExecutor};
435///
436/// let server = McpServer::builder("com.example/fixture", "1.0.0")
437///     .description("A local fixture whose every call runs")
438///     .executor(Arc::new(UngovernedExecutor::new("com.example/fixture")))
439///     .build()?;
440/// assert_eq!(server.name(), "com.example/fixture");
441/// # Ok::<(), adk_core::AdkError>(())
442/// ```
443#[derive(Debug, Clone)]
444pub struct UngovernedExecutor {
445    app_name: String,
446}
447
448impl UngovernedExecutor {
449    /// Creates an executor whose tool contexts carry `app_name`.
450    pub fn new(app_name: impl Into<String>) -> Self {
451        Self { app_name: app_name.into() }
452    }
453
454    /// The app name the tool contexts carry.
455    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    /// A tool of `effect` that counts its runs.
493    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}