Skip to main content

multicast_codemode/
connector.rs

1use std::collections::BTreeMap;
2use std::sync::Arc;
3
4use async_trait::async_trait;
5use multicast::command::RequestContext;
6use multicast::tool::{ToolCallControl, ToolCallOptions, ToolCallOutcome, ToolCatalog};
7use serde::{Deserialize, Serialize};
8use serde_json::Value;
9
10/// Error code a local command returns when its call provably never reached the remote
11/// system, for example because the caller's credential is missing. The run pauses and
12/// the call executes again after resume instead of being reconciled as uncertain.
13pub const CALL_NOT_SENT: &str = "CALL_NOT_SENT";
14
15/// Replay behavior for a connector call.
16#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(rename_all = "snake_case")]
18pub enum ReplayPolicy {
19    /// Record the result and replay it without repeating the call.
20    #[default]
21    Log,
22    /// Re-execute the call during every replay pass.
23    Reexecute,
24}
25
26/// Runtime annotations for one connector method.
27#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
28pub struct ToolAnnotations {
29    /// Whether the method is declared read-only.
30    pub read_only: Option<bool>,
31    /// Whether the method may perform destructive updates.
32    pub destructive: Option<bool>,
33    /// Whether repeated calls have no additional effect.
34    pub idempotent: Option<bool>,
35    /// Whether the method may interact with external entities.
36    pub open_world: Option<bool>,
37}
38
39/// Resolved approval and deterministic replay policy for one method.
40#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
41pub struct ToolPolicy {
42    /// Whether the call must pause for approval.
43    pub requires_approval: bool,
44    /// How the result participates in replay.
45    pub replay: ReplayPolicy,
46}
47
48/// Trust boundary used while resolving tool policy.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum ToolOrigin {
51    /// Metadata declared by the local multicast command graph.
52    Local,
53    /// Metadata received from a remote MCP server.
54    RemoteMcp,
55    /// Metadata inferred from a remote OpenAPI document.
56    OpenApi,
57}
58
59/// Resolves approval and replay behavior from tool metadata.
60pub trait ToolPolicyResolver: Send + Sync {
61    /// Resolves one method's effective policy.
62    fn resolve(&self, origin: ToolOrigin, annotations: &ToolAnnotations) -> ToolPolicy;
63}
64
65/// Conservative default policy resolver.
66#[derive(Debug, Clone, Copy, Default)]
67pub struct DefaultToolPolicyResolver;
68
69impl ToolPolicyResolver for DefaultToolPolicyResolver {
70    fn resolve(&self, origin: ToolOrigin, annotations: &ToolAnnotations) -> ToolPolicy {
71        let safe_local_read = origin == ToolOrigin::Local
72            && annotations.read_only == Some(true)
73            && annotations.destructive != Some(true)
74            && annotations.open_world != Some(true);
75        ToolPolicy {
76            requires_approval: !safe_local_read,
77            replay: if safe_local_read {
78                ReplayPolicy::Reexecute
79            } else {
80                ReplayPolicy::Log
81            },
82        }
83    }
84}
85
86/// One model-facing connector usage example.
87#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
88pub struct ConnectorExample {
89    /// Example invocation.
90    pub command: String,
91    /// Explanation of the example.
92    pub description: Option<String>,
93}
94
95/// Metadata for one connector method.
96#[derive(Debug, Clone, Serialize, Deserialize)]
97pub struct ConnectorTool {
98    /// Method name within its connector namespace.
99    pub name: String,
100    /// Human-readable description.
101    pub description: Option<String>,
102    /// JSON Schema for arguments.
103    pub input_schema: Value,
104    /// JSON Schema for successful output.
105    pub output_schema: Option<Value>,
106    /// Tool-specific model instructions.
107    pub instructions: Option<String>,
108    /// Usage examples.
109    pub examples: Vec<ConnectorExample>,
110    /// Source behavioral annotations.
111    pub annotations: ToolAnnotations,
112    /// Resolved approval and replay behavior.
113    pub policy: ToolPolicy,
114}
115
116/// Model-visible description of a connector.
117#[derive(Debug, Clone, Serialize, Deserialize)]
118pub struct ConnectorDescription {
119    /// JavaScript namespace used in sandbox code.
120    pub name: String,
121    /// Connector-level model guidance.
122    pub instructions: Option<String>,
123    /// Methods exposed by the connector.
124    pub tools: Vec<ConnectorTool>,
125}
126
127/// Maximum host invocations allowed for one call between successful results.
128pub const MAX_CALL_ATTEMPTS: u32 = 8;
129
130/// Opt-in budget for transient connector failures, including the first attempt.
131///
132/// Values are clamped to one through [`MAX_CALL_ATTEMPTS`]. A retry also requires
133/// an explicit [`CallRecovery::Retry`] decision from the connector.
134#[derive(Debug, Clone, Copy)]
135pub struct RetryPolicy {
136    /// Maximum invocations; the durable budget cannot grow after dispatch begins.
137    pub max_attempts: u32,
138}
139
140impl Default for RetryPolicy {
141    fn default() -> Self {
142        Self { max_attempts: 1 }
143    }
144}
145
146/// Identity and durable attempt count of the current connector call.
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
148pub struct CallAttempt {
149    /// Deterministic step sequence within this execution.
150    pub sequence: u64,
151    /// Stable key scoped to the owning execution store; hosts namespace external keys.
152    pub idempotency_key: String,
153    /// Number of host invocations charged before this call, including this attempt.
154    pub attempt: u32,
155}
156
157/// Host reconciliation of a call whose result was not committed locally.
158#[derive(Debug, Clone, PartialEq)]
159pub enum CallRecovery {
160    /// The host cannot establish whether the effect occurred; pause for recovery.
161    Uncertain,
162    /// The host guarantees repeating this key is safe, or proves no effect occurred.
163    Retry,
164    /// The effect already completed; commit this result without repeating it.
165    Applied(Value),
166}
167
168/// Stable execution context passed to connector calls and compensation.
169#[derive(Clone)]
170pub struct ToolContext {
171    /// Current call identity; absent outside connector dispatch.
172    pub call: Option<CallAttempt>,
173    /// Durable execution identifier, stable across replay passes.
174    pub execution_id: String,
175    /// Execution-scoped cancellation and ordered event delivery.
176    pub control: ToolCallControl,
177    /// Transport request metadata inherited by connector calls.
178    pub request: Option<RequestContext>,
179    /// Active pass context propagated through asynchronous executor bridges.
180    pub telemetry_context: multicast::telemetry::opentelemetry::Context,
181}
182
183/// A transport-neutral source of sandbox-callable tools.
184#[async_trait]
185#[allow(
186    clippy::double_must_use,
187    reason = "async_trait annotates generated futures"
188)]
189pub trait Connector: Send + Sync {
190    /// Binds inherited host authority before any prepared child pass may run.
191    /// References in a program cannot supply or expand this authority.
192    async fn admit_child(
193        &self,
194        _parent: &str,
195        _child: &str,
196        _request: Option<&multicast::command::RequestContext>,
197    ) -> Result<(), String> {
198        Ok(())
199    }
200    /// Returns the namespace this connector is bound to.
201    ///
202    /// Separate from [`Connector::describe`] so a namespace can be named without
203    /// being contacted. `describe` reaches the underlying service, so deriving the
204    /// name from it meant every connector had to be connected to before any
205    /// program could be built — including the ones the program never mentions.
206    fn name(&self) -> &str;
207
208    /// Returns connector metadata and schemas.
209    async fn describe(&self) -> Result<ConnectorDescription, String>;
210
211    /// Resolves contextual defaults before replay comparison and dispatch.
212    ///
213    /// The default preserves caller arguments. Implementations must return stable
214    /// values for the same execution context and call sequence.
215    async fn prepare_arguments(
216        &self,
217        _seq: u64,
218        _tool: &ConnectorTool,
219        arguments: Value,
220        _context: &ToolContext,
221    ) -> Result<Value, String> {
222        Ok(arguments)
223    }
224
225    /// Executes one connector method.
226    async fn execute(
227        &self,
228        method: &str,
229        arguments: Value,
230        context: &ToolContext,
231    ) -> Result<Value, String>;
232
233    /// Retry budget for one method. The default invokes a method at most once.
234    fn retry_policy(&self, _method: &str) -> RetryPolicy {
235        RetryPolicy::default()
236    }
237
238    /// Reconciles an interrupted or transiently failed call before any repeat.
239    ///
240    /// Implementations must use the stable key in [`ToolContext::call`] with their
241    /// authoritative effect store or remote idempotency contract. Untrusted remote
242    /// annotations alone do not prove a repeat is safe. This must not repeat the write.
243    async fn recover(
244        &self,
245        _method: &str,
246        _arguments: &Value,
247        _context: &ToolContext,
248    ) -> Result<CallRecovery, String> {
249        Ok(CallRecovery::Uncertain)
250    }
251
252    /// Compensates a previously applied connector action.
253    async fn revert(
254        &self,
255        _method: &str,
256        _arguments: Value,
257        _result: Value,
258        _context: &ToolContext,
259    ) -> Result<bool, String> {
260        Ok(false)
261    }
262
263    /// Releases resources scoped to one sandbox pass.
264    async fn pass_ended(&self, _execution_id: &str, _status: &str) {}
265
266    /// Releases resources scoped to a complete execution.
267    async fn execution_ended(&self, _execution_id: &str, _status: &str) {}
268}
269
270/// Adapts a multicast command graph into one Code Mode connector.
271#[derive(Clone)]
272pub struct MulticastConnector {
273    catalog: ToolCatalog,
274    name: String,
275    instructions: Option<String>,
276    options: ToolCallOptions,
277    policy: Arc<dyn ToolPolicyResolver>,
278    retry: RetryPolicy,
279}
280
281impl MulticastConnector {
282    /// Creates a connector from a resolved multicast tool catalog.
283    pub fn new(catalog: ToolCatalog) -> Self {
284        let name = sanitize_namespace(catalog.name());
285        Self {
286            catalog,
287            name,
288            instructions: None,
289            options: ToolCallOptions::default(),
290            policy: Arc::new(DefaultToolPolicyResolver),
291            retry: RetryPolicy::default(),
292        }
293    }
294
295    /// Overrides the JavaScript namespace exposed to sandbox programs.
296    pub fn with_name(mut self, name: impl Into<String>) -> Self {
297        self.name = name.into();
298        self
299    }
300
301    /// Adds connector-level instructions to model-facing documentation.
302    pub fn with_instructions(mut self, instructions: impl Into<String>) -> Self {
303        self.instructions = Some(instructions.into());
304        self
305    }
306
307    /// Sets the call options shared by every multicast command invocation.
308    pub fn with_call_options(mut self, options: ToolCallOptions) -> Self {
309        self.options = options;
310        self
311    }
312
313    /// Enables bounded transient retries for trusted local read-only or idempotent tools.
314    ///
315    /// Other tools still pause on an uncertain outcome, regardless of this budget.
316    pub fn with_retry_policy(mut self, retry: RetryPolicy) -> Self {
317        self.retry = retry;
318        self
319    }
320
321    /// Overrides policy resolution for local multicast tools.
322    pub fn with_policy_resolver(mut self, resolver: Arc<dyn ToolPolicyResolver>) -> Self {
323        self.policy = resolver;
324        self
325    }
326}
327
328#[async_trait]
329impl Connector for MulticastConnector {
330    fn name(&self) -> &str {
331        &self.name
332    }
333
334    async fn describe(&self) -> Result<ConnectorDescription, String> {
335        Ok(ConnectorDescription {
336            name: self.name.clone(),
337            instructions: self.instructions.clone(),
338            tools: self
339                .catalog
340                .definitions()
341                .into_iter()
342                .map(|tool| {
343                    let annotations = ToolAnnotations {
344                        read_only: tool
345                            .annotations
346                            .as_ref()
347                            .and_then(|annotations| annotations.read_only_hint),
348                        destructive: tool
349                            .annotations
350                            .as_ref()
351                            .and_then(|annotations| annotations.destructive_hint),
352                        idempotent: tool
353                            .annotations
354                            .as_ref()
355                            .and_then(|annotations| annotations.idempotent_hint),
356                        open_world: tool
357                            .annotations
358                            .as_ref()
359                            .and_then(|annotations| annotations.open_world_hint),
360                    };
361                    ConnectorTool {
362                        name: tool.name,
363                        description: (!tool.description.is_empty()).then_some(tool.description),
364                        input_schema: tool.input_schema,
365                        output_schema: tool.output_schema,
366                        instructions: tool.instructions,
367                        examples: tool
368                            .examples
369                            .into_iter()
370                            .map(|example| ConnectorExample {
371                                command: example.command,
372                                description: example.description,
373                            })
374                            .collect(),
375                        policy: self.policy.resolve(ToolOrigin::Local, &annotations),
376                        annotations,
377                    }
378                })
379                .collect(),
380        })
381    }
382
383    fn retry_policy(&self, _method: &str) -> RetryPolicy {
384        self.retry
385    }
386
387    async fn recover(
388        &self,
389        method: &str,
390        _arguments: &Value,
391        _context: &ToolContext,
392    ) -> Result<CallRecovery, String> {
393        let safe = self
394            .catalog
395            .definitions()
396            .iter()
397            .find(|tool| tool.name == method)
398            .and_then(|tool| tool.annotations.as_ref())
399            .is_some_and(|annotations| {
400                annotations.idempotent_hint == Some(true)
401                    || (annotations.read_only_hint == Some(true)
402                        && annotations.destructive_hint != Some(true))
403            });
404        Ok(if safe {
405            CallRecovery::Retry
406        } else {
407            CallRecovery::Uncertain
408        })
409    }
410
411    async fn execute(
412        &self,
413        method: &str,
414        arguments: Value,
415        context: &ToolContext,
416    ) -> Result<Value, String> {
417        let arguments = arguments
418            .as_object()
419            .ok_or_else(|| format!("Arguments to {method} must be an object"))?
420            .iter()
421            .map(|(key, value)| (key.clone(), value.clone()))
422            .collect::<BTreeMap<_, _>>();
423        let mut options = self.options.clone();
424        options.control = context.control.clone();
425        if context.request.is_some() {
426            options.request = context.request.clone();
427        }
428        match self.catalog.call(method, arguments, options).await {
429            ToolCallOutcome::Ok { data, cta } => {
430                if cta.is_some() {
431                    Ok(serde_json::json!({ "data": data, "cta": cta }))
432                } else {
433                    Ok(data)
434                }
435            }
436            ToolCallOutcome::InputRequired {
437                input_requests,
438                request_state,
439                meta,
440            } => Err(serde_json::json!({
441                "code": "MCP_INPUT_REQUIRED",
442                "message": "MCP input is required; Code Mode connectors cannot replay MCP input responses",
443                "retryable": false,
444                "inputRequests": input_requests,
445                "requestState": request_state,
446                "_meta": meta,
447            })
448            .to_string()),
449            ToolCallOutcome::Error {
450                code,
451                message,
452                retryable,
453                field_errors,
454                cta,
455                exit_code,
456            } => Err(serde_json::json!({
457                "suspend": code == CALL_NOT_SENT,
458                "code": code,
459                "message": message,
460                "retryable": retryable,
461                "fieldErrors": field_errors,
462                "cta": cta,
463                "exitCode": exit_code,
464            })
465            .to_string()),
466        }
467    }
468}
469
470/// Validates and normalizes a namespace from a CLI or connector name.
471pub fn sanitize_namespace(value: &str) -> String {
472    let mut result = String::new();
473    for (index, ch) in value.chars().enumerate() {
474        if (index == 0 && !(ch == '_' || ch == '$' || ch.is_ascii_alphabetic()))
475            || (index > 0 && !(ch == '_' || ch == '$' || ch.is_ascii_alphanumeric()))
476        {
477            result.push('_');
478        } else {
479            result.push(ch);
480        }
481    }
482    if result.is_empty() {
483        "tools".to_string()
484    } else {
485        result
486    }
487}
488
489/// MCP tool metadata used by the transport-neutral MCP adapter.
490#[derive(Debug, Clone, Serialize, Deserialize)]
491pub struct McpTool {
492    /// Original MCP tool name.
493    pub name: String,
494    /// Human-readable description.
495    pub description: Option<String>,
496    /// MCP input schema.
497    pub input_schema: Value,
498    /// Optional MCP output schema.
499    pub output_schema: Option<Value>,
500    /// MCP behavioral annotations.
501    pub annotations: Option<multicast::command::McpAnnotations>,
502}
503
504/// Minimal MCP client contract required by Code Mode.
505#[async_trait]
506#[allow(
507    clippy::double_must_use,
508    reason = "async_trait annotates generated futures"
509)]
510pub trait McpClient: Send + Sync {
511    /// Lists tools from the remote MCP server.
512    async fn list_tools(&self) -> Result<Vec<McpTool>, String>;
513
514    /// Calls one remote MCP tool with object arguments.
515    async fn call_tool(&self, name: &str, arguments: Value) -> Result<Value, String>;
516
517    /// Calls one remote MCP tool under an execution-scoped cancellation signal.
518    ///
519    /// The default implementation races [`McpClient::call_tool`] against the
520    /// token. That returns control to Code Mode promptly, but it cannot stop
521    /// work the peer has already accepted. An implementation backed by a real
522    /// MCP transport should override this to also inform the peer, so a
523    /// cancelled pass does not leave a downstream request running.
524    async fn call_tool_cancellable(
525        &self,
526        name: &str,
527        arguments: Value,
528        cancellation: &tokio_util::sync::CancellationToken,
529    ) -> Result<Value, String> {
530        tokio::select! {
531            biased;
532            () = cancellation.cancelled() => Err("Call cancelled".to_string()),
533            result = self.call_tool(name, arguments) => result,
534        }
535    }
536}
537
538/// Exposes a remote MCP connection as a Code Mode connector.
539pub struct McpConnector {
540    name: String,
541    instructions: Option<String>,
542    client: Arc<dyn McpClient>,
543    tools: tokio::sync::OnceCell<Vec<(String, McpTool)>>,
544    policy: Arc<dyn ToolPolicyResolver>,
545}
546
547impl McpConnector {
548    /// Creates an MCP-backed connector.
549    pub fn new(name: impl Into<String>, client: Arc<dyn McpClient>) -> Self {
550        Self {
551            name: name.into(),
552            instructions: None,
553            client,
554            tools: tokio::sync::OnceCell::new(),
555            policy: Arc::new(DefaultToolPolicyResolver),
556        }
557    }
558
559    /// Adds server-level model instructions.
560    pub fn with_instructions(mut self, instructions: impl Into<String>) -> Self {
561        self.instructions = Some(instructions.into());
562        self
563    }
564
565    /// Overrides policy resolution for remote MCP tools.
566    pub fn with_policy_resolver(mut self, resolver: Arc<dyn ToolPolicyResolver>) -> Self {
567        self.policy = resolver;
568        self
569    }
570
571    async fn tools(&self) -> Result<&Vec<(String, McpTool)>, String> {
572        self.tools
573            .get_or_try_init(|| async {
574                let mut names = BTreeMap::new();
575                let mut tools = Vec::new();
576                for tool in self.client.list_tools().await? {
577                    let name = sanitize_namespace(&tool.name);
578                    if let Some(existing) = names.insert(name.clone(), tool.name.clone()) {
579                        return Err(format!(
580                            "MCP tools \"{existing}\" and \"{}\" both map to \"{name}\"",
581                            tool.name
582                        ));
583                    }
584                    tools.push((name, tool));
585                }
586                Ok(tools)
587            })
588            .await
589    }
590}
591
592#[async_trait]
593impl Connector for McpConnector {
594    fn name(&self) -> &str {
595        &self.name
596    }
597
598    async fn describe(&self) -> Result<ConnectorDescription, String> {
599        Ok(ConnectorDescription {
600            name: self.name.clone(),
601            instructions: self.instructions.clone(),
602            tools: self
603                .tools()
604                .await?
605                .iter()
606                .map(|(name, tool)| {
607                    let annotations = ToolAnnotations {
608                        read_only: tool
609                            .annotations
610                            .as_ref()
611                            .and_then(|annotations| annotations.read_only_hint),
612                        destructive: tool
613                            .annotations
614                            .as_ref()
615                            .and_then(|annotations| annotations.destructive_hint),
616                        idempotent: tool
617                            .annotations
618                            .as_ref()
619                            .and_then(|annotations| annotations.idempotent_hint),
620                        open_world: tool
621                            .annotations
622                            .as_ref()
623                            .and_then(|annotations| annotations.open_world_hint),
624                    };
625                    ConnectorTool {
626                        name: name.clone(),
627                        description: tool.description.clone(),
628                        input_schema: tool.input_schema.clone(),
629                        output_schema: tool.output_schema.clone(),
630                        instructions: None,
631                        examples: Vec::new(),
632                        policy: self.policy.resolve(ToolOrigin::RemoteMcp, &annotations),
633                        annotations,
634                    }
635                })
636                .collect(),
637        })
638    }
639
640    async fn execute(
641        &self,
642        method: &str,
643        arguments: Value,
644        context: &ToolContext,
645    ) -> Result<Value, String> {
646        let (_, tool) = self
647            .tools()
648            .await?
649            .iter()
650            .find(|(name, _)| name == method)
651            .ok_or_else(|| format!("Tool \"{method}\" not found on {}", self.name))?;
652        self.client
653            .call_tool_cancellable(&tool.name, arguments, &context.control.cancellation)
654            .await
655    }
656}
657
658/// Authenticated request derived from an OpenAPI operation.
659#[derive(Debug, Clone, Serialize, Deserialize)]
660pub struct OpenApiRequest {
661    /// Path or URL with path parameters substituted.
662    pub path: String,
663    /// HTTP method.
664    pub method: String,
665    /// Query parameters.
666    pub parameters: BTreeMap<String, Value>,
667    /// Optional request body.
668    pub body: Option<Value>,
669    /// Request headers derived from header parameters.
670    pub headers: BTreeMap<String, String>,
671}
672
673/// Host operations required by the OpenAPI connector.
674#[async_trait]
675#[allow(
676    clippy::double_must_use,
677    reason = "async_trait annotates generated futures"
678)]
679pub trait OpenApiClient: Send + Sync {
680    /// Returns the OpenAPI document.
681    async fn specification(&self) -> Result<Value, String>;
682
683    /// Executes an authenticated request.
684    async fn request(&self, request: OpenApiRequest) -> Result<Value, String>;
685}
686
687#[derive(Clone)]
688struct OpenApiOperation {
689    name: String,
690    method: String,
691    path: String,
692    description: String,
693    input_schema: Value,
694    parameters: Vec<(String, String)>,
695}
696
697/// Derives typed Code Mode tools from an OpenAPI document.
698pub struct OpenApiConnector {
699    name: String,
700    instructions: Option<String>,
701    client: Arc<dyn OpenApiClient>,
702    operations: tokio::sync::OnceCell<Vec<OpenApiOperation>>,
703    policy: Arc<dyn ToolPolicyResolver>,
704}
705
706impl OpenApiConnector {
707    /// Creates an OpenAPI-backed connector.
708    pub fn new(name: impl Into<String>, client: Arc<dyn OpenApiClient>) -> Self {
709        Self {
710            name: name.into(),
711            instructions: None,
712            client,
713            operations: tokio::sync::OnceCell::new(),
714            policy: Arc::new(DefaultToolPolicyResolver),
715        }
716    }
717
718    /// Adds API-level model instructions.
719    pub fn with_instructions(mut self, instructions: impl Into<String>) -> Self {
720        self.instructions = Some(instructions.into());
721        self
722    }
723
724    /// Overrides policy resolution for OpenAPI tools.
725    pub fn with_policy_resolver(mut self, resolver: Arc<dyn ToolPolicyResolver>) -> Self {
726        self.policy = resolver;
727        self
728    }
729
730    async fn operations(&self) -> Result<&Vec<OpenApiOperation>, String> {
731        self.operations
732            .get_or_try_init(|| async {
733                derive_openapi_operations(&self.client.specification().await?)
734            })
735            .await
736    }
737}
738
739#[async_trait]
740impl Connector for OpenApiConnector {
741    fn name(&self) -> &str {
742        &self.name
743    }
744
745    async fn describe(&self) -> Result<ConnectorDescription, String> {
746        let mut tools = vec![ConnectorTool {
747            name: "request".to_string(),
748            description: Some(
749                "Perform an authenticated request when no derived operation fits.".to_string(),
750            ),
751            input_schema: serde_json::json!({
752                "type": "object",
753                "properties": {
754                    "path": {"type": "string"},
755                    "method": {"type": "string"},
756                    "parameters": {"type": "object", "additionalProperties": true},
757                    "body": {},
758                    "headers": {"type": "object", "additionalProperties": {"type": "string"}}
759                },
760                "required": ["path"]
761            }),
762            output_schema: None,
763            instructions: None,
764            examples: Vec::new(),
765            annotations: ToolAnnotations {
766                open_world: Some(true),
767                ..ToolAnnotations::default()
768            },
769            policy: ToolPolicy {
770                requires_approval: true,
771                replay: ReplayPolicy::Log,
772            },
773        }];
774        tools.extend(self.operations().await?.iter().map(|operation| {
775            let annotations = ToolAnnotations {
776                read_only: Some(operation.method == "get" || operation.method == "head"),
777                open_world: Some(true),
778                ..ToolAnnotations::default()
779            };
780            ConnectorTool {
781                name: operation.name.clone(),
782                description: Some(operation.description.clone()),
783                input_schema: operation.input_schema.clone(),
784                output_schema: None,
785                instructions: None,
786                examples: Vec::new(),
787                policy: self.policy.resolve(ToolOrigin::OpenApi, &annotations),
788                annotations,
789            }
790        }));
791        Ok(ConnectorDescription {
792            name: self.name.clone(),
793            instructions: self.instructions.clone(),
794            tools,
795        })
796    }
797
798    async fn execute(
799        &self,
800        method: &str,
801        arguments: Value,
802        _context: &ToolContext,
803    ) -> Result<Value, String> {
804        if method == "request" {
805            return self.client.request(parse_raw_request(arguments)?).await;
806        }
807        let operation = self
808            .operations()
809            .await?
810            .iter()
811            .find(|operation| operation.name == method)
812            .ok_or_else(|| format!("Tool \"{method}\" not found on {}", self.name))?;
813        self.client
814            .request(operation_request(operation, arguments)?)
815            .await
816    }
817}
818
819fn derive_openapi_operations(document: &Value) -> Result<Vec<OpenApiOperation>, String> {
820    let Some(paths) = document.get("paths").and_then(Value::as_object) else {
821        return Ok(Vec::new());
822    };
823    let mut used = BTreeMap::new();
824    let mut operations = Vec::new();
825    for (path, item) in paths {
826        let Some(item) = item.as_object() else {
827            continue;
828        };
829        for method in ["get", "put", "post", "delete", "patch", "options", "head"] {
830            let Some(operation) = item.get(method).and_then(Value::as_object) else {
831                continue;
832            };
833            let source_name = operation
834                .get("operationId")
835                .and_then(Value::as_str)
836                .map(str::to_string)
837                .unwrap_or_else(|| format!("{method}_{path}"));
838            let name = sanitize_namespace(&source_name);
839            if name == "request" || name == "spec" || used.insert(name.clone(), path).is_some() {
840                continue;
841            }
842            let mut properties = serde_json::Map::new();
843            let mut required = Vec::new();
844            let mut parameters = Vec::new();
845            for parameter in operation
846                .get("parameters")
847                .and_then(Value::as_array)
848                .into_iter()
849                .flatten()
850            {
851                let Some(parameter) = parameter.as_object() else {
852                    continue;
853                };
854                let Some(parameter_name) = parameter.get("name").and_then(Value::as_str) else {
855                    continue;
856                };
857                let location = parameter
858                    .get("in")
859                    .and_then(Value::as_str)
860                    .unwrap_or("query");
861                properties.insert(
862                    parameter_name.to_string(),
863                    parameter
864                        .get("schema")
865                        .cloned()
866                        .unwrap_or_else(|| serde_json::json!({})),
867                );
868                parameters.push((parameter_name.to_string(), location.to_string()));
869                if parameter.get("required").and_then(Value::as_bool) == Some(true) {
870                    required.push(Value::String(parameter_name.to_string()));
871                }
872            }
873            if let Some(body) = operation
874                .get("requestBody")
875                .and_then(|value| value.get("content"))
876                .and_then(|value| value.get("application/json"))
877                .and_then(|value| value.get("schema"))
878                .cloned()
879            {
880                properties.insert("body".to_string(), body);
881                if operation
882                    .get("requestBody")
883                    .and_then(|value| value.get("required"))
884                    .and_then(Value::as_bool)
885                    == Some(true)
886                {
887                    required.push(Value::String("body".to_string()));
888                }
889            }
890            operations.push(OpenApiOperation {
891                name,
892                method: method.to_string(),
893                path: path.clone(),
894                description: operation
895                    .get("summary")
896                    .or_else(|| operation.get("description"))
897                    .and_then(Value::as_str)
898                    .map(str::to_string)
899                    .unwrap_or_else(|| format!("{} {path}", method.to_ascii_uppercase())),
900                input_schema: serde_json::json!({
901                    "type": "object",
902                    "properties": properties,
903                    "required": required,
904                }),
905                parameters,
906            });
907        }
908    }
909    Ok(operations)
910}
911
912fn operation_request(
913    operation: &OpenApiOperation,
914    arguments: Value,
915) -> Result<OpenApiRequest, String> {
916    let input = arguments
917        .as_object()
918        .ok_or_else(|| format!("Arguments to {} must be an object", operation.name))?;
919    let mut path = operation.path.clone();
920    let mut parameters = BTreeMap::new();
921    let mut headers = BTreeMap::new();
922    for (name, location) in &operation.parameters {
923        let Some(value) = input.get(name) else {
924            continue;
925        };
926        match location.as_str() {
927            "path" => {
928                path = path.replace(
929                    &format!("{{{name}}}"),
930                    value.as_str().unwrap_or(&value.to_string()),
931                )
932            }
933            "header" => {
934                headers.insert(
935                    name.clone(),
936                    value
937                        .as_str()
938                        .map(str::to_string)
939                        .unwrap_or_else(|| value.to_string()),
940                );
941            }
942            "query" => {
943                parameters.insert(name.clone(), value.clone());
944            }
945            _ => {}
946        }
947    }
948    Ok(OpenApiRequest {
949        path,
950        method: operation.method.clone(),
951        parameters,
952        body: input.get("body").cloned(),
953        headers,
954    })
955}
956
957fn parse_raw_request(arguments: Value) -> Result<OpenApiRequest, String> {
958    let input = arguments
959        .as_object()
960        .ok_or_else(|| "Arguments to request must be an object".to_string())?;
961    Ok(OpenApiRequest {
962        path: input
963            .get("path")
964            .and_then(Value::as_str)
965            .ok_or_else(|| "request.path is required".to_string())?
966            .to_string(),
967        method: input
968            .get("method")
969            .and_then(Value::as_str)
970            .unwrap_or("GET")
971            .to_string(),
972        parameters: object_map(input.get("parameters")),
973        body: input.get("body").cloned(),
974        headers: input
975            .get("headers")
976            .and_then(Value::as_object)
977            .into_iter()
978            .flatten()
979            .map(|(key, value)| {
980                (
981                    key.clone(),
982                    value
983                        .as_str()
984                        .map(str::to_string)
985                        .unwrap_or_else(|| value.to_string()),
986                )
987            })
988            .collect(),
989    })
990}
991
992fn object_map(value: Option<&Value>) -> BTreeMap<String, Value> {
993    value
994        .and_then(Value::as_object)
995        .into_iter()
996        .flatten()
997        .map(|(key, value)| (key.clone(), value.clone()))
998        .collect()
999}
1000
1001#[cfg(test)]
1002mod policy_tests {
1003    use super::*;
1004
1005    #[test]
1006    fn only_safe_local_reads_skip_approval() {
1007        let resolver = DefaultToolPolicyResolver;
1008        let read = ToolAnnotations {
1009            read_only: Some(true),
1010            ..ToolAnnotations::default()
1011        };
1012        assert_eq!(
1013            resolver.resolve(ToolOrigin::Local, &read),
1014            ToolPolicy {
1015                requires_approval: false,
1016                replay: ReplayPolicy::Reexecute,
1017            }
1018        );
1019        assert!(
1020            resolver
1021                .resolve(ToolOrigin::RemoteMcp, &read)
1022                .requires_approval
1023        );
1024        assert!(
1025            resolver
1026                .resolve(
1027                    ToolOrigin::Local,
1028                    &ToolAnnotations {
1029                        open_world: Some(true),
1030                        ..read
1031                    }
1032                )
1033                .requires_approval
1034        );
1035    }
1036}
1037
1038#[cfg(test)]
1039mod mcp_tests {
1040    use std::sync::Arc;
1041    use std::sync::atomic::{AtomicUsize, Ordering};
1042
1043    use async_trait::async_trait;
1044    use multicast::tool::ToolCallControl;
1045    use serde_json::{Value, json};
1046
1047    use super::{Connector, McpClient, McpConnector, McpTool, ToolContext};
1048
1049    /// A client implementing only the two required methods.
1050    ///
1051    /// It deliberately does not override `call_tool_cancellable`, so these
1052    /// tests exercise the default implementation and prove the added method is
1053    /// not a breaking change for an existing implementation.
1054    struct HangingClient {
1055        started: Arc<AtomicUsize>,
1056    }
1057
1058    #[async_trait]
1059    impl McpClient for HangingClient {
1060        async fn list_tools(&self) -> Result<Vec<McpTool>, String> {
1061            Ok(vec![McpTool {
1062                name: "wait".to_string(),
1063                description: None,
1064                input_schema: json!({"type": "object"}),
1065                output_schema: None,
1066                annotations: None,
1067            }])
1068        }
1069
1070        async fn call_tool(&self, _name: &str, _arguments: Value) -> Result<Value, String> {
1071            self.started.fetch_add(1, Ordering::SeqCst);
1072            // Never resolves; only cancellation can end this call.
1073            std::future::pending::<()>().await;
1074            unreachable!("pending future resolved")
1075        }
1076    }
1077
1078    fn context(control: ToolCallControl) -> ToolContext {
1079        ToolContext {
1080            call: None,
1081            execution_id: "exec_test".to_string(),
1082            control,
1083            request: None,
1084            telemetry_context: multicast::telemetry::opentelemetry::Context::current(),
1085        }
1086    }
1087
1088    #[tokio::test]
1089    async fn cancellation_reaches_a_client_that_only_implements_call_tool() {
1090        let started = Arc::new(AtomicUsize::new(0));
1091        let connector = McpConnector::new(
1092            "hang",
1093            Arc::new(HangingClient {
1094                started: Arc::clone(&started),
1095            }),
1096        );
1097        let control = ToolCallControl::default();
1098        let cancellation = control.cancellation.clone();
1099
1100        // Cancel once the call is demonstrably in flight, so this asserts
1101        // cancellation of an active call rather than a pre-invocation check.
1102        let started_probe = Arc::clone(&started);
1103        tokio::spawn(async move {
1104            while started_probe.load(Ordering::SeqCst) == 0 {
1105                tokio::task::yield_now().await;
1106            }
1107            cancellation.cancel();
1108        });
1109
1110        let result = connector
1111            .execute("wait", json!({}), &context(control))
1112            .await;
1113
1114        assert_eq!(started.load(Ordering::SeqCst), 1, "the call never started");
1115        assert_eq!(result, Err("Call cancelled".to_string()));
1116    }
1117
1118    #[tokio::test]
1119    async fn an_uncancelled_call_is_unaffected() {
1120        struct Echo;
1121
1122        #[async_trait]
1123        impl McpClient for Echo {
1124            async fn list_tools(&self) -> Result<Vec<McpTool>, String> {
1125                Ok(vec![McpTool {
1126                    name: "echo".to_string(),
1127                    description: None,
1128                    input_schema: json!({"type": "object"}),
1129                    output_schema: None,
1130                    annotations: None,
1131                }])
1132            }
1133
1134            async fn call_tool(&self, _name: &str, arguments: Value) -> Result<Value, String> {
1135                Ok(arguments)
1136            }
1137        }
1138
1139        let connector = McpConnector::new("echo", Arc::new(Echo));
1140        let result = connector
1141            .execute(
1142                "echo",
1143                json!({"v": 1}),
1144                &context(ToolCallControl::default()),
1145            )
1146            .await;
1147
1148        assert_eq!(result, Ok(json!({"v": 1})));
1149    }
1150
1151    #[tokio::test]
1152    async fn a_command_that_never_sent_its_call_asks_the_run_to_suspend() {
1153        use multicast::cli::Cli;
1154        use multicast::command::{CommandContext, CommandDef, CommandHandler};
1155        use multicast::output::CommandResult;
1156        struct Unsent;
1157        #[async_trait]
1158        impl CommandHandler for Unsent {
1159            async fn run(&self, _: CommandContext) -> CommandResult {
1160                CommandResult::Error {
1161                    code: super::CALL_NOT_SENT.into(),
1162                    message: "Reconnect linear".into(),
1163                    retryable: false,
1164                    exit_code: None,
1165                    cta: None,
1166                }
1167            }
1168        }
1169        let cli = Cli::create("app").command("write", CommandDef::build("write", Unsent).done());
1170        let connector = super::MulticastConnector::new(cli.tool_catalog());
1171        let error = connector
1172            .execute("write", json!({}), &context(ToolCallControl::default()))
1173            .await
1174            .unwrap_err();
1175        let error: Value = serde_json::from_str(&error).unwrap();
1176        assert_eq!(error["suspend"], json!(true));
1177        assert_eq!(error["message"], json!("Reconnect linear"));
1178    }
1179}