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