Skip to main content

objectiveai_mcp_proxy/
reverse_channel.rs

1//! WS reverse-channel transport for CLI-hosted upstreams.
2//!
3//! When the proxy is embedded in the API (per request), it is handed a
4//! [`ReverseChannel`] — the means to speak the `client_objectiveai_mcp`
5//! protocol over the request's WebSocket. Upstreams whose URL scheme is
6//! `ws` ([`WsUpstream`]) are reached through it instead of over HTTP:
7//!
8//! - `ws://objectiveai` → [`McpKind::ObjectiveAi`]
9//! - `ws:///owner/name/version/mcp` → [`McpKind::Plugin`]
10//!
11//! Direction split (the API owns the WS itself):
12//! - **send**: the proxy emits a `server_request::Request` into the
13//!   channel's mpsc; the API serializes it onto the shared WS sink.
14//! - **recv**: the API's recv loop demuxes incoming frames by type and
15//!   hands the proxy-bound ones back via [`ReverseChannel::deliver_response`]
16//!   (the 6 MCP `server_response` variants) and
17//!   [`ReverseChannel::deliver_client_request`] (`McpListChanged`). The
18//!   proxy correlates responses to its own outstanding requests by id.
19//!
20//! [`Upstream`] is the proxy's per-upstream handle — either an HTTP
21//! [`Connection`] or a [`WsUpstream`] — exposing the slice of the
22//! `Connection` interface the [`crate::session::Session`] depends on.
23
24use std::sync::{Arc, OnceLock};
25use std::time::Duration;
26
27use dashmap::DashMap;
28use indexmap::IndexMap;
29use objectiveai_sdk::client_objectiveai_mcp::{
30    McpKind,
31    client_request::{self, McpListChangedKind},
32    client_response,
33    server_request::{self, InitializeRequest, Request as ServerRequest},
34    server_response::{self, JsonRpcResult, Response as ServerResponse},
35};
36use objectiveai_sdk::mcp::resource::{
37    ListResourcesRequest, ReadResourceRequestParams, ReadResourceResult, Resource,
38};
39use objectiveai_sdk::mcp::tool::{
40    CallToolRequestParams, CallToolResult, ListToolsRequest, Tool,
41};
42use objectiveai_sdk::mcp::{Connection, Error as McpError};
43use tokio::sync::{RwLock, mpsc, oneshot};
44
45use crate::session::Session;
46use crate::session_manager::SessionManager;
47
48/// A list-changed callback (mirrors `Connection::set_on_*_list_changed`).
49type ListChangedCb = Arc<dyn Fn() + Send + Sync>;
50
51struct Inner {
52    /// proxy → API → WS. The API drains the paired receiver and writes
53    /// each request onto the shared WS sink.
54    tx: mpsc::UnboundedSender<ServerRequest>,
55    /// Outstanding requests awaiting their `server_response`, by id.
56    pending: DashMap<String, oneshot::Sender<ServerResponse>>,
57    /// Per-upstream round-trip budget.
58    timeout: Duration,
59    /// list-changed callbacks per upstream `McpKind`: `(tools, resources)`.
60    /// Fired when a matching `client_request::McpListChanged` arrives.
61    list_changed: DashMap<McpKind, (Option<ListChangedCb>, Option<ListChangedCb>)>,
62    /// Session registry, late-bound by [`ReverseChannel::wire_sessions`]
63    /// in `setup` (the channel is built before the proxy's
64    /// `SessionManager` exists). Lets inbound `client_request`s
65    /// (`ListTools`/`CallTool`/`ListResources`/`ReadResource`) run the
66    /// proxy's aggregated MCP ops by `response_id`.
67    sessions: OnceLock<Arc<SessionManager>>,
68}
69
70/// Cheaply-cloneable handle the proxy uses to speak over the WS.
71#[derive(Clone)]
72pub struct ReverseChannel(Arc<Inner>);
73
74impl std::fmt::Debug for ReverseChannel {
75    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76        f.debug_struct("ReverseChannel").finish_non_exhaustive()
77    }
78}
79
80impl ReverseChannel {
81    /// Build a channel. Returns the channel plus the receiver the API
82    /// drains (serializing each `server_request` onto the shared WS sink).
83    pub fn new(timeout: Duration) -> (Self, mpsc::UnboundedReceiver<ServerRequest>) {
84        let (tx, rx) = mpsc::unbounded_channel();
85        let inner = Inner {
86            tx,
87            pending: DashMap::new(),
88            timeout,
89            list_changed: DashMap::new(),
90            sessions: OnceLock::new(),
91        };
92        (Self(Arc::new(inner)), rx)
93    }
94
95    /// Late-bind the proxy's session registry so inbound MCP-op
96    /// `client_request`s can resolve a session by `response_id`. Called
97    /// once by `setup` (idempotent — first write wins).
98    pub(crate) fn wire_sessions(&self, sessions: Arc<SessionManager>) {
99        let _ = self.0.sessions.set(sessions);
100    }
101
102    /// Resolve a session for an inbound MCP-op `client_request`. Returns
103    /// a `(code, message)` error suitable for a `JsonRpcResult::Err` when
104    /// sessions aren't wired or no session exists for `response_id`.
105    fn lookup_session(&self, response_id: &str) -> Result<Arc<Session>, (i64, String)> {
106        let sessions = self
107            .0
108            .sessions
109            .get()
110            .ok_or((-32603i64, "proxy sessions not wired".to_string()))?;
111        sessions
112            .get(response_id)
113            .ok_or_else(|| (-32001i64, format!("unknown session for response id {response_id:?}")))
114    }
115
116    /// Emit a `server_request` and await its matching `server_response`,
117    /// bounded by the configured timeout. `id` is minted here; the API's
118    /// recv loop routes the reply back via [`Self::deliver_response`].
119    async fn request(
120        &self,
121        payload: server_request::Payload,
122        headers: IndexMap<String, String>,
123    ) -> Result<ServerResponse, McpError> {
124        let id = uuid::Uuid::new_v4().to_string();
125        let (resp_tx, resp_rx) = oneshot::channel();
126        self.0.pending.insert(id.clone(), resp_tx);
127        let request = ServerRequest {
128            id: id.clone(),
129            headers,
130            payload,
131        };
132        if self.0.tx.send(request).is_err() {
133            self.0.pending.remove(&id);
134            return Err(transport_error("reverse channel closed before send"));
135        }
136        match tokio::time::timeout(self.0.timeout, resp_rx).await {
137            Ok(Ok(response)) => Ok(response),
138            Ok(Err(_)) => {
139                self.0.pending.remove(&id);
140                Err(transport_error("reverse channel dropped before response"))
141            }
142            Err(_) => {
143                self.0.pending.remove(&id);
144                Err(transport_error("reverse channel timed out waiting for response"))
145            }
146        }
147    }
148
149    /// Best-effort `Drop` server-request for `response_id`: tells the CLI
150    /// to tear down the whole response-id bucket (connections + plugin
151    /// subprocesses). The reply (`DropResult`) is discarded; transport
152    /// errors / timeouts are ignored — teardown is fire-and-forget.
153    pub(crate) async fn drop_response(&self, response_id: String) {
154        let _ = self
155            .request(
156                server_request::Payload::Drop(server_request::DropRequest { response_id }),
157                IndexMap::new(),
158            )
159            .await;
160    }
161
162    /// Stream a file/folder from one laboratory to another. The conduit
163    /// splices the source laboratory's `/export` straight into the
164    /// destination's `/import`; both laboratories are on the same conduit,
165    /// so this rides the session's reverse channel like any other op.
166    pub async fn transfer_laboratories(
167        &self,
168        source_id: String,
169        dest_id: String,
170        source_path: String,
171        dest_path: String,
172    ) -> Result<server_response::LaboratoryTransferResult, McpError> {
173        let response = self
174            .request(
175                server_request::Payload::LaboratoryTransfer(
176                    server_request::LaboratoryTransferRequest {
177                        source_id,
178                        dest_id,
179                        source_path,
180                        dest_path,
181                    },
182                ),
183                IndexMap::new(),
184            )
185            .await?;
186        match response.payload {
187            server_response::Payload::LaboratoryTransfer(result) => {
188                unwrap_rpc("laboratory_transfer", result)
189            }
190            other => Err(variant_mismatch(
191                "laboratory_transfer",
192                "laboratory_transfer",
193                &other,
194            )),
195        }
196    }
197
198    /// Hand a proxy-bound `server_response` (one of the 6 MCP variants)
199    /// back to the waiter that issued the matching request. Called by the
200    /// API's recv loop. Unknown id → dropped.
201    pub fn deliver_response(&self, response: ServerResponse) {
202        if let Some((_, tx)) = self.0.pending.remove(&response.id) {
203            let _ = tx.send(response);
204        }
205    }
206
207    /// Hand a proxy-bound `client_request` to the proxy.
208    ///
209    /// `McpListChanged` fires the registered list-changed callback for the
210    /// upstream. The MCP-op variants (`ListTools`/`CallTool`/
211    /// `ListResources`/`ReadResource`) resolve the session by
212    /// `response_id` and run the SAME shared [`crate::session::Session`]
213    /// code the HTTP endpoints use — fanning out / routing exactly as
214    /// `mcp::handle_tools_list` etc. — returning the normal MCP result.
215    /// NOTE: the `CallTool` path deliberately does NOT consult the queue
216    /// delegate (that splice is only for the regular HTTP `tools/call`).
217    /// Returns the ack/result the API writes back over the WS.
218    pub async fn deliver_client_request(
219        &self,
220        request: client_request::Request,
221    ) -> client_response::Response {
222        let client_request::Request { id, payload } = request;
223        match payload {
224            client_request::Payload::McpListChanged(change) => {
225                if let Some(cbs) = self.0.list_changed.get(&change.mcp_kind) {
226                    let cb = match change.kind {
227                        McpListChangedKind::Tools => cbs.0.clone(),
228                        McpListChangedKind::Resources => cbs.1.clone(),
229                    };
230                    drop(cbs);
231                    if let Some(cb) = cb {
232                        cb();
233                    }
234                }
235                client_response::Response::Ok { id }
236            }
237            // List params (cursor) are ignored, matching the HTTP
238            // `handle_tools_list` which fans out to every upstream.
239            // List params (cursor) are ignored, matching the HTTP
240            // `handle_tools_list`; `name`, when set, scopes the fan-out to
241            // the single server with that routing prefix.
242            client_request::Payload::ListTools {
243                response_id, name, ..
244            } => {
245                let result = match self.lookup_session(&response_id) {
246                    Ok(session) => {
247                        match session.list_tools_filtered(None, name.as_deref()).await {
248                            Ok(result) => JsonRpcResult::Ok { result },
249                            Err(e) => rpc_err_result(-32603, format!("list_tools: {e}")),
250                        }
251                    }
252                    Err((code, message)) => rpc_err_result(code, message),
253                };
254                client_response::Response::ListTools { id, result }
255            }
256            client_request::Payload::ListResources {
257                response_id, name, ..
258            } => {
259                let result = match self.lookup_session(&response_id) {
260                    Ok(session) => {
261                        match session.list_resources_filtered(None, name.as_deref()).await {
262                            Ok(result) => JsonRpcResult::Ok { result },
263                            Err(e) => rpc_err_result(-32603, format!("list_resources: {e}")),
264                        }
265                    }
266                    Err((code, message)) => rpc_err_result(code, message),
267                };
268                client_response::Response::ListResources { id, result }
269            }
270            client_request::Payload::ListServers { response_id } => {
271                let result = match self.lookup_session(&response_id) {
272                    // Proxy-local aggregate — no upstream fan-out, can't fail.
273                    Ok(session) => JsonRpcResult::Ok {
274                        result: session.list_servers(),
275                    },
276                    Err((code, message)) => rpc_err_result(code, message),
277                };
278                client_response::Response::ListServers { id, result }
279            }
280            client_request::Payload::CallTool { response_id, params } => {
281                let result = match self.lookup_session(&response_id) {
282                    // No queue delegate here — unlike the HTTP path, this
283                    // returns the upstream tool result verbatim.
284                    Ok(session) => match session.call_tool(&params).await {
285                        Ok(result) => JsonRpcResult::Ok { result },
286                        Err(crate::session::CallToolError::ToolNotFound(name)) => {
287                            rpc_err_result(-32601, format!("tool not found: {name}"))
288                        }
289                        Err(crate::session::CallToolError::Upstream(e)) => {
290                            rpc_err_result(-32603, format!("upstream call_tool: {e}"))
291                        }
292                    },
293                    Err((code, message)) => rpc_err_result(code, message),
294                };
295                client_response::Response::CallTool { id, result }
296            }
297            client_request::Payload::ReadResource { response_id, params } => {
298                let result = match self.lookup_session(&response_id) {
299                    Ok(session) => match session.read_resource(&params.uri).await {
300                        Ok(result) => JsonRpcResult::Ok { result },
301                        Err(crate::session::ReadResourceError::ResourceNotFound(uri)) => {
302                            rpc_err_result(-32602, format!("resource not found: {uri}"))
303                        }
304                        Err(crate::session::ReadResourceError::Upstream(e)) => {
305                            rpc_err_result(-32603, format!("upstream read_resource: {e}"))
306                        }
307                    },
308                    Err((code, message)) => rpc_err_result(code, message),
309                };
310                client_response::Response::ReadResource { id, result }
311            }
312        }
313    }
314
315    fn set_tools_list_changed(&self, mcp_kind: McpKind, cb: ListChangedCb) {
316        let mut entry = self.0.list_changed.entry(mcp_kind).or_default();
317        entry.0 = Some(cb);
318    }
319
320    fn set_resources_list_changed(&self, mcp_kind: McpKind, cb: ListChangedCb) {
321        let mut entry = self.0.list_changed.entry(mcp_kind).or_default();
322        entry.1 = Some(cb);
323    }
324}
325
326/// A `ws://`-scheme upstream, reached over the [`ReverseChannel`]. Mirrors
327/// the slice of [`Connection`]'s interface the [`crate::session::Session`]
328/// uses, translating each op into a `server_request` carrying this
329/// upstream's [`McpKind`].
330pub struct WsUpstream {
331    channel: ReverseChannel,
332    mcp_kind: McpKind,
333    /// The `ws://…` URL this upstream was dialed with (used for filtering).
334    pub url: String,
335    /// Upstream `Mcp-Session-Id` returned by the CLI on `initialize`.
336    pub session_id: String,
337    /// Upstream `server_info.name` / `.version` from the `initialize`
338    /// reply — feeds the session's routing-prefix derivation.
339    server_name: String,
340    server_version: String,
341    /// The upstream's full `initialize` reply (capabilities, server_info,
342    /// instructions, protocol version) — kept verbatim so `servers/list`
343    /// can report it. `Connection` exposes the same via its own
344    /// `initialize_result`.
345    initialize_result: objectiveai_sdk::mcp::initialize_result::InitializeResult,
346    /// Typed laboratory identity from the explicit `X-MCP-Laboratories`
347    /// marker — the authoritative "this upstream is a laboratory" signal,
348    /// `None` for non-laboratory upstreams. Never derived from the URL.
349    laboratory: Option<objectiveai_sdk::laboratories::Laboratory>,
350    /// Whether the upstream advertised the `tools` / `resources`
351    /// capability in its `initialize` reply. We must NOT issue
352    /// `tools/list` / `resources/list` against an upstream that didn't
353    /// advertise the capability: many servers (incl. the test
354    /// fixtures) 404 the un-advertised method, and a hard error there
355    /// fails the whole aggregate — and, on the post-init health probe,
356    /// fails the connect and churns endless re-`initialize`s. Mirrors
357    /// `mcp::Connection::has_{tools,resources}_cap`.
358    has_tools_cap: bool,
359    has_resources_cap: bool,
360    /// Persistent per-upstream headers captured at connect: the per-URL
361    /// set (`Authorization`, custom `X-*`, `X-OBJECTIVEAI-ARGUMENTS`)
362    /// plus whatever identity headers were present at dial. Never
363    /// mutated after connect — mirrors the SDK `Connection`'s base
364    /// `headers`. The transient subset is overridden per request by
365    /// `extra_headers`; the per-URL subset has no overlay key, so it
366    /// always survives on every request.
367    base_headers: IndexMap<String, String>,
368    /// Mutable transient-identity overlay, full-replaced every turn by
369    /// `apply_transient_headers` → `set_extra_headers`. Overrides
370    /// `base_headers` per key (mirrors `Connection::extra_headers`).
371    /// Starts empty: until the first refresh, `base_headers` alone
372    /// carries the dial-time identity headers.
373    extra_headers: RwLock<IndexMap<String, String>>,
374}
375
376impl std::fmt::Debug for WsUpstream {
377    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
378        f.debug_struct("WsUpstream")
379            .field("url", &self.url)
380            .field("session_id", &self.session_id)
381            .finish_non_exhaustive()
382    }
383}
384
385impl WsUpstream {
386    /// Headers to stamp on every outbound `server_request`, mirroring
387    /// `Connection::build_request_headers` exactly: the persistent
388    /// `base_headers` first, then the `extra_headers` transient overlay
389    /// (overrides per key), then this upstream's `Mcp-Session-Id` last
390    /// (so it can never be shadowed). Per-URL headers live only in
391    /// `base_headers` (no overlay key collides), so they're present on
392    /// EVERY request — identical to the HTTP path.
393    async fn headers(&self) -> IndexMap<String, String> {
394        let mut h = self.base_headers.clone();
395        for (k, v) in self.extra_headers.read().await.iter() {
396            h.insert(k.clone(), v.clone());
397        }
398        h.insert(
399            crate::upstream::MCP_SESSION_ID_KEY.to_string(),
400            self.session_id.clone(),
401        );
402        h
403    }
404
405    pub async fn list_tools(&self) -> Result<Arc<Vec<Tool>>, Arc<McpError>> {
406        // Capability gate — an upstream that didn't advertise `tools`
407        // has no `tools/list`; calling it anyway 404s on most servers.
408        if !self.has_tools_cap {
409            return Ok(Arc::new(Vec::new()));
410        }
411        let headers = self.headers().await;
412        let response = self
413            .channel
414            .request(
415                server_request::Payload::ToolsList {
416                    mcp_kind: self.mcp_kind.clone(),
417                    params: ListToolsRequest { cursor: None },
418                },
419                headers,
420            )
421            .await
422            .map_err(Arc::new)?;
423        match response.payload {
424            server_response::Payload::ToolsList { result, .. } => {
425                Ok(Arc::new(unwrap_rpc(&self.url, result).map_err(Arc::new)?.tools))
426            }
427            other => Err(Arc::new(variant_mismatch(&self.url, "tools_list", &other))),
428        }
429    }
430
431    pub async fn list_resources(&self) -> Result<Arc<Vec<Resource>>, Arc<McpError>> {
432        // Capability gate — an upstream that didn't advertise
433        // `resources` has no `resources/list`; calling it anyway 404s
434        // on most servers (e.g. the tools-only plugin fixtures).
435        if !self.has_resources_cap {
436            return Ok(Arc::new(Vec::new()));
437        }
438        let headers = self.headers().await;
439        let response = self
440            .channel
441            .request(
442                server_request::Payload::ResourcesList {
443                    mcp_kind: self.mcp_kind.clone(),
444                    params: ListResourcesRequest { cursor: None },
445                },
446                headers,
447            )
448            .await
449            .map_err(Arc::new)?;
450        match response.payload {
451            server_response::Payload::ResourcesList { result, .. } => {
452                Ok(Arc::new(unwrap_rpc(&self.url, result).map_err(Arc::new)?.resources))
453            }
454            other => Err(Arc::new(variant_mismatch(&self.url, "resources_list", &other))),
455        }
456    }
457
458    pub async fn call_tool(
459        &self,
460        params: &CallToolRequestParams,
461    ) -> Result<CallToolResult, McpError> {
462        let headers = self.headers().await;
463        let response = self
464            .channel
465            .request(
466                server_request::Payload::ToolsCall {
467                    mcp_kind: self.mcp_kind.clone(),
468                    params: params.clone(),
469                },
470                headers,
471            )
472            .await?;
473        match response.payload {
474            server_response::Payload::ToolsCall { result, .. } => unwrap_rpc(&self.url, result),
475            other => Err(variant_mismatch(&self.url, "tools_call", &other)),
476        }
477    }
478
479    pub async fn read_resource(&self, uri: &str) -> Result<ReadResourceResult, McpError> {
480        let headers = self.headers().await;
481        let response = self
482            .channel
483            .request(
484                server_request::Payload::ResourcesRead {
485                    mcp_kind: self.mcp_kind.clone(),
486                    params: ReadResourceRequestParams {
487                        uri: uri.to_string(),
488                    },
489                },
490                headers,
491            )
492            .await?;
493        match response.payload {
494            server_response::Payload::ResourcesRead { result, .. } => unwrap_rpc(&self.url, result),
495            other => Err(variant_mismatch(&self.url, "resources_read", &other)),
496        }
497    }
498
499    pub async fn delete(&self) -> Result<(), McpError> {
500        let headers = self.headers().await;
501        let response = self
502            .channel
503            .request(
504                server_request::Payload::SessionTerminate {
505                    mcp_kind: self.mcp_kind.clone(),
506                },
507                headers,
508            )
509            .await?;
510        match response.payload {
511            server_response::Payload::SessionTerminate { result, .. } => unwrap_rpc(&self.url, result),
512            other => Err(variant_mismatch(&self.url, "session_terminate", &other)),
513        }
514    }
515
516    pub fn set_on_tools_list_changed<F>(&self, callback: F)
517    where
518        F: Fn() + Send + Sync + 'static,
519    {
520        self.channel
521            .set_tools_list_changed(self.mcp_kind.clone(), Arc::new(callback));
522    }
523
524    pub fn set_on_resources_list_changed<F>(&self, callback: F)
525    where
526        F: Fn() + Send + Sync + 'static,
527    {
528        self.channel
529            .set_resources_list_changed(self.mcp_kind.clone(), Arc::new(callback));
530    }
531
532    pub async fn set_extra_headers(&self, extras: IndexMap<String, String>) {
533        *self.extra_headers.write().await = extras;
534    }
535}
536
537/// A per-upstream handle: HTTP [`Connection`] or WS [`WsUpstream`]. Exposes
538/// exactly the surface [`crate::session::Session`] + `handle_delete` use.
539#[derive(Debug)]
540pub enum Upstream {
541    Http(Connection),
542    Ws(WsUpstream),
543}
544
545impl Upstream {
546    /// Whether this upstream is reached over the `client_objectiveai_mcp`
547    /// reverse channel (a `ws://` upstream) rather than plain HTTP.
548    pub fn is_ws(&self) -> bool {
549        matches!(self, Upstream::Ws(_))
550    }
551
552    pub fn url(&self) -> &str {
553        match self {
554            Upstream::Http(c) => &c.url,
555            Upstream::Ws(w) => &w.url,
556        }
557    }
558
559    pub fn session_id(&self) -> &str {
560        match self {
561            Upstream::Http(c) => &c.session_id,
562            Upstream::Ws(w) => &w.session_id,
563        }
564    }
565
566    /// Upstream `server_info.name` — used to derive the session's routing
567    /// prefix. (`Connection` exposes it via `initialize_result`.)
568    pub fn server_name(&self) -> &str {
569        match self {
570            Upstream::Http(c) => &c.initialize_result.server_info.name,
571            Upstream::Ws(w) => &w.server_name,
572        }
573    }
574
575    /// Upstream `server_info.version` — the prefix collision tie-breaker.
576    pub fn server_version(&self) -> &str {
577        match self {
578            Upstream::Http(c) => &c.initialize_result.server_info.version,
579            Upstream::Ws(w) => &w.server_version,
580        }
581    }
582
583    /// The upstream's full `initialize` reply (capabilities, server_info,
584    /// instructions, protocol version) — used by `servers/list`.
585    pub fn initialize_result(
586        &self,
587    ) -> &objectiveai_sdk::mcp::initialize_result::InitializeResult {
588        match self {
589            Upstream::Http(c) => &c.initialize_result,
590            Upstream::Ws(w) => &w.initialize_result,
591        }
592    }
593
594    /// The laboratory this upstream IS, if any — for `servers/list` and
595    /// `laboratory_transfer`.
596    ///
597    /// Read from the explicit, typed laboratory marker the API supplied
598    /// (`X-MCP-Laboratories`), NOT inferred by string-parsing the
599    /// `ws://laboratory/{id}` URL. HTTP upstreams and unmarked websocket
600    /// upstreams (the primary `objectiveai` MCP, plugins) are `None`.
601    pub fn laboratory(&self) -> Option<objectiveai_sdk::laboratories::Laboratory> {
602        match self {
603            Upstream::Http(_) => None,
604            Upstream::Ws(w) => w.laboratory.clone(),
605        }
606    }
607
608    /// The plugin this upstream IS, if any — for `servers/list`. Same
609    /// transport+kind gating as [`Self::laboratory`]: only a websocket
610    /// upstream whose `McpKind` is `Plugin` maps to a [`Plugin`]; HTTP and
611    /// non-plugin websocket kinds are `None`.
612    pub fn plugin(&self) -> Option<objectiveai_sdk::mcp::server::Plugin> {
613        match self {
614            Upstream::Http(_) => None,
615            Upstream::Ws(w) => match &w.mcp_kind {
616                McpKind::Plugin {
617                    owner,
618                    name,
619                    version,
620                    mcp,
621                } => Some(objectiveai_sdk::mcp::server::Plugin {
622                    owner: owner.clone(),
623                    name: name.clone(),
624                    version: version.clone(),
625                    mcp: mcp.clone(),
626                }),
627                McpKind::ObjectiveAi | McpKind::Laboratory { .. } => None,
628            },
629        }
630    }
631
632    /// The session reverse channel this upstream rides, for proxy-level
633    /// ops that aren't a per-upstream MCP call (e.g. laboratory transfer,
634    /// which spans two laboratories on the same conduit). `None` for HTTP
635    /// upstreams, which have no reverse channel.
636    pub fn reverse_channel(&self) -> Option<&ReverseChannel> {
637        match self {
638            Upstream::Http(_) => None,
639            Upstream::Ws(w) => Some(&w.channel),
640        }
641    }
642
643    pub async fn list_tools(&self) -> Result<Arc<Vec<Tool>>, Arc<McpError>> {
644        match self {
645            Upstream::Http(c) => c.list_tools().await,
646            Upstream::Ws(w) => w.list_tools().await,
647        }
648    }
649
650    pub async fn list_resources(&self) -> Result<Arc<Vec<Resource>>, Arc<McpError>> {
651        match self {
652            Upstream::Http(c) => c.list_resources().await,
653            Upstream::Ws(w) => w.list_resources().await,
654        }
655    }
656
657    pub async fn call_tool(
658        &self,
659        params: &CallToolRequestParams,
660    ) -> Result<CallToolResult, McpError> {
661        match self {
662            Upstream::Http(c) => c.call_tool(params).await,
663            Upstream::Ws(w) => w.call_tool(params).await,
664        }
665    }
666
667    pub async fn read_resource(&self, uri: &str) -> Result<ReadResourceResult, McpError> {
668        match self {
669            Upstream::Http(c) => c.read_resource(uri).await,
670            Upstream::Ws(w) => w.read_resource(uri).await,
671        }
672    }
673
674    pub async fn delete(&self) -> Result<(), McpError> {
675        match self {
676            Upstream::Http(c) => c.delete().await,
677            Upstream::Ws(w) => w.delete().await,
678        }
679    }
680
681    pub fn set_on_tools_list_changed<F>(&self, callback: F)
682    where
683        F: Fn() + Send + Sync + 'static,
684    {
685        match self {
686            Upstream::Http(c) => c.set_on_tools_list_changed(callback),
687            Upstream::Ws(w) => w.set_on_tools_list_changed(callback),
688        }
689    }
690
691    pub fn set_on_resources_list_changed<F>(&self, callback: F)
692    where
693        F: Fn() + Send + Sync + 'static,
694    {
695        match self {
696            Upstream::Http(c) => c.set_on_resources_list_changed(callback),
697            Upstream::Ws(w) => w.set_on_resources_list_changed(callback),
698        }
699    }
700
701    pub async fn set_extra_headers(&self, extras: IndexMap<String, String>) {
702        match self {
703            Upstream::Http(c) => c.set_extra_headers(extras).await,
704            Upstream::Ws(w) => w.set_extra_headers(extras).await,
705        }
706    }
707}
708
709/// Parse a `ws://objectiveai` / `ws:///owner/name/version/mcp` URL into
710/// its [`McpKind`]. Returns `None` for any other shape.
711///
712/// NOTE: laboratories are deliberately NOT parsed here. A laboratory's
713/// `McpKind` comes from the explicit, typed `X-MCP-Laboratories` marker
714/// (see `crate::upstream`), never from string-matching the URL — so the
715/// proxy's notion of "this is a laboratory" has a single authoritative
716/// source.
717pub fn parse_ws_mcp_kind(url: &str) -> Option<McpKind> {
718    let rest = url.strip_prefix("ws://")?;
719    // Drop any `?query` (plugin args ride there, parsed separately).
720    let rest = rest.split('?').next().unwrap_or(rest);
721    // `ws://objectiveai` → host "objectiveai", no path.
722    if rest == "objectiveai" {
723        return Some(McpKind::ObjectiveAi);
724    }
725    // `ws:///owner/name/version/mcp` → empty host, leading '/'.
726    let path = rest.strip_prefix('/')?;
727    let parts: Vec<&str> = path.split('/').collect();
728    if let [owner, name, version, mcp] = parts.as_slice() {
729        if !owner.is_empty() && !name.is_empty() && !version.is_empty() && !mcp.is_empty() {
730            return Some(McpKind::Plugin {
731                owner: (*owner).to_string(),
732                name: (*name).to_string(),
733                version: (*version).to_string(),
734                mcp: (*mcp).to_string(),
735            });
736        }
737    }
738    None
739}
740
741/// `initialize` a `ws://` upstream over `channel` and build its
742/// [`WsUpstream`]. `headers` is the full set sent on the `initialize`
743/// request — the session-global transient identity headers, plus (on
744/// resume) the upstream `Mcp-Session-Id` and any auth. `args` carries
745/// plugin init arguments (empty for `objectiveai`).
746pub async fn connect_ws(
747    channel: ReverseChannel,
748    url: String,
749    mcp_kind: McpKind,
750    args: IndexMap<String, Option<String>>,
751    mut headers: IndexMap<String, String>,
752    laboratory: Option<objectiveai_sdk::laboratories::Laboratory>,
753) -> Result<WsUpstream, McpError> {
754    let response = channel
755        .request(
756            server_request::Payload::Initialize {
757                mcp_kind: mcp_kind.clone(),
758                params: InitializeRequest { args },
759            },
760            headers.clone(),
761        )
762        .await?;
763    let reply = match response.payload {
764        server_response::Payload::Initialize { result, .. } => unwrap_rpc(&url, result)?,
765        other => return Err(variant_mismatch(&url, "initialize", &other)),
766    };
767    // The per-request stamped set drops the resume `Mcp-Session-Id`
768    // ([`WsUpstream::headers`] re-adds whatever the upstream just minted)
769    // but keeps the transient identity + auth so the post-init health
770    // probe + every later call still pass the conduit's transient check.
771    headers.shift_remove(crate::upstream::MCP_SESSION_ID_KEY);
772    let session_id = reply.mcp_session_id;
773    let initialize_result = reply.result;
774    let has_tools_cap = initialize_result.capabilities.tools.is_some();
775    let has_resources_cap = initialize_result.capabilities.resources.is_some();
776    let server_name = initialize_result.server_info.name.clone();
777    let server_version = initialize_result.server_info.version.clone();
778    Ok(WsUpstream {
779        channel,
780        mcp_kind,
781        url,
782        session_id,
783        server_name,
784        server_version,
785        initialize_result,
786        laboratory,
787        has_tools_cap,
788        has_resources_cap,
789        // The connect-time set (per-URL ∪ dial-time identity) is the
790        // persistent base; the transient overlay starts empty and is
791        // filled by the first `set_extra_headers`. Mirrors the SDK
792        // `Connection`, where connect headers are the base and
793        // `extra_headers` begins empty.
794        base_headers: headers,
795        extra_headers: RwLock::new(IndexMap::new()),
796    })
797}
798
799fn unwrap_rpc<R>(url: &str, result: JsonRpcResult<R>) -> Result<R, McpError> {
800    match result {
801        JsonRpcResult::Ok { result } => Ok(result),
802        JsonRpcResult::Err {
803            code,
804            message,
805            data,
806        } => Err(McpError::JsonRpc {
807            url: url.to_string(),
808            code,
809            message,
810            data,
811        }),
812    }
813}
814
815fn transport_error(message: &str) -> McpError {
816    McpError::MalformedResponse {
817        url: "ws".to_string(),
818        message: message.to_string(),
819    }
820}
821
822/// Build a `JsonRpcResult::Err` for an inbound MCP-op `client_request`
823/// (`deliver_client_request`). Generic over the result type so each
824/// op's reply variant infers `R`.
825fn rpc_err_result<R>(code: i64, message: String) -> JsonRpcResult<R> {
826    JsonRpcResult::Err {
827        code,
828        message,
829        data: None,
830    }
831}
832
833fn variant_mismatch(url: &str, expected: &str, got: &server_response::Payload) -> McpError {
834    McpError::MalformedResponse {
835        url: url.to_string(),
836        message: format!(
837            "reverse channel returned wrong payload variant: expected {expected}, got {}",
838            got_variant_name(got),
839        ),
840    }
841}
842
843fn got_variant_name(p: &server_response::Payload) -> &'static str {
844    use server_response::Payload as P;
845    match p {
846        P::Initialize { .. } => "initialize",
847        P::ToolsList { .. } => "tools_list",
848        P::ToolsCall { .. } => "tools_call",
849        P::ResourcesList { .. } => "resources_list",
850        P::ResourcesRead { .. } => "resources_read",
851        P::SessionTerminate { .. } => "session_terminate",
852        P::ReadMessageQueue(_) => "read_message_queue",
853        P::Retrieve(_) => "retrieve",
854        P::Drop(_) => "drop",
855        P::LaboratoryTransfer(_) => "laboratory_transfer",
856    }
857}