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