Skip to main content

mcp_twill_host/
lib.rs

1//! Compiled host adapters and runtime policy for mcp-twill servers.
2//!
3//! RFC 0019 host profiles compile an immutable native tool-surface snapshot
4//! into a separately hashed host snapshot. That snapshot drives generated
5//! VS Code artifacts and either the closed process-envelope router or the
6//! typed in-process bridge. This crate also owns process-level runtime
7//! identity and the effect-aware retry policy a supervisor needs when it
8//! considers re-issuing a call.
9//!
10//! Hot-replacement detection (noticing the server binary was swapped under
11//! a live connection) is planned follow-up work in this crate; nothing here
12//! populates `executable_hash` yet.
13
14mod canonical;
15mod profile;
16mod transport;
17mod vscode;
18
19use chrono::Utc;
20use mcp_twill::{CliMcpServer, EffectSpec, InvocationPlan, RuntimeIdentity};
21
22pub use profile::*;
23pub use transport::*;
24pub use vscode::*;
25
26/// Wraps a server with the identity facts a process-level host can observe.
27///
28/// Construction captures the start time, so build the host once at startup
29/// and keep it for the life of the process.
30#[derive(Debug, Clone)]
31pub struct RuntimeHost {
32    identity: RuntimeIdentity,
33}
34
35impl RuntimeHost {
36    /// Captures process facts for the given server: process id and start
37    /// time, layered onto the identity the server already reports.
38    pub fn new(server: &CliMcpServer) -> Self {
39        let identity = attach_process_facts(server.runtime_identity());
40        Self { identity }
41    }
42
43    /// The hosted identity: everything the core server reports, plus the
44    /// process id and start time.
45    pub fn identity(&self) -> &RuntimeIdentity {
46        &self.identity
47    }
48
49    /// Whether the planned call may be re-issued after an ambiguous failure
50    /// (connection dropped mid-call, server replaced, timeout with unknown
51    /// outcome). Reads the effect and the idempotency declaration from the
52    /// plan — the catalog is authoritative, not the supervisor's judgment.
53    pub fn retry_decision(&self, plan: &InvocationPlan) -> RetryDecision {
54        retry_decision(plan)
55    }
56}
57
58fn attach_process_facts(identity: RuntimeIdentity) -> RuntimeIdentity {
59    let mut identity = identity;
60    identity.process_id = Some(std::process::id());
61    identity.started_at_unix_ms = Some(Utc::now().timestamp_millis());
62    identity
63}
64
65/// The host's answer to "may this call be re-issued after an ambiguous
66/// failure?".
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub enum RetryDecision {
69    /// Safe to retry: the effect observes but does not change anything.
70    Retry,
71    /// Safe to retry only because the command declared itself idempotent
72    /// in the catalog; the handler deduplicates re-issued invocations
73    /// (the plan's invocation fingerprint is the natural key).
74    RetryAsIdempotent,
75    /// Not safe to retry; re-issuing could repeat the side effect.
76    NoRetry {
77        /// The effect that blocks the retry, for diagnostics.
78        effect: EffectSpec,
79    },
80}
81
82impl RetryDecision {
83    pub fn is_retryable(&self) -> bool {
84        !matches!(self, RetryDecision::NoRetry { .. })
85    }
86}
87
88/// Effect-aware retry policy, reading both the effect and the idempotency
89/// declaration from the plan. Pure and read effects are always retryable.
90/// Writes, deletes, process execution, and network calls are retryable only
91/// when the command declared itself idempotent in the catalog; composites
92/// take the most restrictive answer among their parts.
93///
94/// The declaration is trusted, like every other catalog fact; verifying
95/// that a handler actually deduplicates is the handler author's contract.
96pub fn retry_decision(plan: &InvocationPlan) -> RetryDecision {
97    effect_retry(&plan.effect, plan.idempotent)
98}
99
100fn effect_retry(effect: &EffectSpec, idempotent: bool) -> RetryDecision {
101    match effect {
102        EffectSpec::Pure | EffectSpec::Read => RetryDecision::Retry,
103        EffectSpec::Composite(effects) => {
104            let mut decision = RetryDecision::Retry;
105            for part in effects {
106                match effect_retry(part, idempotent) {
107                    blocked @ RetryDecision::NoRetry { .. } => return blocked,
108                    RetryDecision::RetryAsIdempotent => {
109                        decision = RetryDecision::RetryAsIdempotent;
110                    }
111                    RetryDecision::Retry => {}
112                }
113            }
114            decision
115        }
116        // Write, Delete, Exec, Network, and Custom effects all change
117        // something outside the framework; ambiguous failure means the
118        // change may already have happened.
119        effect => {
120            if idempotent {
121                RetryDecision::RetryAsIdempotent
122            } else {
123                RetryDecision::NoRetry {
124                    effect: effect.clone(),
125                }
126            }
127        }
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134
135    #[test]
136    fn pure_and_read_effects_retry_without_a_declaration() {
137        assert_eq!(effect_retry(&EffectSpec::Pure, false), RetryDecision::Retry);
138        assert_eq!(effect_retry(&EffectSpec::Read, false), RetryDecision::Retry);
139    }
140
141    #[test]
142    fn side_effects_do_not_retry_without_a_declaration() {
143        for effect in [
144            EffectSpec::Write,
145            EffectSpec::Delete,
146            EffectSpec::Exec,
147            EffectSpec::Network,
148            EffectSpec::Custom("sync".to_string()),
149        ] {
150            let decision = effect_retry(&effect, false);
151            assert!(!decision.is_retryable(), "{effect:?} must not retry");
152            assert_eq!(decision, RetryDecision::NoRetry { effect });
153        }
154    }
155
156    #[test]
157    fn side_effects_retry_only_when_declared_idempotent() {
158        for effect in [
159            EffectSpec::Write,
160            EffectSpec::Delete,
161            EffectSpec::Exec,
162            EffectSpec::Network,
163            EffectSpec::Custom("sync".to_string()),
164        ] {
165            assert_eq!(
166                effect_retry(&effect, true),
167                RetryDecision::RetryAsIdempotent,
168                "{effect:?} must retry when declared idempotent"
169            );
170        }
171    }
172
173    #[test]
174    fn composites_take_the_most_restrictive_answer() {
175        let read_write = EffectSpec::Composite(vec![EffectSpec::Read, EffectSpec::Write]);
176        assert_eq!(
177            effect_retry(&read_write, false),
178            RetryDecision::NoRetry {
179                effect: EffectSpec::Write
180            }
181        );
182        assert_eq!(
183            effect_retry(&read_write, true),
184            RetryDecision::RetryAsIdempotent
185        );
186
187        let read_only = EffectSpec::Composite(vec![EffectSpec::Read, EffectSpec::Pure]);
188        assert_eq!(effect_retry(&read_only, false), RetryDecision::Retry);
189    }
190}