Skip to main content

mcp_proxy/
execution.rs

1//! Per-tool execution policy: which tool calls the proxy may send more than
2//! once, or answer without sending.
3//!
4//! Retry, hedging, mirroring and failover can execute one client call several
5//! times; caching and coalescing can answer it without executing it. Each
6//! backend classifies its tools by [`Effect`], and every one of these features
7//! checks the effect of the call it handles:
8//!
9//! | Effect | Retry, hedging | Failover re-send | Mirror | Cache, coalescing |
10//! |---|---|---|---|---|
11//! | `read` | yes | yes | yes | yes |
12//! | `idempotent` | yes | yes | yes | no |
13//! | `write` (default) | no | only when the primary never received the call | no | no |
14//!
15//! Tools no entry matches take the backend's `default_effect`, which is
16//! `write`. A backend that enables any of these features applies them only to
17//! tools listed as `read` or `idempotent`; `default_effect = "read"` restores
18//! the behavior of releases before 0.9, where every tool was treated as `read`.
19//!
20//! # Configuration
21//!
22//! Configuration fragment: append this block after [proxy.toml](https://github.com/joshrotenberg/mcp-proxy/blob/main/tests/fixtures/documentation/proxy.toml).
23//! No optional features required.
24//!
25//! <!-- doc-config: fragment=tests/fixtures/documentation/proxy.toml features=none -->
26//! ```toml
27//! [[backends]]
28//! name = "api"
29//! transport = "http"
30//! url = "http://localhost:8080"
31//! default_effect = "write"        # default: unlisted tools are sent once
32//!
33//! [backends.retry]
34//! max_retries = 2
35//!
36//! [backends.cache]
37//! tool_ttl_seconds = 30
38//!
39//! [[backends.tool_effects]]
40//! tools = ["get_*", "list_*", "search"]
41//! effect = "read"                 # retried, cached, coalesced
42//!
43//! [[backends.tool_effects]]
44//! tools = ["put_record"]
45//! effect = "idempotent"           # retried, never cached
46//!
47//! [[backends.tool_effects]]
48//! tools = ["create_order"]
49//! effect = "write"
50//! idempotency_key = "request_id"  # retried only when the call carries one
51//! ```
52//!
53//! - `tools` lists backend-local names or wildcard patterns, with the syntax
54//!   of `expose_tools` and `hide_tools`. The first matching entry wins.
55//! - `idempotency_key` names a backend argument (after `param_overrides` and
56//!   `inject_args`). A `write` call with a non-empty value for it is treated as
57//!   `idempotent` for that call, because the backend can deduplicate by key. It
58//!   never enables caching or coalescing.
59//! - Upstream tool annotations (`readOnlyHint`, `idempotentHint`) are not
60//!   used: a backend that marks a mutating tool read-only by mistake would be
61//!   replayed silently.
62//! - Resources and prompts are unaffected; the policy covers tool calls.
63//!
64//! # Failover
65//!
66//! Failover re-sends a call only when the primary's outcome is a backend
67//! failure (internal, server or transport error), never after a client error
68//! such as `-32602` or a tool `isError` result. A `write` call without an
69//! idempotency key is re-sent only when it was rejected inside the proxy
70//! before reaching the primary: an open circuit breaker, a rate or
71//! concurrency limit, an outlier ejection, or a timeout while queued. A
72//! connection failure to the primary is not proof that the call was not
73//! received, so with only failover configured a `write` call is not re-sent;
74//! adding a circuit breaker lets writes fail over once it opens.
75//!
76//! Changing `tool_effects` or `default_effect` requires a restart. Backends
77//! added at runtime carry no policy fields, so their tools are `write`.
78
79use std::collections::HashMap;
80use std::convert::Infallible;
81use std::sync::Arc;
82use std::sync::atomic::{AtomicBool, Ordering};
83use std::task::{Context, Poll};
84
85use tower::util::BoxCloneService;
86use tower::{Service, ServiceExt};
87use tower_mcp::router::{RouterRequest, RouterResponse};
88use tower_mcp_types::protocol::McpRequest;
89
90pub use crate::config::Effect;
91use crate::config::{BackendConfig, ProxyConfig};
92
93/// One backend's tool classification.
94#[derive(Debug, Clone)]
95pub struct BackendEffects {
96    default: Effect,
97    rules: Vec<Rule>,
98}
99
100#[derive(Debug, Clone)]
101struct Rule {
102    tools: Vec<String>,
103    effect: Effect,
104    idempotency_key: Option<String>,
105}
106
107impl BackendEffects {
108    /// Build from a backend's `default_effect` and `tool_effects`.
109    pub fn from_backend(backend: &BackendConfig) -> Self {
110        Self {
111            default: backend.default_effect,
112            rules: backend
113                .tool_effects
114                .iter()
115                .map(|entry| Rule {
116                    tools: entry.tools.clone(),
117                    effect: entry.effect,
118                    idempotency_key: entry.idempotency_key.clone(),
119                })
120                .collect(),
121        }
122    }
123
124    fn rule(&self, tool: &str) -> Option<&Rule> {
125        self.rules.iter().find(|rule| {
126            rule.tools
127                .iter()
128                .any(|pattern| crate::config::wildcard_matches(pattern, tool))
129        })
130    }
131
132    /// The configured effect of a backend-local tool, ignoring arguments.
133    pub fn configured(&self, tool: &str) -> Effect {
134        self.rule(tool).map_or(self.default, |rule| rule.effect)
135    }
136
137    /// The effect of one call: a `write` call carrying a non-empty value for
138    /// its idempotency key is `idempotent`.
139    pub fn call(&self, tool: &str, arguments: &serde_json::Value) -> Effect {
140        let Some(rule) = self.rule(tool) else {
141            return self.default;
142        };
143        match (&rule.effect, &rule.idempotency_key) {
144            (Effect::Write, Some(key)) if has_value(arguments.get(key)) => Effect::Idempotent,
145            (effect, _) => *effect,
146        }
147    }
148
149    /// Whether a request addressed with backend-local names may be sent more
150    /// than once. Requests other than tool calls are unaffected.
151    pub(crate) fn replayable(&self, request: &McpRequest) -> bool {
152        match request {
153            McpRequest::CallTool(params) => {
154                self.call(&params.name, &params.arguments) != Effect::Write
155            }
156            _ => true,
157        }
158    }
159
160    /// Number of configured rules and whether any tool can resolve to `write`.
161    fn summary(&self) -> (usize, bool) {
162        let write = self.default == Effect::Write
163            || self.rules.iter().any(|rule| rule.effect == Effect::Write);
164        (self.rules.len(), write)
165    }
166}
167
168fn has_value(value: Option<&serde_json::Value>) -> bool {
169    match value {
170        None | Some(serde_json::Value::Null) => false,
171        Some(serde_json::Value::String(s)) => !s.is_empty(),
172        Some(_) => true,
173    }
174}
175
176/// Every backend's tool classification, addressed by namespaced names.
177///
178/// ```
179/// use mcp_proxy::config::{Effect, ProxyConfig};
180/// use mcp_proxy::execution::ExecutionPolicy;
181///
182/// let config = ProxyConfig::parse(r#"
183/// [proxy]
184/// name = "gw"
185/// [proxy.listen]
186/// [[backends]]
187/// name = "api"
188/// transport = "http"
189/// url = "http://localhost:8080"
190/// [[backends.tool_effects]]
191/// tools = ["get_*"]
192/// effect = "read"
193/// "#).unwrap();
194/// let policy = ExecutionPolicy::from_config(&config);
195/// assert_eq!(policy.configured("api/get_user"), Effect::Read);
196/// assert_eq!(policy.configured("api/delete_user"), Effect::Write);
197/// ```
198#[derive(Debug, Clone)]
199pub struct ExecutionPolicy {
200    /// `(namespace prefix, effects)`, longest prefix first.
201    backends: Vec<(String, Arc<BackendEffects>)>,
202    by_name: HashMap<String, Arc<BackendEffects>>,
203}
204
205impl ExecutionPolicy {
206    /// Build the table for every configured backend.
207    pub fn from_config(config: &ProxyConfig) -> Self {
208        let mut backends: Vec<(String, Arc<BackendEffects>)> = Vec::new();
209        let mut by_name = HashMap::new();
210        for backend in &config.backends {
211            let effects = Arc::new(BackendEffects::from_backend(backend));
212            backends.push((
213                format!("{}{}", backend.name, config.proxy.separator),
214                effects.clone(),
215            ));
216            by_name.insert(backend.name.clone(), effects);
217        }
218        backends.sort_by_key(|(prefix, _)| std::cmp::Reverse(prefix.len()));
219        Self { backends, by_name }
220    }
221
222    /// A backend's classification by backend name.
223    pub fn backend(&self, name: &str) -> Option<Arc<BackendEffects>> {
224        self.by_name.get(name).cloned()
225    }
226
227    fn resolve<'a>(&self, name: &'a str) -> Option<(&BackendEffects, &'a str)> {
228        self.backends.iter().find_map(|(prefix, effects)| {
229            name.strip_prefix(prefix.as_str())
230                .map(|local| (effects.as_ref(), local))
231        })
232    }
233
234    /// The configured effect of a namespaced tool, ignoring arguments. A name
235    /// outside every configured backend is `write`.
236    pub fn configured(&self, name: &str) -> Effect {
237        self.resolve(name)
238            .map_or(Effect::Write, |(effects, local)| effects.configured(local))
239    }
240
241    /// The effect of one namespaced call, including its idempotency key.
242    pub fn call(&self, name: &str, arguments: &serde_json::Value) -> Effect {
243        self.resolve(name)
244            .map_or(Effect::Write, |(effects, local)| {
245                effects.call(local, arguments)
246            })
247    }
248
249    /// Whether a response may be stored or shared for this request. Only
250    /// `read` tool calls qualify; other requests are unaffected.
251    pub(crate) fn shareable(&self, request: &McpRequest) -> bool {
252        match request {
253            McpRequest::CallTool(params) => self.configured(&params.name) == Effect::Read,
254            _ => true,
255        }
256    }
257
258    /// Whether a namespaced request may be sent more than once.
259    pub(crate) fn replayable(&self, request: &McpRequest) -> bool {
260        match request {
261            McpRequest::CallTool(params) => {
262                self.call(&params.name, &params.arguments) != Effect::Write
263            }
264            _ => true,
265        }
266    }
267}
268
269/// Log, once per backend at startup, which features skip some of its tools.
270pub(crate) fn log_protection(config: &ProxyConfig, policy: &ExecutionPolicy) {
271    let coalescing = config.performance.coalesce_requests;
272    let mirrored: std::collections::HashSet<&str> = config
273        .backends
274        .iter()
275        .filter_map(|b| b.mirror_of.as_deref())
276        .collect();
277    let failover: std::collections::HashSet<&str> = config
278        .backends
279        .iter()
280        .filter_map(|b| b.failover_for.as_deref())
281        .collect();
282    for backend in &config.backends {
283        let Some(effects) = policy.backend(&backend.name) else {
284            continue;
285        };
286        let (rules, write) = effects.summary();
287        if !write {
288            continue;
289        }
290        let mut features = Vec::new();
291        if backend.retry.is_some() {
292            features.push("retry");
293        }
294        if backend.hedging.is_some() {
295            features.push("hedging");
296        }
297        if mirrored.contains(backend.name.as_str()) {
298            features.push("mirror");
299        }
300        if failover.contains(backend.name.as_str()) {
301            features.push("failover");
302        }
303        if backend
304            .cache
305            .as_ref()
306            .is_some_and(|c| c.tool_ttl_seconds > 0)
307        {
308            features.push("cache");
309        }
310        if coalescing {
311            features.push("coalescing");
312        }
313        if features.is_empty() {
314            continue;
315        }
316        tracing::info!(
317            backend = %backend.name,
318            default_effect = ?backend.default_effect,
319            tool_effect_rules = rules,
320            features = %features.join(","),
321            "Execution policy: write tools are sent once and never cached or coalesced; \
322             list read and idempotent tools in tool_effects, or set default_effect"
323        );
324    }
325}
326
327/// Records whether a request reached a backend's middleware and its
328/// transport, so failover can tell a local rejection from a failed call.
329#[derive(Clone, Default)]
330pub(crate) struct DispatchProbe(Arc<ProbeState>);
331
332#[derive(Default)]
333struct ProbeState {
334    entered: AtomicBool,
335    dispatched: AtomicBool,
336}
337
338impl DispatchProbe {
339    /// The request entered the backend's middleware and was rejected there
340    /// without being handed to the transport. A request that never passed a
341    /// marked layer is not a local rejection.
342    pub(crate) fn locally_rejected(&self) -> bool {
343        self.0.entered.load(Ordering::SeqCst) && !self.0.dispatched.load(Ordering::SeqCst)
344    }
345}
346
347#[derive(Clone, Copy)]
348pub(crate) enum Mark {
349    Entered,
350    Dispatched,
351}
352
353/// Marks the request's [`DispatchProbe`], if any, then calls the inner service.
354#[derive(Clone)]
355pub(crate) struct MarkProbe<S> {
356    inner: S,
357    mark: Mark,
358}
359
360impl<S> MarkProbe<S> {
361    pub(crate) fn new(inner: S, mark: Mark) -> Self {
362        Self { inner, mark }
363    }
364}
365
366impl<S> Service<RouterRequest> for MarkProbe<S>
367where
368    S: Service<RouterRequest, Response = RouterResponse, Error = Infallible>,
369{
370    type Response = RouterResponse;
371    type Error = Infallible;
372    type Future = S::Future;
373
374    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
375        self.inner.poll_ready(cx)
376    }
377
378    fn call(&mut self, req: RouterRequest) -> Self::Future {
379        if let Some(probe) = req.extensions.get::<DispatchProbe>() {
380            let flag = match self.mark {
381                Mark::Entered => &probe.0.entered,
382                Mark::Dispatched => &probe.0.dispatched,
383            };
384            flag.store(true, Ordering::SeqCst);
385        }
386        self.inner.call(req)
387    }
388}
389
390type InfallibleService = BoxCloneService<RouterRequest, RouterResponse, Infallible>;
391
392/// Sends replayable calls through `replay` (retry and hedging) and every
393/// other tool call straight to `direct`.
394#[derive(Clone)]
395pub(crate) struct EffectBranch {
396    effects: Arc<BackendEffects>,
397    replay: InfallibleService,
398    direct: InfallibleService,
399}
400
401impl EffectBranch {
402    pub(crate) fn new(
403        effects: Arc<BackendEffects>,
404        replay: InfallibleService,
405        direct: InfallibleService,
406    ) -> Self {
407        Self {
408            effects,
409            replay,
410            direct,
411        }
412    }
413}
414
415impl Service<RouterRequest> for EffectBranch {
416    type Response = RouterResponse;
417    type Error = Infallible;
418    type Future = tower::util::Oneshot<InfallibleService, RouterRequest>;
419
420    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
421        // The chosen branch is readied by oneshot in `call`.
422        Poll::Ready(Ok(()))
423    }
424
425    fn call(&mut self, req: RouterRequest) -> Self::Future {
426        let branch = if self.effects.replayable(&req.inner) {
427            self.replay.clone()
428        } else {
429            self.direct.clone()
430        };
431        branch.oneshot(req)
432    }
433}
434
435/// A policy for one backend named `backend` whose `read_tools` are `read`
436/// and every other tool `write`.
437#[cfg(test)]
438pub(crate) fn test_policy(backend: &str, read_tools: &[&str]) -> Arc<ExecutionPolicy> {
439    let tools = serde_json::to_string(read_tools).unwrap();
440    let config = ProxyConfig::parse(&format!(
441        "[proxy]\nname = \"t\"\n[proxy.listen]\n[[backends]]\nname = \"{backend}\"\ntransport = \"http\"\nurl = \"http://localhost:1\"\n[[backends.tool_effects]]\ntools = {tools}\neffect = \"read\"\n"
442    ))
443    .unwrap();
444    Arc::new(ExecutionPolicy::from_config(&config))
445}
446
447#[cfg(test)]
448mod tests {
449    use super::*;
450    use serde_json::json;
451
452    fn policy(backends: &str) -> ExecutionPolicy {
453        let config = ProxyConfig::parse(&format!(
454            "[proxy]\nname = \"t\"\n[proxy.listen]\n{backends}"
455        ))
456        .unwrap();
457        ExecutionPolicy::from_config(&config)
458    }
459
460    const API: &str = r#"
461[[backends]]
462name = "api"
463transport = "http"
464url = "http://localhost:1"
465[[backends.tool_effects]]
466tools = ["get_*", "search"]
467effect = "read"
468[[backends.tool_effects]]
469tools = ["put_{a,b}"]
470effect = "idempotent"
471[[backends.tool_effects]]
472tools = ["create"]
473effect = "write"
474idempotency_key = "request_id"
475"#;
476
477    #[test]
478    fn first_match_and_default_resolve_effects() {
479        let p = policy(API);
480        assert_eq!(p.configured("api/get_user"), Effect::Read);
481        assert_eq!(p.configured("api/search"), Effect::Read);
482        assert_eq!(p.configured("api/put_a"), Effect::Idempotent);
483        assert_eq!(p.configured("api/put_c"), Effect::Write);
484        assert_eq!(p.configured("api/create"), Effect::Write);
485        assert_eq!(p.configured("api/unlisted"), Effect::Write);
486        assert_eq!(p.configured("other/get_user"), Effect::Write);
487    }
488
489    #[test]
490    fn default_effect_applies_to_unlisted_tools() {
491        let p = policy(&API.replace(
492            "url = \"http://localhost:1\"",
493            "url = \"http://localhost:1\"\ndefault_effect = \"read\"",
494        ));
495        assert_eq!(p.configured("api/unlisted"), Effect::Read);
496        assert_eq!(p.configured("api/create"), Effect::Write);
497    }
498
499    #[test]
500    fn idempotency_key_value_makes_a_write_call_idempotent() {
501        let p = policy(API);
502        let call = |args| p.call("api/create", &args);
503        assert_eq!(call(json!({"request_id": "r-1"})), Effect::Idempotent);
504        assert_eq!(call(json!({"request_id": 7})), Effect::Idempotent);
505        assert_eq!(call(json!({"request_id": ""})), Effect::Write);
506        assert_eq!(call(json!({"request_id": null})), Effect::Write);
507        assert_eq!(call(json!({})), Effect::Write);
508        // The key never makes a call shareable.
509        let request = McpRequest::CallTool(tower_mcp::protocol::CallToolParams {
510            name: "api/create".into(),
511            arguments: json!({"request_id": "r-1"}),
512            input_responses: None,
513            request_state: None,
514            meta: None,
515            task: None,
516        });
517        assert!(p.replayable(&request));
518        assert!(!p.shareable(&request));
519    }
520
521    #[test]
522    fn other_requests_are_unaffected() {
523        let p = policy(API);
524        let request = McpRequest::ReadResource(tower_mcp::protocol::ReadResourceParams {
525            uri: "api/file".into(),
526            input_responses: None,
527            request_state: None,
528            meta: None,
529        });
530        assert!(p.shareable(&request));
531        assert!(p.replayable(&request));
532    }
533
534    #[test]
535    fn probe_reports_local_rejection_only_after_entry_without_dispatch() {
536        let probe = DispatchProbe::default();
537        assert!(!probe.locally_rejected(), "unmarked counts as dispatched");
538        probe.0.entered.store(true, Ordering::SeqCst);
539        assert!(probe.locally_rejected());
540        probe.0.dispatched.store(true, Ordering::SeqCst);
541        assert!(!probe.locally_rejected());
542    }
543}