Skip to main content

mcpmesh_local_api/
client.rs

1//! A no-iroh mcpmesh-local/1 client: connect the UDS, read the server's `Hello`
2//! first frame, assert the api name, then issue typed request/response frames. Distinct
3//! from the CLI crate (`cli/`)'s ControlClient (which uses mcpmesh_net::framing) — this one links no
4//! iroh, so kb and the host shell can use it. kb calls this to self-register
5//! its `[services.kb]` socket backend with the running mcpmesh daemon.
6use std::path::Path;
7
8use serde_json::Value;
9
10use crate::codec::{FrameReader, Inbound, MAX_FRAME_BYTES, write_frame};
11use crate::protocol::{
12    AuditSummaryResult, BackendSpec, BlobFetchParams, BlobFetchResult, BlobGrantParams,
13    BlobPublishParams, BlobPublishResult, BlobScopeList, Hello, InviteParams, InviteResult,
14    OpenSessionParams, OrgJoinParams, OrgJoinResult, PairParams, PairResult, PeerRemoveParams,
15    PeerRenameParams, PeerServicesParams, PeerServicesResult, RegisterServiceParams, Request,
16    RosterInstallParams, RosterInstallResult, ServiceAllowParams, SetAppMetadataParams,
17    SetNicknameParams, SetRelaysParams, SetRelaysResult, SetRosterUrlParams, StatusResult,
18    StreamFrame, UnregisterServiceParams,
19};
20use crate::transport::{connect_local, split_local};
21
22/// The client's read half — boxed so ONE `ControlClient` serves every transport (the
23/// platform socket/pipe via [`connect_control`], or an embedder's in-memory duplex via
24/// [`connect_control_io`]).
25pub type ControlRead = Box<dyn tokio::io::AsyncRead + Send + Unpin>;
26/// The client's write half — see [`ControlRead`].
27pub type ControlWrite = Box<dyn tokio::io::AsyncWrite + Send + Unpin>;
28
29/// A connected mcpmesh-local/1 client: the framed stream + the server's `Hello`.
30pub struct ControlClient {
31    hello: Hello,
32    reader: FrameReader<ControlRead>,
33    writer: ControlWrite,
34}
35
36/// Hand-rolled (the boxed transport halves are not `Debug`): the `Hello` is the one
37/// diagnostic a `{:?}` needs — tests format `Result<ControlClient, _>` this way.
38impl std::fmt::Debug for ControlClient {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        f.debug_struct("ControlClient")
41            .field("hello", &self.hello)
42            .finish_non_exhaustive()
43    }
44}
45
46/// The error surface of the client — thin, so callers can `anyhow`-wrap it.
47///
48/// The `Display`/`Error`/`From` impls below are hand-rolled rather than derived: the
49/// `client` feature deliberately pulls ONLY tokio (no `thiserror`), and the hand-rolled
50/// impls are behavior-identical (same messages, same `?`-conversion from `io::Error`)
51/// with zero extra dependencies.
52#[derive(Debug)]
53pub enum ClientError {
54    Io(std::io::Error),
55    Closed(&'static str),
56    Malformed(&'static str),
57    WrongApi { got: String, want: &'static str },
58    Api(Value),
59}
60
61impl std::fmt::Display for ClientError {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        match self {
64            ClientError::Io(err) => write!(f, "io: {err}"),
65            ClientError::Closed(what) => write!(f, "connection closed before {what}"),
66            ClientError::Malformed(what) => write!(f, "malformed {what} frame"),
67            ClientError::WrongApi { got, want } => {
68                write!(f, "unexpected api: got {got:?}, want {want:?}")
69            }
70            ClientError::Api(err) => write!(f, "control API error: {err}"),
71        }
72    }
73}
74
75impl std::error::Error for ClientError {}
76
77impl From<std::io::Error> for ClientError {
78    fn from(err: std::io::Error) -> Self {
79        ClientError::Io(err)
80    }
81}
82
83impl ControlClient {
84    pub fn hello(&self) -> &Hello {
85        &self.hello
86    }
87
88    /// Issue a typed request; return the JSON-RPC `result` (or `ClientError::Api` on a
89    /// JSON-RPC `error`).
90    pub async fn request(&mut self, request: Request) -> Result<Value, ClientError> {
91        let frame = serde_json::to_value(&request).expect("Request serializes");
92        self.request_value(&frame).await
93    }
94
95    /// Issue a RAW request frame — the escape hatch for methods outside the typed
96    /// [`Request`] surface (the daemon-internal `shutdown`, third-party
97    /// `{"method":..,"params":{}}` shapes the dispatcher tolerates). Returns the JSON-RPC
98    /// `result` value (or `ClientError::Api` on a JSON-RPC `error`).
99    pub async fn request_value(&mut self, request: &Value) -> Result<Value, ClientError> {
100        write_frame(&mut self.writer, request).await?;
101        match self.reader.next().await? {
102            Some(Inbound::Frame(resp)) => {
103                if let Some(err) = resp.get("error") {
104                    return Err(ClientError::Api(err.clone()));
105                }
106                Ok(resp.get("result").cloned().unwrap_or(Value::Null))
107            }
108            Some(Inbound::Violation(_)) => Err(ClientError::Malformed("response")),
109            None => Err(ClientError::Closed("response")),
110        }
111    }
112
113    /// Send a request WITHOUT reading a response — for `OpenSession`, after which the
114    /// socket stops being JSON-RPC and becomes a raw MCP byte pipe (protocol.rs). Returns
115    /// the framed halves so the caller can pump the session — the SAME `FrameReader` that
116    /// read the Hello, so bytes the daemon pipelined behind it are never lost. A caller
117    /// that must re-box the read half calls `FrameReader::into_inner`, which returns the
118    /// BUFFERED reader (its read-ahead travels with it — see the pipelining test below).
119    pub async fn open_session(
120        mut self,
121        peer: String,
122        service: String,
123    ) -> Result<(FrameReader<ControlRead>, ControlWrite), ClientError> {
124        let frame = serde_json::to_value(Request::OpenSession(OpenSessionParams { peer, service }))
125            .expect("Request serializes");
126        write_frame(&mut self.writer, &frame).await?;
127        Ok((self.reader, self.writer))
128    }
129
130    /// Send a parameterless stream-upgrade request WITHOUT reading a response — like
131    /// [`open_session`](Self::open_session), but generic on the `method`: after this call the
132    /// socket stops being request/response and becomes a one-way push stream of frames the caller
133    /// READS (the `subscribe` telemetry surface). Returns the framed halves — the SAME
134    /// `FrameReader` that read the Hello, so any frame the daemon pipelined behind it is never
135    /// lost. The write half is handed back so the caller can hold the connection open (a watcher
136    /// only reads, but dropping the writer would half-close the socket).
137    pub async fn open_stream(
138        mut self,
139        method: &str,
140    ) -> Result<(FrameReader<ControlRead>, ControlWrite), ClientError> {
141        let frame = serde_json::json!({ "method": method });
142        write_frame(&mut self.writer, &frame).await?;
143        Ok((self.reader, self.writer))
144    }
145
146    /// Issue `request` and deserialize the JSON-RPC `result` into `T` — the shared core of every
147    /// typed helper below. `what` names the result in the [`ClientError::Malformed`] surface. The
148    /// wrong-type hazard the raw [`request`](Self::request) leaves to the caller is closed here:
149    /// each helper pairs its Request variant with its result type once, in this crate.
150    async fn request_typed<T: serde::de::DeserializeOwned>(
151        &mut self,
152        request: Request,
153        what: &'static str,
154    ) -> Result<T, ClientError> {
155        let v = self.request(request).await?;
156        serde_json::from_value(v).map_err(|_| ClientError::Malformed(what))
157    }
158
159    /// Issue `request` and discard the ack body (the daemon answers `{}` for verbs with no result
160    /// vocabulary). A JSON-RPC error still surfaces as [`ClientError::Api`].
161    async fn request_ack(&mut self, request: Request) -> Result<(), ClientError> {
162        self.request(request).await.map(|_| ())
163    }
164
165    /// The daemon's `status` picture: services served, known peers, roster/presence state,
166    /// self identity, recent pairings, and advisory reachability.
167    pub async fn status(&mut self) -> Result<StatusResult, ClientError> {
168        self.request_typed(Request::Status, "status result").await
169    }
170
171    /// Register/update a `[services.*]` entry idempotently (the daemon persists it and hot-reloads
172    /// serving). The daemon acks; the ack body is discarded.
173    pub async fn register_service(
174        &mut self,
175        name: &str,
176        backend: BackendSpec,
177        allow: Vec<String>,
178    ) -> Result<(), ClientError> {
179        self.register_service_with(name, backend, allow, false)
180            .await
181    }
182
183    /// [`register_service`](Self::register_service) with an explicit `ephemeral` flag (#36). When
184    /// `ephemeral` is true the registration lives only in daemon memory and is unregistered
185    /// automatically when THIS control connection closes — no config write, nothing to clean up.
186    /// Ideal for an embedder serving a `socket` backend from a fresh path each run.
187    pub async fn register_service_with(
188        &mut self,
189        name: &str,
190        backend: BackendSpec,
191        allow: Vec<String>,
192        ephemeral: bool,
193    ) -> Result<(), ClientError> {
194        self.request_ack(Request::RegisterService(RegisterServiceParams {
195            name: name.to_string(),
196            backend,
197            allow,
198            ephemeral,
199            rate_limit_per_min: None,
200        }))
201        .await
202    }
203
204    /// Mint a single-use pairing invite granting `services` (see `invite_multi` for more than
205    /// one); return the copyable
206    /// `mcpmesh-invite:` line + its expiry.
207    pub async fn invite(&mut self, services: Vec<String>) -> Result<InviteResult, ClientError> {
208        self.invite_with(services, None).await
209    }
210
211    /// [`invite`](Self::invite) with an opaque `app_label` (#31) carried through to the redeemer's
212    /// `pair` result. mcpmesh never interprets the label; the embedder does (e.g. its own URN).
213    pub async fn invite_with(
214        &mut self,
215        services: Vec<String>,
216        app_label: Option<String>,
217    ) -> Result<InviteResult, ClientError> {
218        self.invite_multi(services, app_label, None).await
219    }
220
221    /// `invite_with`, plus `max_uses` (#87): an invite redeemable up to that many times, each
222    /// redemption running its own SAS ceremony and writing its own peer rows.
223    ///
224    /// `None` = 1, the single-use default. The value is clamped daemon-side to
225    /// [`MAX_INVITE_USES`](crate::MAX_INVITE_USES) — read
226    /// [`InviteResult::uses_remaining`](crate::InviteResult::uses_remaining) for what you actually
227    /// got rather than assuming the request was honoured verbatim.
228    pub async fn invite_multi(
229        &mut self,
230        services: Vec<String>,
231        app_label: Option<String>,
232        max_uses: Option<u32>,
233    ) -> Result<InviteResult, ClientError> {
234        self.invite_named(services, app_label, max_uses, None).await
235    }
236
237    /// Mint an invite, optionally under YOUR OWN local name for whoever redeems it (#87).
238    ///
239    /// `peer_nickname` overrides the name they claim for themselves — the fix for two same-model
240    /// machines that does not require the other person to rename theirs. Never sent to them, and
241    /// rejected alongside `max_uses > 1` (one name for every redeemer collides on the second).
242    pub async fn invite_named(
243        &mut self,
244        services: Vec<String>,
245        app_label: Option<String>,
246        max_uses: Option<u32>,
247        peer_nickname: Option<String>,
248    ) -> Result<InviteResult, ClientError> {
249        self.request_typed(
250            Request::Invite(InviteParams {
251                services,
252                app_label,
253                max_uses,
254                peer_nickname,
255            }),
256            "invite result",
257        )
258        .await
259    }
260
261    /// Redeem a pairing invite; return the inviter's suggested nickname, the display-only SAS
262    /// code, and the granted services.
263    pub async fn pair(&mut self, invite_line: &str) -> Result<PairResult, ClientError> {
264        self.pair_as(invite_line, None).await
265    }
266
267    /// Redeem an invite, optionally under YOUR OWN local name for the inviter (#87).
268    ///
269    /// `as_nickname` overrides the name the invite suggests. Use it when that name is already
270    /// taken locally — otherwise the pairing is refused and the only other fixes are asking the
271    /// inviter to re-mint or renaming your existing peer. It does not bypass the collision check:
272    /// an alias that itself collides is refused the same way.
273    pub async fn pair_as(
274        &mut self,
275        invite_line: &str,
276        as_nickname: Option<String>,
277    ) -> Result<PairResult, ClientError> {
278        self.request_typed(
279            Request::Pair(PairParams {
280                invite_line: invite_line.to_string(),
281                as_nickname,
282            }),
283            "pair result",
284        )
285        .await
286    }
287
288    /// Unpair a peer by nickname: drops its identity row AND its every-`allow` membership
289    /// (idempotent; live sessions are not severed). The daemon acks; the ack body is discarded.
290    pub async fn peer_remove(&mut self, nickname: &str) -> Result<(), ClientError> {
291        self.request_ack(Request::PeerRemove(PeerRemoveParams {
292            nickname: nickname.to_string(),
293        }))
294        .await
295    }
296
297    /// Rename a contact's nickname to `to` — every device sharing `user_id` when given, else the
298    /// single provisional `nickname` entry — carrying its grants along. The daemon refuses (a
299    /// [`ClientError::Api`]) when `to` is empty or already names a different identity. The daemon
300    /// acks; the ack body is discarded.
301    pub async fn peer_rename(
302        &mut self,
303        user_id: Option<String>,
304        nickname: Option<String>,
305        to: &str,
306    ) -> Result<(), ClientError> {
307        self.request_ack(Request::PeerRename(PeerRenameParams {
308            user_id,
309            nickname,
310            to: to.to_string(),
311        }))
312        .await
313    }
314
315    /// Install a signed roster from the LOCAL file at `path` (`org_root_pk` pins the org root on
316    /// FIRST install); return the installed org id + serial + severed-session count.
317    pub async fn roster_install(
318        &mut self,
319        path: &str,
320        org_root_pk: Option<String>,
321    ) -> Result<RosterInstallResult, ClientError> {
322        self.request_typed(
323            Request::RosterInstall(RosterInstallParams {
324                path: path.to_string(),
325                org_root_pk,
326            }),
327            "roster_install result",
328        )
329        .await
330    }
331
332    /// Pin the org root on a JOINER (no roster yet). `user_key` is a LOCAL path — the key never
333    /// crosses the API. Returns the pinned org id.
334    pub async fn org_join(
335        &mut self,
336        org_id: &str,
337        org_root_pk: &str,
338        user_id: &str,
339        user_key: &str,
340    ) -> Result<OrgJoinResult, ClientError> {
341        self.request_typed(
342            Request::OrgJoin(OrgJoinParams {
343                org_id: org_id.to_string(),
344                org_root_pk: org_root_pk.to_string(),
345                user_id: user_id.to_string(),
346                user_key: user_key.to_string(),
347            }),
348            "org_join result",
349        )
350        .await
351    }
352
353    /// Pin the HTTPS roster URL (`[roster].url`) in the daemon's config. The daemon acks; the
354    /// ack body is discarded.
355    pub async fn set_roster_url(&mut self, url: &str) -> Result<(), ClientError> {
356        self.request_ack(Request::SetRosterUrl(SetRosterUrlParams {
357            url: url.to_string(),
358        }))
359        .await
360    }
361
362    /// Discover which services a paired `peer` (a nickname, `eid:`, or `b64u:`) CURRENTLY grants
363    /// the caller (#52) — dials the peer and returns the service names its allow admits for the
364    /// caller's principal (only your own admitted services, never the peer's full registry).
365    pub async fn peer_services(&mut self, peer: &str) -> Result<Vec<String>, ClientError> {
366        self.request_typed::<PeerServicesResult>(
367            Request::PeerServices(PeerServicesParams {
368                peer: peer.to_string(),
369            }),
370            "peer_services",
371        )
372        .await
373        .map(|r| r.services)
374    }
375
376    /// Remove a service registration (#50) — the deregistration mirror of `register_service`.
377    /// Removes the whole entry (allow included) + any ephemeral registration of the name, then
378    /// hot-reloads. Idempotent: an unknown name is a clean no-op.
379    pub async fn unregister_service(&mut self, name: &str) -> Result<(), ClientError> {
380        self.request_ack(Request::UnregisterService(UnregisterServiceParams {
381            name: name.to_string(),
382        }))
383        .await
384    }
385
386    /// Grant a stable `principal` (`b64u:`/`eid:`) access to `service` WITHOUT (re)pairing (#44)
387    /// — the per-peer "sharing on" toggle. Idempotent; an unknown service is a clean no-op.
388    pub async fn service_allow_grant(
389        &mut self,
390        service: &str,
391        principal: &str,
392    ) -> Result<(), ClientError> {
393        self.request_ack(Request::ServiceAllowGrant(ServiceAllowParams {
394            service: service.to_string(),
395            principal: principal.to_string(),
396        }))
397        .await
398    }
399
400    /// Revoke a stable `principal` from `service`'s allow WITHOUT unpairing (#44) — the
401    /// "sharing off" toggle. The peer's identity row is untouched; it just cannot open NEW
402    /// sessions (in-flight ones run to completion). Idempotent.
403    pub async fn service_allow_revoke(
404        &mut self,
405        service: &str,
406        principal: &str,
407    ) -> Result<(), ClientError> {
408        self.request_ack(Request::ServiceAllowRevoke(ServiceAllowParams {
409            service: service.to_string(),
410            principal: principal.to_string(),
411        }))
412        .await
413    }
414
415    /// Set this node's opaque app-metadata blob (#39, roster mode): ≤256 bytes, folded
416    /// signed into each presence heartbeat so paired peers read it in `status` presence —
417    /// no per-peer session. `""` clears it; in-memory (re-set on startup).
418    pub async fn set_app_metadata(&mut self, metadata: &str) -> Result<(), ClientError> {
419        self.request_ack(Request::SetAppMetadata(SetAppMetadataParams {
420            metadata: metadata.to_string(),
421        }))
422        .await
423    }
424
425    /// Set this node's CUSTOM relay set LIVE (#53). `relay_urls` is the desired set (each must
426    /// parse as an iroh `RelayUrl`; empty is rejected). When the node is already in
427    /// `relay_mode = "custom"`, the daemon diffs against the running endpoint and applies the
428    /// delta live (iroh `insert_relay`/`remove_relay`) — no restart, no dropped sessions — then
429    /// persists `[network]`. When the node is currently `default`/`disabled`, the config is
430    /// persisted but the live mode transition isn't possible: the returned
431    /// [`SetRelaysResult::restart_required`] is `true`. Idempotent (an unchanged set → `changed:
432    /// false`, no writes).
433    pub async fn set_relays(
434        &mut self,
435        relay_urls: &[String],
436    ) -> Result<SetRelaysResult, ClientError> {
437        self.request_typed::<SetRelaysResult>(
438            Request::SetRelays(SetRelaysParams {
439                relay_urls: relay_urls.to_vec(),
440            }),
441            "set_relays",
442        )
443        .await
444    }
445
446    /// Rename this node LIVE (#37): the daemon validates + persists `[identity].nickname`
447    /// under its own config lock and updates the name future invites present — no restart.
448    /// Peers keep their stored pairing-time nickname until a re-invite (display-only).
449    pub async fn set_nickname(&mut self, nickname: &str) -> Result<(), ClientError> {
450        self.request_ack(Request::SetNickname(SetNicknameParams {
451            nickname: nickname.to_string(),
452        }))
453        .await
454    }
455
456    /// Summarize the daemon's LOCAL audit log into per-peer / per-service session counts
457    /// (local-only — nothing is transmitted).
458    pub async fn audit_summary(&mut self) -> Result<AuditSummaryResult, ClientError> {
459        self.request_typed(Request::AuditSummary, "audit_summary result")
460            .await
461    }
462
463    /// Publish a local file into `scope`; return the minted `mcpmesh/blob/1` ticket + hash.
464    pub async fn blob_publish(
465        &mut self,
466        scope: &str,
467        path: &str,
468    ) -> Result<BlobPublishResult, ClientError> {
469        self.request_typed(
470            Request::BlobPublish(BlobPublishParams {
471                scope: scope.to_string(),
472                path: path.to_string(),
473            }),
474            "blob_publish result",
475        )
476        .await
477    }
478
479    /// List the daemon's blob scopes (name → hashes + grants + withdrawn).
480    ///
481    /// A DEFAULT LIMIT applies (#84b) — check `truncated` and page with
482    /// [`blob_list_paged`](Self::blob_list_paged) rather than assuming you saw everything.
483    pub async fn blob_list(&mut self) -> Result<BlobScopeList, ClientError> {
484        self.blob_list_paged(Default::default()).await
485    }
486
487    /// List blob scopes with filters + paging (#84b, `api_minor >= 20`).
488    pub async fn blob_list_paged(
489        &mut self,
490        params: crate::BlobListParams,
491    ) -> Result<BlobScopeList, ClientError> {
492        self.request_typed(Request::BlobList(params), "blob_list result")
493            .await
494    }
495
496    /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified), export to
497    /// `dest_path`; return the verified hash + byte length.
498    pub async fn blob_fetch(
499        &mut self,
500        ticket: &str,
501        dest_path: &str,
502    ) -> Result<BlobFetchResult, ClientError> {
503        self.request_typed(
504            Request::BlobFetch(BlobFetchParams {
505                ticket: ticket.to_string(),
506                dest_path: dest_path.to_string(),
507            }),
508            "blob_fetch result",
509        )
510        .await
511    }
512
513    /// Grant a scope to a principal — any flat-namespace entry: a group name, a user_id,
514    /// or a nickname (the shared `principal_set` expansion).
515    /// The daemon acks; the ack body is discarded (a JSON-RPC error surfaces as
516    /// `ClientError::Api`). Granting a scope to your own user_id reaches ALL of that
517    /// person's devices.
518    pub async fn blob_grant(&mut self, scope: &str, principal: &str) -> Result<(), ClientError> {
519        self.request_ack(Request::BlobGrant(BlobGrantParams {
520            scope: scope.to_string(),
521            principal: principal.to_string(),
522        }))
523        .await
524    }
525
526    /// The TYPED `subscribe` upgrade: send [`Request::Subscribe`] (after which the connection
527    /// stops being request/response — see [`open_stream`](Self::open_stream)) and return a
528    /// [`StreamSubscription`] yielding [`StreamFrame`]s. For raw frames (e.g. to tolerate frame
529    /// types newer than this crate), use `open_stream("subscribe")` instead.
530    pub async fn subscribe(self) -> Result<StreamSubscription, ClientError> {
531        let (reader, writer) = self.open_stream("subscribe").await?;
532        Ok(StreamSubscription {
533            reader,
534            _writer: writer,
535        })
536    }
537}
538
539/// A live [`Request::Subscribe`] stream yielding typed [`StreamFrame`]s (snapshot, then
540/// events/lagged notices) until the daemon side closes. Holds the connection's write half for its
541/// lifetime — a subscriber only reads, but dropping the writer would half-close the socket. Drop
542/// the subscription to disconnect (there is no request channel back).
543pub struct StreamSubscription {
544    reader: FrameReader<ControlRead>,
545    _writer: ControlWrite,
546}
547
548/// Hand-rolled like [`ControlClient`]'s: the boxed transport halves are not `Debug`.
549impl std::fmt::Debug for StreamSubscription {
550    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
551        f.debug_struct("StreamSubscription").finish_non_exhaustive()
552    }
553}
554
555impl StreamSubscription {
556    /// The next frame, or `None` when the daemon closed the stream. A frame this crate's
557    /// [`StreamFrame`] does not model (a NEWER daemon's frame type) surfaces as
558    /// [`ClientError::Malformed`] — a forward-compatible consumer reads raw frames via
559    /// [`ControlClient::open_stream`] instead.
560    pub async fn next(&mut self) -> Result<Option<StreamFrame>, ClientError> {
561        match self.reader.next().await? {
562            Some(Inbound::Frame(v)) => serde_json::from_value(v)
563                .map(Some)
564                .map_err(|_| ClientError::Malformed("stream frame")),
565            Some(Inbound::Violation(_)) => Err(ClientError::Malformed("stream frame")),
566            None => Ok(None),
567        }
568    }
569}
570
571/// Complete the mcpmesh-local/1 hello handshake over ALREADY-CONNECTED byte halves —
572/// the transport-agnostic core of [`connect_control`], and the front door for in-process
573/// embedding (`mcpmesh-node`'s `Node::control` dials a tokio duplex through here).
574pub async fn connect_control_io(
575    reader: impl tokio::io::AsyncRead + Send + Unpin + 'static,
576    writer: impl tokio::io::AsyncWrite + Send + Unpin + 'static,
577) -> Result<ControlClient, ClientError> {
578    let mut reader = FrameReader::new(Box::new(reader) as ControlRead, MAX_FRAME_BYTES);
579    let hello: Hello = match reader.next().await? {
580        Some(Inbound::Frame(v)) => {
581            serde_json::from_value(v).map_err(|_| ClientError::Malformed("hello"))?
582        }
583        Some(Inbound::Violation(_)) => return Err(ClientError::Malformed("hello")),
584        None => return Err(ClientError::Closed("hello")),
585    };
586    if hello.api != crate::protocol::API_NAME {
587        return Err(ClientError::WrongApi {
588            got: hello.api,
589            want: crate::protocol::API_NAME,
590        });
591    }
592    Ok(ControlClient {
593        hello,
594        reader,
595        writer: Box::new(writer) as ControlWrite,
596    })
597}
598
599/// Connect + complete the hello handshake, asserting the api name is `mcpmesh-local/1`.
600pub async fn connect_control(path: &Path) -> Result<ControlClient, ClientError> {
601    let stream = connect_local(path).await?;
602    let (read_half, write_half) = split_local(stream);
603    connect_control_io(read_half, write_half).await
604}
605
606/// [`connect_control`] at the platform default endpoint ([`crate::paths::default_endpoint`]):
607/// the quickstart front door — a consumer dials the running daemon without reimplementing
608/// the platform endpoint rule. Resolution failure surfaces as [`ClientError::Io`]
609/// (`NotFound`), same as a daemon that is not running.
610pub async fn connect_control_default() -> Result<ControlClient, ClientError> {
611    connect_control(&crate::paths::default_endpoint()?).await
612}
613
614// Seam-ported (Task 6): every stub daemon binds via the platform seam
615// (`transport::bind_local` + `LocalListener::accept`) rather than a raw `UnixListener`,
616// so these exercise the platform-identical `ControlClient` on BOTH unix (UDS) and windows
617// (named pipe). Gated on `feature = "service"` (bind needs it) rather than `unix`: under
618// `cargo test --workspace` feature unification turns `service` on for this crate (cli
619// depends on local-api with features=["service"]), so the module compiles and RUNS on the
620// windows CI leg. `test_endpoint` yields a platform-appropriate unique endpoint.
621#[cfg(all(test, feature = "service"))]
622mod tests {
623    use super::*;
624    use crate::protocol::{API_NAME, API_VERSION, BackendKind, ServiceInfo, StatusResult};
625    use crate::transport::{LocalListener, bind_local, split_local};
626    use tokio::io::AsyncWriteExt;
627
628    /// A unique local endpoint for a stub daemon, platform-appropriate: a tempdir socket
629    /// path on unix, a per-process-unique `\\.\pipe\…` name on windows. Returns the
630    /// endpoint plus a guard that MUST outlive the listener (the `TempDir` on unix; unit
631    /// on windows, whose pipe namespace needs no filesystem cleanup).
632    #[cfg(unix)]
633    fn test_endpoint(tag: &str) -> (std::path::PathBuf, tempfile::TempDir) {
634        let dir = tempfile::tempdir().unwrap();
635        let path = dir.path().join(format!("{tag}.sock"));
636        (path, dir)
637    }
638    #[cfg(windows)]
639    fn test_endpoint(tag: &str) -> (std::path::PathBuf, ()) {
640        use std::sync::atomic::{AtomicU64, Ordering};
641        static SEQ: AtomicU64 = AtomicU64::new(0);
642        let n = SEQ.fetch_add(1, Ordering::Relaxed);
643        let path = std::path::PathBuf::from(format!(
644            r"\\.\pipe\mcpmesh-client-test-{}-{tag}-{n}",
645            std::process::id()
646        ));
647        (path, ())
648    }
649
650    /// A stub mcpmesh daemon: send Hello, then answer one `status` with a StatusResult.
651    async fn stub_daemon(mut listener: LocalListener) {
652        let stream = listener.accept().await.unwrap();
653        let (read_half, mut writer) = split_local(stream);
654        write_frame(
655            &mut writer,
656            &serde_json::to_value(Hello {
657                api: API_NAME.into(),
658                api_version: API_VERSION.into(),
659                api_minor: 0,
660                stack_version: "0.1.0".into(),
661            })
662            .unwrap(),
663        )
664        .await
665        .unwrap();
666        let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
667        let req = match reader.next().await.unwrap().unwrap() {
668            Inbound::Frame(v) => v,
669            Inbound::Violation(_) => panic!("violation"),
670        };
671        assert_eq!(req["method"], "status");
672        let result = StatusResult {
673            stack_version: "0.1.0".into(),
674            services: vec![ServiceInfo {
675                name: "kb".into(),
676                allow: vec![],
677                allow_display: vec![],
678                backend: BackendKind::Socket,
679                ephemeral: false,
680            }],
681            peers: vec![],
682            roster: None,
683            presence: vec![],
684            self_user_id: None,
685            recent_pairings: vec![],
686            reachability: vec![],
687            self_nickname: String::new(),
688            storage: None,
689            self_network: None,
690        };
691        write_frame(
692            &mut writer,
693            &serde_json::json!({ "jsonrpc": "2.0", "id": 1, "result": result }),
694        )
695        .await
696        .unwrap();
697        writer.flush().await.unwrap();
698    }
699
700    /// The transport-agnostic front door: the same hello handshake over a plain in-memory
701    /// duplex — what an embedded node's `Node::control` dials through.
702    #[tokio::test]
703    async fn connect_control_io_handshakes_over_a_duplex() {
704        let (client_io, mut server_io) = tokio::io::duplex(4096);
705        tokio::spawn(async move {
706            write_frame(
707                &mut server_io,
708                &serde_json::to_value(Hello {
709                    api: API_NAME.into(),
710                    api_version: API_VERSION.into(),
711                    api_minor: 0,
712                    stack_version: "in-proc".into(),
713                })
714                .unwrap(),
715            )
716            .await
717            .unwrap();
718        });
719        let (r, w) = tokio::io::split(client_io);
720        let client = connect_control_io(r, w).await.expect("handshake");
721        assert_eq!(client.hello().stack_version, "in-proc");
722    }
723
724    #[tokio::test]
725    async fn connect_reads_hello_asserts_api_and_requests() {
726        let (sock, _guard) = test_endpoint("status");
727        let listener = bind_local(&sock).unwrap();
728        let server = tokio::spawn(stub_daemon(listener));
729
730        let mut client = connect_control(&sock).await.unwrap();
731        assert_eq!(client.hello().api, API_NAME);
732        let result = client.request(Request::Status).await.unwrap();
733        assert_eq!(result["services"][0]["name"], "kb");
734        assert_eq!(result["services"][0]["backend"], "socket");
735        server.await.unwrap();
736    }
737
738    #[tokio::test]
739    async fn wrong_api_hello_is_rejected() {
740        let (sock, _guard) = test_endpoint("wrongapi");
741        let listener = bind_local(&sock).unwrap();
742        tokio::spawn(async move {
743            let mut listener = listener;
744            let stream = listener.accept().await.unwrap();
745            let (_r, mut w) = split_local(stream);
746            write_frame(
747                &mut w,
748                &serde_json::json!({"api":"other/1","api_version":"1.0","stack_version":"0"}),
749            )
750            .await
751            .unwrap();
752            w.flush().await.unwrap();
753        });
754        match connect_control(&sock).await {
755            Err(ClientError::WrongApi { got, want }) => {
756                assert_eq!(got, "other/1");
757                assert_eq!(want, API_NAME);
758            }
759            other => panic!("expected WrongApi, got {other:?}"),
760        }
761    }
762
763    #[tokio::test]
764    async fn blob_fetch_and_publish_deserialize_typed_results() {
765        use crate::protocol::{BlobFetchResult, BlobPublishResult};
766        let (sock, _guard) = test_endpoint("blob");
767        let listener = bind_local(&sock).unwrap();
768        let server = tokio::spawn(async move {
769            let mut listener = listener;
770            let stream = listener.accept().await.unwrap();
771            let (read_half, mut writer) = split_local(stream);
772            write_frame(
773                &mut writer,
774                &serde_json::to_value(Hello {
775                    api: API_NAME.into(),
776                    api_version: API_VERSION.into(),
777                    api_minor: 0,
778                    stack_version: "0.1.0".into(),
779                })
780                .unwrap(),
781            )
782            .await
783            .unwrap();
784            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
785            // First request: blob_publish -> a ticket + hash.
786            let req = match reader.next().await.unwrap().unwrap() {
787                Inbound::Frame(v) => v,
788                Inbound::Violation(_) => panic!("violation"),
789            };
790            assert_eq!(req["method"], "blob_publish");
791            assert_eq!(req["params"]["scope"], "eng");
792            write_frame(
793                &mut writer,
794                &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ticket":"blobT","hash":"ab"}}),
795            )
796            .await
797            .unwrap();
798            // Second request: blob_fetch -> a verified hash + length.
799            let req = match reader.next().await.unwrap().unwrap() {
800                Inbound::Frame(v) => v,
801                Inbound::Violation(_) => panic!("violation"),
802            };
803            assert_eq!(req["method"], "blob_fetch");
804            assert_eq!(req["params"]["ticket"], "blobT");
805            assert_eq!(req["params"]["dest_path"], "/tmp/out.bin");
806            write_frame(
807                &mut writer,
808                &serde_json::json!({"jsonrpc":"2.0","id":2,"result":{"hash":"cd","bytes_len":7}}),
809            )
810            .await
811            .unwrap();
812            let _ = (
813                BlobFetchResult {
814                    hash: "cd".into(),
815                    bytes_len: 7,
816                },
817                BlobPublishResult {
818                    ticket: "blobT".into(),
819                    hash: "ab".into(),
820                },
821            );
822        });
823
824        let mut client = connect_control(&sock).await.unwrap();
825        let pub_res = client.blob_publish("eng", "/tmp/a.bin").await.unwrap();
826        assert_eq!(pub_res.ticket, "blobT");
827        assert_eq!(pub_res.hash, "ab");
828        let fetch_res = client.blob_fetch("blobT", "/tmp/out.bin").await.unwrap();
829        assert_eq!(fetch_res.hash, "cd");
830        assert_eq!(fetch_res.bytes_len, 7);
831        server.await.unwrap();
832    }
833
834    /// Regression (lossless rebox): a frame the server PIPELINES in the same write as
835    /// the Hello must survive `open_session` + kb's production re-box shape
836    /// (`FrameReader::new(Box::new(reader.into_inner()), …)`, bridge/session.rs). Against
837    /// the old `into_inner -> R` — which unwrapped the internal `BufReader` and DROPPED
838    /// its read-ahead — the pipelined frame vanished and this test failed (EOF instead of
839    /// the frame). `into_inner -> BufReader<R>` carries the read-ahead across the rebox.
840    #[tokio::test]
841    async fn frame_pipelined_behind_hello_survives_open_session_rebox() {
842        use tokio::io::AsyncRead;
843
844        let (sock, _guard) = test_endpoint("pipelined");
845        let listener = bind_local(&sock).unwrap();
846        let server = tokio::spawn(async move {
847            let mut listener = listener;
848            let stream = listener.accept().await.unwrap();
849            let (read_half, mut writer) = split_local(stream);
850            // ONE write carrying the Hello AND a session frame → both land in the
851            // client's first BufReader fill (the read-ahead under test).
852            let mut bytes = serde_json::to_vec(
853                &serde_json::to_value(Hello {
854                    api: API_NAME.into(),
855                    api_version: API_VERSION.into(),
856                    api_minor: 0,
857                    stack_version: "0.1.0".into(),
858                })
859                .unwrap(),
860            )
861            .unwrap();
862            bytes.push(b'\n');
863            bytes.extend_from_slice(b"{\"jsonrpc\":\"2.0\",\"id\":42,\"result\":{}}\n");
864            writer.write_all(&bytes).await.unwrap();
865            writer.flush().await.unwrap();
866            // Absorb the client's open_session frame so its write never sees EPIPE.
867            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
868            let req = match reader.next().await.unwrap().unwrap() {
869                Inbound::Frame(v) => v,
870                Inbound::Violation(_) => panic!("violation"),
871            };
872            assert_eq!(req["method"], "open_session");
873        });
874
875        let client = connect_control(&sock).await.unwrap();
876        let (reader, _writer) = client
877            .open_session("peer".into(), "kb".into())
878            .await
879            .unwrap();
880        // kb's production shape: erase the half type behind a boxed pipe, then re-frame.
881        let boxed: Box<dyn AsyncRead + Unpin + Send> = Box::new(reader.into_inner());
882        let mut reframed = FrameReader::new(boxed, MAX_FRAME_BYTES);
883        match reframed.next().await.unwrap() {
884            Some(Inbound::Frame(v)) => assert_eq!(v["id"], 42),
885            other => panic!("pipelined frame was lost across the rebox: {other:?}"),
886        }
887        server.await.unwrap();
888    }
889
890    #[tokio::test]
891    async fn blob_grant_issues_request_and_acks() {
892        let (sock, _guard) = test_endpoint("grant");
893        let listener = bind_local(&sock).unwrap();
894        let server = tokio::spawn(async move {
895            let mut listener = listener;
896            let stream = listener.accept().await.unwrap();
897            let (read_half, mut writer) = split_local(stream);
898            write_frame(
899                &mut writer,
900                &serde_json::to_value(Hello {
901                    api: API_NAME.into(),
902                    api_version: API_VERSION.into(),
903                    api_minor: 0,
904                    stack_version: "0.1.0".into(),
905                })
906                .unwrap(),
907            )
908            .await
909            .unwrap();
910            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
911            let req = match reader.next().await.unwrap().unwrap() {
912                Inbound::Frame(v) => v,
913                Inbound::Violation(_) => panic!("violation"),
914            };
915            assert_eq!(req["method"], "blob_grant");
916            assert_eq!(req["params"]["scope"], "kb-sync");
917            assert_eq!(req["params"]["principal"], "alice");
918            write_frame(
919                &mut writer,
920                &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ok":true}}),
921            )
922            .await
923            .unwrap();
924        });
925        let mut client = connect_control(&sock).await.unwrap();
926        client.blob_grant("kb-sync", "alice").await.unwrap();
927        server.await.unwrap();
928    }
929
930    /// The typed `status()` helper pairs `Request::Status` with `StatusResult` — the caller gets
931    /// the struct, not a `Value` to hand-deserialize (and a malformed result surfaces as
932    /// `ClientError::Malformed`, never a silently-wrong type).
933    #[tokio::test]
934    async fn typed_status_helper_deserializes_the_result() {
935        let (sock, _guard) = test_endpoint("typedstatus");
936        let listener = bind_local(&sock).unwrap();
937        let server = tokio::spawn(stub_daemon(listener));
938
939        let mut client = connect_control(&sock).await.unwrap();
940        let status = client.status().await.unwrap();
941        assert_eq!(status.stack_version, "0.1.0");
942        assert_eq!(status.services[0].name, "kb");
943        assert_eq!(status.services[0].backend, BackendKind::Socket);
944        assert!(status.peers.is_empty());
945        server.await.unwrap();
946    }
947
948    /// The ack-shaped typed helpers issue the right wire method and discard the `{}` ack; a
949    /// JSON-RPC error frame surfaces as `ClientError::Api`.
950    #[tokio::test]
951    async fn typed_ack_helpers_issue_requests_and_surface_api_errors() {
952        let (sock, _guard) = test_endpoint("typedack");
953        let listener = bind_local(&sock).unwrap();
954        let server = tokio::spawn(async move {
955            let mut listener = listener;
956            let stream = listener.accept().await.unwrap();
957            let (read_half, mut writer) = split_local(stream);
958            write_frame(
959                &mut writer,
960                &serde_json::to_value(Hello {
961                    api: API_NAME.into(),
962                    api_version: API_VERSION.into(),
963                    api_minor: 0,
964                    stack_version: "0.1.0".into(),
965                })
966                .unwrap(),
967            )
968            .await
969            .unwrap();
970            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
971            // peer_remove → ack.
972            let req = match reader.next().await.unwrap().unwrap() {
973                Inbound::Frame(v) => v,
974                Inbound::Violation(_) => panic!("violation"),
975            };
976            assert_eq!(req["method"], "peer_remove");
977            assert_eq!(req["params"]["nickname"], "bob");
978            write_frame(
979                &mut writer,
980                &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{}}),
981            )
982            .await
983            .unwrap();
984            // peer_rename → an error frame (collision refusal).
985            let req = match reader.next().await.unwrap().unwrap() {
986                Inbound::Frame(v) => v,
987                Inbound::Violation(_) => panic!("violation"),
988            };
989            assert_eq!(req["method"], "peer_rename");
990            assert_eq!(req["params"]["to"], "Bobby");
991            write_frame(
992                &mut writer,
993                &serde_json::json!({"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"taken"}}),
994            )
995            .await
996            .unwrap();
997        });
998
999        let mut client = connect_control(&sock).await.unwrap();
1000        client.peer_remove("bob").await.unwrap();
1001        match client.peer_rename(None, Some("bob".into()), "Bobby").await {
1002            Err(ClientError::Api(e)) => assert_eq!(e["message"], "taken"),
1003            other => panic!("expected Api error, got {other:?}"),
1004        }
1005        server.await.unwrap();
1006    }
1007
1008    /// The typed `subscribe()` upgrade yields `StreamFrame`s — snapshot, event, lagged — then
1009    /// `None` when the daemon side closes.
1010    #[tokio::test]
1011    async fn typed_subscribe_yields_frames_then_end() {
1012        use crate::protocol::{ActiveSession, AuditRecord, PeerReachability};
1013
1014        let (sock, _guard) = test_endpoint("subscribe");
1015        let listener = bind_local(&sock).unwrap();
1016        let server = tokio::spawn(async move {
1017            let mut listener = listener;
1018            let stream = listener.accept().await.unwrap();
1019            let (read_half, mut writer) = split_local(stream);
1020            write_frame(
1021                &mut writer,
1022                &serde_json::to_value(Hello {
1023                    api: API_NAME.into(),
1024                    api_version: API_VERSION.into(),
1025                    api_minor: 0,
1026                    stack_version: "0.1.0".into(),
1027                })
1028                .unwrap(),
1029            )
1030            .await
1031            .unwrap();
1032            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1033            let req = match reader.next().await.unwrap().unwrap() {
1034                Inbound::Frame(v) => v,
1035                Inbound::Violation(_) => panic!("violation"),
1036            };
1037            assert_eq!(req["method"], "subscribe");
1038            for frame in [
1039                StreamFrame::Snapshot {
1040                    self_network: None,
1041                    active_sessions: vec![ActiveSession {
1042                        peer: "bob".into(),
1043                        service: "notes".into(),
1044                        opened_at: 7,
1045                        principal: Some("eid:bob".into()),
1046                    }],
1047                    reachability: vec![PeerReachability {
1048                        name: "bob".into(),
1049                        reachable: true,
1050                        rtt_ms: Some(42),
1051                        age_secs: Some(3),
1052                        meta: String::new(),
1053                        principal: None,
1054                        path: Default::default(),
1055                    }],
1056                },
1057                StreamFrame::Event {
1058                    record: Box::new(AuditRecord::session_open(
1059                        "2026-07-03T14:02:11.480Z".into(),
1060                        Some("bob".into()),
1061                        "notes".into(),
1062                        None,
1063                    )),
1064                },
1065                StreamFrame::Lagged { dropped: 12 },
1066            ] {
1067                write_frame(&mut writer, &serde_json::to_value(&frame).unwrap())
1068                    .await
1069                    .unwrap();
1070            }
1071            writer.flush().await.unwrap();
1072            // Drop the connection: the client must see the stream END (Ok(None)), not an error.
1073        });
1074
1075        let client = connect_control(&sock).await.unwrap();
1076        let mut sub = client.subscribe().await.unwrap();
1077        match sub.next().await.unwrap().unwrap() {
1078            StreamFrame::Snapshot {
1079                active_sessions,
1080                reachability,
1081                ..
1082            } => {
1083                assert_eq!(active_sessions[0].peer, "bob");
1084                assert_eq!(reachability[0].rtt_ms, Some(42));
1085            }
1086            other => panic!("expected the snapshot first, got {other:?}"),
1087        }
1088        match sub.next().await.unwrap().unwrap() {
1089            StreamFrame::Event { record } => {
1090                assert_eq!(record.peer.as_deref(), Some("bob"));
1091                assert_eq!(record.service.as_deref(), Some("notes"));
1092            }
1093            other => panic!("expected the event, got {other:?}"),
1094        }
1095        assert_eq!(
1096            sub.next().await.unwrap(),
1097            Some(StreamFrame::Lagged { dropped: 12 })
1098        );
1099        assert_eq!(sub.next().await.unwrap(), None, "clean end of stream");
1100        server.await.unwrap();
1101    }
1102}