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