mcpmesh_local_api/protocol.rs
1//! mcpmesh-local/1 protocol types. Shared vocabulary between the daemon
2//! and its clients (porcelain, connect proxy, later the host shell). Wire framing
3//! is the family NDJSON codec — carried by the caller, not defined here.
4//!
5//! Request/response asymmetry: requests are one typed, closed enum (`Request`);
6//! responses are per-method typed structs deserialized from the JSON-RPC `result`
7//! Value — `Status` → [`StatusResult`], `RegisterService` → an ack, `OpenSession` →
8//! no JSON-RPC result at all: the socket STOPS being JSON-RPC and becomes a raw
9//! byte pipe.
10//!
11//! Additive-only: new fields (capabilities on `Hello`, groups/user_id on
12//! `PeerInfo`, device on `OpenSession`) MUST land as
13//! `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
14use serde::{Deserialize, Serialize};
15
16/// The first exchange on any `*-local/N` socket (the family's hello convention).
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18pub struct Hello {
19 pub api: String, // "mcpmesh-local/1"
20 pub api_version: String, // "MAJOR.MINOR" of the protocol surface (see API_MINOR)
21 /// The protocol-compatibility MINOR as an integer, for a trivial machine comparison
22 /// (`api_minor >= N`) without string parsing. Distinct from `stack_version` (the crate
23 /// release train). Additive: an older daemon omits it and it defaults to 0.
24 #[serde(default)]
25 pub api_minor: u32,
26 pub stack_version: String,
27}
28
29/// The kind of backend answering a service — the two valid values, enforced at the
30/// type level and kept in lockstep with `BackendSpec`'s variants. Status reports the
31/// kind only, never the command/path (no transport vocabulary).
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
33#[serde(rename_all = "snake_case")]
34pub enum BackendKind {
35 Run,
36 Socket,
37}
38
39/// A registered service as reported by `status` (no transport vocabulary).
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41pub struct ServiceInfo {
42 pub name: String,
43 pub allow: Vec<String>, // nicknames/groups (flat namespace)
44 pub backend: BackendKind, // "run" | "socket" (kind only, never the command/path)
45 /// True if this registration is ephemeral (#36): in-memory only, tied to the registering
46 /// control connection's lifetime, absent from config, gone on restart. Additive — an older
47 /// daemon omits it and it reads as `false` (the persistent default).
48 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
49 pub ephemeral: bool,
50}
51
52/// A known peer as reported by `status` (nickname only — never the EndpointId).
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub struct PeerInfo {
55 pub name: String,
56 pub services: Vec<String>,
57 /// The peer's PROVEN self-sovereign `user_id` (`b64u:<user_pk>`) if it presented a verified
58 /// device->user binding at pairing (roster peers carry it too), else `None` (nickname-only). This
59 /// is a surface-clean identity (an opaque user id, NOT an EndpointId). Additive:
60 /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so older payloads round-trip.
61 #[serde(default, skip_serializing_if = "Option::is_none")]
62 pub user_id: Option<String>,
63}
64
65/// Advisory reachability of a paired peer (pairing-mode liveness). Surface-clean:
66/// a nickname + a bool + latency/age NUMBERS — never an endpoint-id, key, or transport path.
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68pub struct PeerReachability {
69 pub name: String, // the peer's nickname
70 pub reachable: bool, // result of the last probe (false if never probed)
71 #[serde(default, skip_serializing_if = "Option::is_none")]
72 pub rtt_ms: Option<u64>, // last measured round-trip, if reachable
73 #[serde(default, skip_serializing_if = "Option::is_none")]
74 pub age_secs: Option<u64>, // None = never probed (consumer shows "checking…")
75}
76
77/// Roster-mode status. Surface-clean roster VOCABULARY only: org_id, serial, a plain
78/// state word, and the pinned org-root FINGERPRINT in short words — never raw keys/EndpointIds/serials-
79/// as-transport-vocab. Absent in a pure-pairing daemon.
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81pub struct RosterStatus {
82 pub org_id: String,
83 pub serial: u64,
84 pub state: String, // "pending" | "approved" | "degraded" | "stopped"
85 pub org_root_fingerprint: String, // short-word form
86}
87
88/// One reachable roster peer device as reported by `status` (the advisory presence read).
89/// ADVISORY — this is a display convenience, never an authorization surface. Surface-clean:
90/// FLAT vocabulary ONLY — a `user_id`, a human `device_label`, its `role` word, and an `online`
91/// boolean. It carries NO EndpointId / pubkey / hash / ALPN or any transport vocabulary.
92#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
93pub struct PresencePeer {
94 pub user_id: String,
95 pub device_label: String,
96 pub role: String, // "primary" | "mirror" (roster vocabulary)
97 /// Whether the device has a live presence heartbeat (advisory — absence never blocks a dial).
98 pub online: bool,
99}
100
101/// One recently completed INVITER-side pairing, surfaced by `status` so the inviter's human can
102/// read the short authentication code (SAS) and compare it with the redeemer's out-of-band —
103/// the pairing ceremony is "both humans compare the code": the redeemer sees it in its
104/// [`PairResult`]; this is the inviter's porcelain surface for the same words. DISPLAY-ONLY
105/// ceremony state: held in-memory by the daemon (a small ring), lost on restart, NEVER an
106/// authorization input or trust data. Surface-clean: a nickname + the SAS wordlist words +
107/// an epoch — never an EndpointId.
108#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
109pub struct RecentPairing {
110 /// The peer's nickname as stored by the inviter (its local name for the redeemer).
111 pub peer_nickname: String,
112 /// The display-only SAS words (e.g. `"tango-fig-cabbage"`) — the same code the redeemer's
113 /// `PairResult.sas_code` carried. Never checked programmatically.
114 pub sas_code: String,
115 /// When the pairing completed (epoch seconds) — the porcelain renders a friendly age.
116 pub paired_at_epoch: u64,
117}
118
119#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
120pub struct StatusResult {
121 pub stack_version: String,
122 pub services: Vec<ServiceInfo>,
123 pub peers: Vec<PeerInfo>,
124 /// Roster-mode status, absent in a pure-pairing daemon. Additive:
125 /// `#[serde(default, skip_serializing_if = ...)]` so a daemon/client without it round-trips.
126 #[serde(default, skip_serializing_if = "Option::is_none")]
127 pub roster: Option<RosterStatus>,
128 /// The reachable roster peer devices (the advisory presence read), each with an `online`
129 /// flag. Empty in a pure-pairing daemon / when no roster is installed. Additive:
130 /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
131 #[serde(default, skip_serializing_if = "Vec::is_empty")]
132 pub presence: Vec<PresencePeer>,
133 /// THIS daemon's own self-sovereign `user_id` (`b64u:<user_pk>`), if it has a user key (auto-
134 /// minted at boot; shared by pairing AND roster mode). Lets the operator see + share their stable
135 /// identity that multiple devices resolve to. `None` only when no user key exists. Additive:
136 /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so an older payload round-trips.
137 #[serde(default, skip_serializing_if = "Option::is_none")]
138 pub self_user_id: Option<String>,
139 /// Recent INVITER-side pairing completions, newest first (display-only pairing-ceremony aids —
140 /// see [`RecentPairing`]; in-memory on the daemon, cleared by a restart). Empty on a daemon
141 /// that has accepted no pairing since it started. Additive:
142 /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
143 #[serde(default, skip_serializing_if = "Vec::is_empty")]
144 pub recent_pairings: Vec<RecentPairing>,
145 /// Advisory reachability of paired peers, from the on-demand probe cache. Empty until the
146 /// first probe completes. Additive: default + skip-if-empty.
147 #[serde(default, skip_serializing_if = "Vec::is_empty")]
148 pub reachability: Vec<PeerReachability>,
149}
150
151/// Params of [`Request::RegisterService`]: the `[services.*]` entry to write/update.
152#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
153#[serde(deny_unknown_fields)]
154pub struct RegisterServiceParams {
155 pub name: String,
156 pub backend: BackendSpec,
157 pub allow: Vec<String>,
158 /// When true (#36), the registration is EPHEMERAL: kept in daemon memory only, never written
159 /// to the on-disk config, and automatically unregistered when the control connection that
160 /// registered it closes (and gone on daemon restart). For an embedder that serves a
161 /// `socket` backend from a fresh path each run, this removes the need to derive a stable
162 /// socket path solely to keep a persisted registration valid, and the stale-registration
163 /// accumulation that comes with no unregister. Default false = the persistent behavior.
164 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
165 pub ephemeral: bool,
166}
167
168/// Params of [`Request::Invite`]: the services the minted invite grants. Rejects unknown
169/// fields (so `{service: "kb"}` — a singular typo — is a loud error, not a silently
170/// grants-nothing invite), and the daemon additionally rejects an empty/absent `services`
171/// list (an invite that grants nothing is useless — #34).
172#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
173#[serde(deny_unknown_fields)]
174pub struct InviteParams {
175 #[serde(default)]
176 pub services: Vec<String>,
177 /// An OPAQUE, caller-chosen label carried through to the redeemer in the `pair` result (#31).
178 /// mcpmesh never interprets it (not a nickname, never resolved or authorized) — a per-pairing
179 /// metadata slot for the embedder (e.g. its own URN). Capped at the daemon; omit for none.
180 #[serde(default, skip_serializing_if = "Option::is_none")]
181 pub app_label: Option<String>,
182}
183
184/// Params of [`Request::Pair`]: the copyable `mcpmesh-invite:` line. Defaultable — an
185/// absent field reads as an empty line, which simply fails to decode (a clean pair error).
186#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
187#[serde(deny_unknown_fields)]
188pub struct PairParams {
189 #[serde(default)]
190 pub invite_line: String,
191}
192
193/// Params of [`Request::PeerRemove`]: the nickname to unpair.
194#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
195#[serde(deny_unknown_fields)]
196pub struct PeerRemoveParams {
197 pub nickname: String,
198}
199
200/// Params of [`Request::PeerRename`]: the contact to rename — every device sharing `user_id`
201/// when given, else the single provisional `nickname` entry — and the new nickname `to`.
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203#[serde(deny_unknown_fields)]
204pub struct PeerRenameParams {
205 #[serde(default)]
206 pub user_id: Option<String>,
207 #[serde(default)]
208 pub nickname: Option<String>,
209 pub to: String,
210}
211
212/// Params of [`Request::PeerAdd`] (reserved/internal — see the variant): a raw `endpoint_id`
213/// (iroh base32) plus the nickname and service allow list to install it under.
214#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
215#[serde(deny_unknown_fields)]
216pub struct PeerAddParams {
217 pub nickname: String,
218 pub endpoint_id: String,
219 #[serde(default)]
220 pub allow: Vec<String>,
221}
222
223/// Params of [`Request::OpenSession`]: the `peer/service` target to dial. Both fields are
224/// defaultable — an empty target simply fails the dial (a clean `-32055` error).
225#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
226#[serde(deny_unknown_fields)]
227pub struct OpenSessionParams {
228 #[serde(default)]
229 pub peer: String,
230 #[serde(default)]
231 pub service: String,
232}
233
234/// Params of [`Request::RosterInstall`]: the LOCAL roster file `path`, plus the org-root pin
235/// on FIRST install (`b64u:`; omit once pinned — config carries it).
236#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
237#[serde(deny_unknown_fields)]
238pub struct RosterInstallParams {
239 pub path: String,
240 #[serde(default, skip_serializing_if = "Option::is_none")]
241 pub org_root_pk: Option<String>,
242}
243
244/// Params of [`Request::OrgJoin`]: the `[identity]` pin. `user_key` is a LOCAL path — the key
245/// never crosses the API.
246#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
247#[serde(deny_unknown_fields)]
248pub struct OrgJoinParams {
249 pub org_id: String,
250 pub org_root_pk: String,
251 pub user_id: String,
252 pub user_key: String,
253}
254
255/// Params of [`Request::SetRosterUrl`]: the HTTPS roster URL to pin.
256#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
257#[serde(deny_unknown_fields)]
258pub struct SetRosterUrlParams {
259 pub url: String,
260}
261
262/// Params of [`Request::BlobPublish`]: the scope to publish into and the LOCAL file to add.
263#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
264#[serde(deny_unknown_fields)]
265pub struct BlobPublishParams {
266 pub scope: String,
267 pub path: String,
268}
269
270/// Params of [`Request::BlobGrant`]: the scope and the flat-namespace principal to grant it to.
271#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
272#[serde(deny_unknown_fields)]
273pub struct BlobGrantParams {
274 pub scope: String,
275 pub principal: String,
276}
277
278/// Params of [`Request::BlobFetch`]: the `mcpmesh/blob/1` ticket and the LOCAL export path.
279#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
280#[serde(deny_unknown_fields)]
281pub struct BlobFetchParams {
282 pub ticket: String,
283 pub dest_path: String,
284}
285
286/// Control-API requests. Serialized as `{ "method": "...", "params": {...} }`
287/// (JSON-RPC-shaped; the id/jsonrpc envelope is added by the transport layer).
288///
289/// Each param-carrying variant wraps its named `*Params` struct — the ONE wire truth for that
290/// method's params, shared by clients (which serialize whole `Request`s) and the daemon (which
291/// deserializes `params` into the same struct after its method-string dispatch). Adjacent
292/// tagging serializes a newtype variant's content as the struct's fields, so the wire shape is
293/// identical to inline variant bodies.
294///
295/// **Servers dispatch on the `method` string and deserialize `params` per-method** — tolerating
296/// omitted / null / empty-object params for parameterless methods — rather than deserializing a
297/// whole message into `Request` (adjacent tagging rejects `params:{}` for unit variants).
298/// This keeps the wire tolerant for third-party clients (the versioned, additive-only surface).
299/// Use [`method_of`] to extract the tag, then match + deserialize `params` per-method.
300#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
301#[serde(tag = "method", content = "params", rename_all = "snake_case")]
302pub enum Request {
303 /// Register/update a `[services.*]` entry idempotently.
304 RegisterService(RegisterServiceParams),
305 Status,
306 /// Mint a one-time pairing invite granting `services`. The daemon
307 /// answers an [`InviteResult`] carrying the copyable `mcpmesh-invite:` line. Tag
308 /// `"invite"` (snake_case). `method_of` needs no per-variant arm — it reads the
309 /// `method` string generically; the tag comes from `rename_all`.
310 Invite(InviteParams),
311 /// Redeem a pairing invite. The daemon dials the inviter named by
312 /// `invite_line` on `mcpmesh/pair/1`, proves the secret, writes the mutual
313 /// (dial-back) `PeerEntry`, and answers a [`PairResult`]. Tag `"pair"`
314 /// (snake_case); `method_of` reads the `method` string generically.
315 ///
316 /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
317 Pair(PairParams),
318 /// Remove a paired peer by nickname (`mcpmesh pair --remove`). The daemon drops the
319 /// peer's `PeerEntry` (identity) AND revokes its access by removing the nickname from every
320 /// `[services.*].allow` (authorization) — the inverse of the pairing grant. Idempotent: a
321 /// nickname with no entry / no allow membership is a clean no-op. Live in-flight sessions are
322 /// NOT severed here: existing sessions run to completion; the peer only loses the
323 /// ability to establish NEW authorized sessions. Tag `"peer_remove"` (snake_case);
324 /// `method_of` reads the `method` string generically (no per-variant arm).
325 ///
326 /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
327 PeerRemove(PeerRemoveParams),
328 /// Rename a contact's nickname (nickname) authoritatively. Renames the
329 /// PERSON — every `PeerEntry` sharing `user_id` when given (one op for all their devices), else the
330 /// single `nickname` entry (a provisional, no-`user_id` contact) — to `to`, AND rewrites the old
331 /// nickname → `to` in every `[services.*].allow` so grants follow the rename. Refuses (error frame)
332 /// when `to` is empty or already names/grants a DIFFERENT identity — the same collision guard the
333 /// pairing rendezvous uses, so a rename can't inherit another peer's access. Tag `"peer_rename"`;
334 /// host-privileged like the other pair ops.
335 PeerRename(PeerRenameParams),
336 /// RESERVED / INTERNAL (`docs/local-protocol.md` "Reserved / internal methods"): install a
337 /// peer directly from a raw `endpoint_id` — the trust-population stand-in for pairing behind
338 /// `mcpmesh internal peer add`. A deliberate, documented exception to the surface discipline
339 /// (raw endpoint identifiers otherwise never cross this socket); NOT part of the stable
340 /// vocabulary — do not build on it. Tag `"peer_add"`.
341 PeerAdd(PeerAddParams),
342 /// Open a mesh session to `peer/service`; the daemon dials and pipes.
343 /// Distinct from the proxy's job: this returns a session the client streams.
344 /// Named `open_session` rather than `connect` to avoid colliding
345 /// with the `connect` porcelain.
346 OpenSession(OpenSessionParams),
347 /// Install a signed roster from a local file (the manual `internal roster install` path).
348 /// `path` is a LOCAL file the same-uid daemon reads (the daemon runs as the caller's own
349 /// uid, so passing a path rather than the bytes crosses no trust boundary). `org_root_pk`
350 /// pins the org root on FIRST install (`b64u:`); omit it
351 /// once pinned (config carries it). Tag `"roster_install"`.
352 RosterInstall(RosterInstallParams),
353 /// Pin the org root on a JOINER — WITHOUT a roster (the joiner has none yet; its poll loop
354 /// fetches the first one). Records `[identity]` org_id / org_root_pk / user_id / user_key.
355 /// `user_key` is a LOCAL path
356 /// (the key never crosses the API). Tag `"org_join"`.
357 OrgJoin(OrgJoinParams),
358 /// Pin the HTTPS roster URL (`[roster].url`) in config. Written by `org create
359 /// --roster-url` (the operator keeps it current) AND by `join` when the org invite carries one —
360 /// so the joiner's poll loop bootstraps its FIRST roster. The daemon writes it under
361 /// `reload_lock` (single-writer), then the poll loop picks it up on the next daemon start. Tag
362 /// `"set_roster_url"`.
363 SetRosterUrl(SetRosterUrlParams),
364 /// Publish a LOCAL file INTO a scope: the daemon adds the bytes to its gated
365 /// app-blob store and records the hash in `scope`. `path` is a local file the same-uid daemon
366 /// reads. Answers a [`BlobPublishResult`] carrying the `mcpmesh/blob/1` ticket + hash.
367 /// Tag `"blob_publish"`.
368 BlobPublish(BlobPublishParams),
369 /// Grant a scope to a principal — any flat-namespace entry: a group name, a user_id, or a
370 /// nickname (the shared `principal_set` expansion). Tag
371 /// `"blob_grant"`.
372 BlobGrant(BlobGrantParams),
373 /// List the daemon's blob scopes (name → hashes + grants). Tag `"blob_list"`.
374 BlobList,
375 /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified streaming) and export the
376 /// verified blob to `dest_path` (a local file the same-uid daemon writes). Answers a
377 /// [`BlobFetchResult`] with the verified hash + byte length. Tag `"blob_fetch"`.
378 BlobFetch(BlobFetchParams),
379 /// Summarize this node's LOCAL audit log into per-peer / per-service SESSION counts
380 /// (local-only — the daemon reads its OWN audit dir, nothing is transmitted). The host Mesh surface
381 /// renders these as "who serves me / whom I serve / session counts". Parameterless (like `Status`);
382 /// the server dispatches on the `method` string. Tag `"audit_summary"` (snake_case);
383 /// `method_of` reads the `method` string generically (no per-variant arm).
384 AuditSummary,
385 /// Open a live event stream (pairing liveness & health telemetry). Like `open_session`, the
386 /// connection STOPS being request/response after this call and becomes a one-way push stream
387 /// of `StreamFrame`s. Parameterless. Tag `"subscribe"`.
388 Subscribe,
389}
390
391/// Result of [`Request::OrgJoin`] — the pinned org id echoed back (surface-clean; the fingerprint is
392/// computed porcelain-side from the invite's org_root_pk). Additive-only.
393#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
394pub struct OrgJoinResult {
395 pub org_id: String,
396}
397
398/// Result of a [`Request::RosterInstall`] request (the manual install path): the installed roster's
399/// org id + serial (roster-status vocabulary the confirmation line is permitted to render) plus how
400/// many live sessions the install severed. Surface-clean: NO keys / EndpointIds / paths.
401///
402/// Additive-only: any future field MUST land as
403/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
404#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
405pub struct RosterInstallResult {
406 pub org_id: String,
407 pub serial: u64,
408 /// How many live sessions were severed, for the porcelain's confirmation line.
409 #[serde(default)]
410 pub severed: u32,
411}
412
413/// Result of [`Request::BlobPublish`]: the copyable `mcpmesh/blob/1` ticket + the blob's blake3 hash.
414/// A ticket/hash here is blob-reference vocabulary (NOT a transport-vocab leak — the same
415/// carve-out as the pairing invite line). Additive-only.
416#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
417pub struct BlobPublishResult {
418 pub ticket: String,
419 pub hash: String, // bare blake3 hex
420}
421
422/// One scope in a [`BlobScopeList`]: its name + the hashes it contains + the principals it
423/// grants. Flat vocabulary ONLY — no EndpointId/pubkey/ALPN. Additive-only.
424#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
425pub struct ScopeInfo {
426 pub name: String,
427 pub hashes: Vec<String>,
428 pub grants: Vec<String>,
429}
430
431/// Result of [`Request::BlobList`]: the daemon's scopes. Additive-only.
432#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
433pub struct BlobScopeList {
434 pub scopes: Vec<ScopeInfo>,
435}
436
437/// Result of [`Request::BlobFetch`]: the verified hash + byte length written to `dest_path`.
438/// Additive-only.
439#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
440pub struct BlobFetchResult {
441 pub hash: String,
442 pub bytes_len: u64,
443}
444
445/// Result of [`Request::AuditSummary`]: LOCAL per-peer / per-service session counts
446/// aggregated from this node's OWN audit log — NEVER transmitted (local-only). Surface-clean:
447/// peer names are nicknames / user_ids (NEVER EndpointIds), service names are the registered
448/// service names (NEVER transport vocabulary). A "session" is one `SessionOpen` record. `per_peer` /
449/// `per_service` are sorted ascending by name (deterministic). Tuples mirror kb's
450/// `InsightResponse::per_peer_contribution` — `["bob", 2]` on the wire.
451///
452/// Additive-only: any future field MUST land as
453/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
454#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
455pub struct AuditSummaryResult {
456 /// Sessions opened per peer (nickname). A session with no attributed peer is NOT counted here (no
457 /// peer to attribute) but IS in `total_sessions`.
458 pub per_peer: Vec<(String, u64)>,
459 /// Sessions opened per registered service name.
460 pub per_service: Vec<(String, u64)>,
461 /// Total sessions opened (every `SessionOpen` record, including peer-less ones).
462 #[serde(default)]
463 pub total_sessions: u64,
464}
465
466/// Result of an [`Request::Invite`] request: the copyable `mcpmesh-invite:` artifact
467/// (the ONE pairing artifact deliberately carved out of the
468/// transport-vocabulary blocklist, so this is NOT a transport-vocab leak) plus its
469/// absolute expiry in epoch seconds (≤ now + 24h).
470///
471/// `invite` returns BEFORE any redemption, so the SAS — which is derived from the redeemer's
472/// endpoint id, unknown until they redeem — cannot appear here. The inviter reads its side of
473/// the SAS from [`StatusResult::recent_pairings`] once a redemption completes (a `trust`/`pair`
474/// frame on the live [`StreamFrame`] stream signals that moment). See the "embedding the pairing
475/// ceremony" note in `docs/local-protocol.md` (#35).
476///
477/// Additive-only: any future field MUST land as `#[serde(default, skip_serializing_if = ...)]`
478/// so older payloads still deserialize.
479#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
480pub struct InviteResult {
481 /// The `mcpmesh-invite:<base32>` line, copied out-of-band to the redeemer.
482 pub invite_line: String,
483 /// When the invite expires (epoch seconds); the daemon burns it at redemption or expiry.
484 pub expires_at_epoch: u64,
485}
486
487/// Result of a [`Request::Pair`] request: the inviter's suggested nickname (the
488/// redeemer's local name for the new peer) plus the display-only short authentication
489/// code (SAS) — a few words the human reads aloud to a second channel to
490/// catch a whole-invite forgery / address-swap MITM. The SAS is a pairing-ceremony
491/// artifact (like the invite line), NOT a transport-vocabulary leak.
492///
493/// Additive-only: any future field MUST land as
494/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
495#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
496pub struct PairResult {
497 /// The inviter's suggested nickname (from the invite) — the redeemer's local name for it.
498 pub peer_nickname: String,
499 /// The display-only short authentication code (e.g. `"tango-fig-42"`), shown on both
500 /// sides for the out-of-band human check. Never sent on the wire, never checked
501 /// programmatically.
502 pub sas_code: String,
503 /// The services this pairing granted the redeemer — each mountable as `<peer>/<service>`.
504 /// Populated from the invite (`invite.services`) by the redeemer-side `redeem_invite`, so
505 /// the porcelain can print the "You can mount: alice/notes" line without re-decoding the
506 /// invite. Additive: `#[serde(default, skip_serializing_if = ...)]` so a `PairResult`
507 /// minted by an older daemon (which omits `services`) still deserializes — to an empty list.
508 #[serde(default, skip_serializing_if = "Vec::is_empty")]
509 pub services: Vec<String>,
510 /// The opaque `app_label` the inviter attached at `invite` time (#31), echoed verbatim — or
511 /// absent if none was set. mcpmesh never interprets it; the embedder does. Additive.
512 #[serde(default, skip_serializing_if = "Option::is_none")]
513 pub app_label: Option<String>,
514 /// The inviter's proven self-sovereign `user_id` (`b64u:<user_pk>`), when it presented a
515 /// device→user binding at pairing (#30). This is the STABLE, portable identity the redeemer
516 /// can align with its own — and the same value it may later pass to `open_session` to dial
517 /// this peer by identity rather than by local nickname. `None` if the inviter presented no
518 /// binding (a legacy/keyless peer). Additive.
519 #[serde(default, skip_serializing_if = "Option::is_none")]
520 pub peer_user_id: Option<String>,
521}
522
523/// The event class of an [`AuditRecord`] (the four audit event classes). An additive discriminant on
524/// top of the base record schema: it removes no field and makes the JSONL self-describing so
525/// a consumer can filter by class without guessing from which optional fields are present.
526#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
527#[serde(rename_all = "snake_case")]
528pub enum AuditKind {
529 /// A mesh session opened (a backend was selected for an authenticated peer).
530 /// (A `session_open` with `status:"error"` is a synthesized FAILED-dial marker — no backend
531 /// was reached; it records an attempted-and-failed reach for the telemetry stream.)
532 SessionOpen,
533 /// A mesh session closed (the backend returned / the session tore down).
534 SessionClose,
535 /// One proxied MCP request line (method + tool NAME + args_hash). NEVER carries raw arguments.
536 Request,
537 /// A peer fetched a blob from this node's gated provider (peer + hash + allow/deny).
538 BlobFetch,
539 /// A trust mutation (pair, unpair, roster install/swap, revoke).
540 Trust,
541}
542
543/// One audit record — the union of the event classes, and the `record` payload of a
544/// [`StreamFrame::Event`]. ONE schema for the on-disk JSONL log and the live stream. Every field
545/// beyond `ts`/`kind` is optional and elided when absent (`skip_serializing_if`), so each class
546/// serializes to just its relevant keys (a session record has no `method`; a trust record has no
547/// `bytes_out`).
548///
549/// PRIVACY: the proxied-request record carries `method` + `tool` (NAME only) +
550/// `args_hash` (`"blake3:<hex>"`), and NEVER the raw arguments, the request/response content, or
551/// any tool-output bytes — only a `bytes_out` COUNT and a `status`.
552#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
553pub struct AuditRecord {
554 /// RFC3339 UTC with millisecond precision, e.g. `"2026-07-03T14:02:11.480Z"`. The `YYYY-MM`
555 /// prefix also selects the monthly file (the rotation boundary), so it is always present.
556 pub ts: String,
557 pub kind: AuditKind,
558 /// The gate-resolved authenticated peer (attributed by the endpoint_id-keyed trust gate). Absent on
559 /// local-only events with no remote peer (a manual roster install).
560 #[serde(skip_serializing_if = "Option::is_none")]
561 pub peer: Option<String>,
562 #[serde(skip_serializing_if = "Option::is_none")]
563 pub service: Option<String>,
564 #[serde(skip_serializing_if = "Option::is_none")]
565 pub method: Option<String>,
566 /// The tool NAME only (never its arguments or output) — e.g. `"read_file"` for a `tools/call`.
567 #[serde(skip_serializing_if = "Option::is_none")]
568 pub tool: Option<String>,
569 /// `"blake3:<hex>"` of the request arguments. The raw arguments are NEVER stored.
570 #[serde(skip_serializing_if = "Option::is_none")]
571 pub args_hash: Option<String>,
572 /// Byte COUNT of the response sent back to the peer — a count, never the content.
573 #[serde(skip_serializing_if = "Option::is_none")]
574 pub bytes_out: Option<u64>,
575 /// `"ok"` / `"error"` (proxied request) or `"ok"` / `"denied"` (blob fetch).
576 #[serde(skip_serializing_if = "Option::is_none")]
577 pub status: Option<String>,
578 #[serde(skip_serializing_if = "Option::is_none")]
579 pub latency_ms: Option<u64>,
580 /// Trust-event verb: `"pair"` / `"unpair"` / `"roster_install"` / `"revoke"` (kind == Trust).
581 #[serde(skip_serializing_if = "Option::is_none")]
582 pub event: Option<String>,
583 /// A reference, NEVER content: a blob hash (`BlobFetch`) or a trust-event target such as a
584 /// nickname or `org/serial` (`Trust`).
585 #[serde(skip_serializing_if = "Option::is_none")]
586 pub target: Option<String>,
587}
588
589impl AuditRecord {
590 fn base(ts: String, kind: AuditKind) -> Self {
591 Self {
592 ts,
593 kind,
594 peer: None,
595 service: None,
596 method: None,
597 tool: None,
598 args_hash: None,
599 bytes_out: None,
600 status: None,
601 latency_ms: None,
602 event: None,
603 target: None,
604 }
605 }
606
607 pub fn session_open(ts: String, peer: Option<String>, service: String) -> Self {
608 let mut r = Self::base(ts, AuditKind::SessionOpen);
609 r.peer = peer;
610 r.service = Some(service);
611 r
612 }
613
614 /// Set the record's `status` (`"ok"`/`"error"`/`"denied"`), returning `self` for chaining.
615 /// Marks a synthesized failure record — e.g. the `session_open` for a FAILED dial, which
616 /// reaches no backend and so is never audited by the far side's session guard — without a
617 /// dedicated constructor. DRY: reuses the existing optional `status` field.
618 pub fn with_status(mut self, status: &str) -> Self {
619 self.status = Some(status.into());
620 self
621 }
622
623 pub fn session_close(ts: String, peer: Option<String>, service: String) -> Self {
624 let mut r = Self::base(ts, AuditKind::SessionClose);
625 r.peer = peer;
626 r.service = Some(service);
627 r
628 }
629
630 /// A completed (request→response correlated) proxied line: method + tool NAME + args_hash, plus
631 /// the response's `bytes_out` COUNT, `status`, and `latency_ms`. PRIVACY: `args_hash` is a digest;
632 /// no raw arguments, request/response content, or tool-output bytes are ever passed in.
633 #[allow(clippy::too_many_arguments)]
634 pub fn proxied_request(
635 ts: String,
636 peer: Option<String>,
637 service: String,
638 method: String,
639 tool: Option<String>,
640 args_hash: String,
641 bytes_out: u64,
642 status: String,
643 latency_ms: u64,
644 ) -> Self {
645 let mut r = Self::base(ts, AuditKind::Request);
646 r.peer = peer;
647 r.service = Some(service);
648 r.method = Some(method);
649 r.tool = tool;
650 r.args_hash = Some(args_hash);
651 r.bytes_out = Some(bytes_out);
652 r.status = Some(status);
653 r.latency_ms = Some(latency_ms);
654 r
655 }
656
657 /// A proxied NOTIFICATION line (no `id`, so no response correlates): method + tool + args_hash,
658 /// no `bytes_out`/`status`/`latency_ms`. The line is still recorded — every proxied request is audited.
659 pub fn proxied_notification(
660 ts: String,
661 peer: Option<String>,
662 service: String,
663 method: String,
664 tool: Option<String>,
665 args_hash: String,
666 ) -> Self {
667 let mut r = Self::base(ts, AuditKind::Request);
668 r.peer = peer;
669 r.service = Some(service);
670 r.method = Some(method);
671 r.tool = tool;
672 r.args_hash = Some(args_hash);
673 r
674 }
675
676 pub fn blob_fetch(ts: String, peer: Option<String>, hash: String, status: String) -> Self {
677 let mut r = Self::base(ts, AuditKind::BlobFetch);
678 r.peer = peer;
679 r.target = Some(hash);
680 r.status = Some(status);
681 r
682 }
683
684 pub fn trust(ts: String, event: String, target: Option<String>) -> Self {
685 let mut r = Self::base(ts, AuditKind::Trust);
686 r.event = Some(event);
687 r.target = target;
688 r
689 }
690}
691
692/// One live mesh session, in a [`StreamFrame::Snapshot`]. Surface-clean: `peer` is the
693/// user_id-or-nickname the audit records carry, never an endpoint-id. `opened_at` is epoch seconds.
694#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
695pub struct ActiveSession {
696 pub peer: String,
697 pub service: String,
698 pub opened_at: i64,
699}
700
701/// One frame of the [`Request::Subscribe`] stream (pairing liveness & health telemetry). Tagged on
702/// `type` (snake_case), so a frame is `{"type":"snapshot",...}` / `{"type":"event",...}` /
703/// `{"type":"lagged",...}`. `Event.record` is the [`AuditRecord`] verbatim, so the stream and the
704/// on-disk log carry ONE schema. The daemon serializes these; an embedding consumer deserializes
705/// them (see `docs/local-protocol.md` "Live event stream").
706#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
707#[serde(tag = "type", rename_all = "snake_case")]
708pub enum StreamFrame {
709 /// The FIRST frame: a point-in-time picture of the mesh (open sessions + paired-peer
710 /// reachability) so a fresh subscriber renders immediately without replaying history.
711 Snapshot {
712 active_sessions: Vec<ActiveSession>,
713 reachability: Vec<PeerReachability>,
714 },
715 /// A live audit event (session open/close, request, blob fetch, trust) — the tap on the hub.
716 /// Boxed so this (much larger) variant does not bloat every frame; serde delegates through the
717 /// `Box`, so the wire shape is the record's fields verbatim.
718 Event { record: Box<AuditRecord> },
719 /// The subscriber fell `dropped` records behind the broadcast ring; the stream continues (a
720 /// fresh reconnect would re-`Snapshot`). Never drops the subscriber — lag is reported, never fatal.
721 Lagged { dropped: u64 },
722}
723
724/// Extract the `method` tag from a raw request value without deserializing the whole
725/// message. The daemon's dispatcher uses this: match on the method string, then deserialize
726/// `params` per-method — which tolerates omitted / null / `{}` params for parameterless
727/// methods (adjacent tagging rejects `params:{}` on unit variants).
728pub fn method_of(v: &serde_json::Value) -> Option<&str> {
729 v.get("method").and_then(serde_json::Value::as_str)
730}
731
732/// How a service is answered. Mirrors the config `[services.*]` *kinds*;
733/// Config→BackendSpec is a hand-written match, not a serde passthrough.
734#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
735#[serde(rename_all = "snake_case")]
736pub enum BackendSpec {
737 Run { cmd: Vec<String> },
738 Socket { path: String },
739}
740
741pub const API_NAME: &str = "mcpmesh-local/1";
742/// The protocol-compatibility version as `"MAJOR.MINOR"`, distinct from the crate/stack version.
743///
744/// - **MAJOR** matches the `/N` in [`API_NAME`] and changes only on a breaking wire change (the
745/// transport already rejects a mismatched `api`, so an equality check on that is redundant).
746/// - **MINOR** ([`API_MINOR`]) increments on EVERY surface change within a major — additive fields,
747/// new methods, or a strictness change like params validation — bumped in the same change that
748/// makes it. A client can guard with `api_minor >= N` for a feature it needs, or refuse a daemon
749/// older than a minor it requires. It never resets except on a MAJOR bump.
750pub const API_VERSION: &str = "1.1";
751/// The integer MINOR of [`API_VERSION`] — see there. Bumped from 0 to 1 when params validation
752/// became strict (#34), the first change that made this field worth checking.
753pub const API_MINOR: u32 = 1;
754
755#[cfg(test)]
756mod tests {
757 use super::*;
758
759 #[test]
760 fn peer_reachability_serde_is_additive() {
761 let r = PeerReachability {
762 name: "bob".into(),
763 reachable: true,
764 rtt_ms: Some(42),
765 age_secs: Some(3),
766 };
767 let v = serde_json::to_value(&r).unwrap();
768 assert_eq!(v["name"], "bob");
769 assert_eq!(v["reachable"], true);
770 assert_eq!(v["rtt_ms"], 42);
771 assert_eq!(v["age_secs"], 3);
772 // Never-probed peer: optionals elided, not null.
773 let unknown = PeerReachability {
774 name: "carol".into(),
775 reachable: false,
776 rtt_ms: None,
777 age_secs: None,
778 };
779 let uv = serde_json::to_value(&unknown).unwrap();
780 assert!(uv.get("rtt_ms").is_none() && uv.get("age_secs").is_none());
781 // An older StatusResult (no reachability field) still deserializes.
782 let old = serde_json::json!({"stack_version":"0.1.0","services":[],"peers":[]});
783 let s: StatusResult = serde_json::from_value(old).unwrap();
784 assert!(s.reachability.is_empty());
785 }
786
787 #[test]
788 fn subscribe_method_tag_resolves() {
789 let req = serde_json::to_value(Request::Subscribe).unwrap();
790 assert_eq!(method_of(&req), Some("subscribe"));
791 }
792
793 // --- #34: params structs reject unknown fields (the `{service: "kb"}` silent-accept bug) ---
794
795 #[test]
796 fn invite_params_reject_singular_service_typo() {
797 // The reported bug: `{"service":"kb"}` (singular) used to deserialize to
798 // InviteParams { services: [] } and mint a grants-nothing invite that looked
799 // successful. With deny_unknown_fields the typo is a loud parse error instead.
800 let err = serde_json::from_value::<InviteParams>(serde_json::json!({"service": "kb"}));
801 assert!(
802 err.is_err(),
803 "an unknown `service` key must be rejected, not silently ignored"
804 );
805 // The correct plural shape still parses.
806 let ok: InviteParams =
807 serde_json::from_value(serde_json::json!({"services": ["kb"]})).unwrap();
808 assert_eq!(ok.services, vec!["kb".to_string()]);
809 }
810
811 #[test]
812 fn open_session_params_reject_unknown_field() {
813 let err = serde_json::from_value::<OpenSessionParams>(
814 serde_json::json!({"peer": "a", "service": "b", "nonsense": 1}),
815 );
816 assert!(err.is_err(), "unknown params keys must be rejected");
817 }
818
819 #[test]
820 fn api_minor_is_present_and_monotonic_from_hello() {
821 // #34 part 2: a machine-comparable protocol-compat minor, distinct from the
822 // crate/stack version, additive on the Hello frame.
823 let h = Hello {
824 api: API_NAME.into(),
825 api_version: API_VERSION.into(),
826 api_minor: API_MINOR,
827 stack_version: "9.9.9".into(),
828 };
829 let v = serde_json::to_value(&h).unwrap();
830 assert_eq!(v["api_minor"], API_MINOR);
831 // An OLD Hello without api_minor still deserializes (additive contract).
832 let old = serde_json::json!({
833 "api": API_NAME, "api_version": "1.0", "stack_version": "0.4.0"
834 });
835 let back: Hello = serde_json::from_value(old).unwrap();
836 assert_eq!(back.api_minor, 0, "absent api_minor defaults to 0");
837 }
838
839 #[test]
840 fn hello_result_roundtrips() {
841 let h = Hello {
842 api: "mcpmesh-local/1".into(),
843 api_version: "1.0".into(),
844 api_minor: 0,
845 stack_version: "0.1.0".into(),
846 };
847 let v = serde_json::to_value(&h).unwrap();
848 assert_eq!(v["api"], "mcpmesh-local/1");
849 let back: Hello = serde_json::from_value(v).unwrap();
850 assert_eq!(back, h);
851 }
852
853 #[test]
854 fn request_tagged_by_method() {
855 let r = Request::Status;
856 assert_eq!(serde_json::to_value(&r).unwrap()["method"], "status");
857 let r = Request::OpenSession(OpenSessionParams {
858 peer: "alice".into(),
859 service: "notes".into(),
860 });
861 let v = serde_json::to_value(&r).unwrap();
862 assert_eq!(v["method"], "open_session");
863 assert_eq!(v["params"]["peer"], "alice");
864 }
865
866 #[test]
867 fn parameterless_method_tolerates_params_forms() {
868 // Omitted and null params deserialize straight into the unit variant.
869 let omitted: Request =
870 serde_json::from_value(serde_json::json!({"method": "status"})).unwrap();
871 assert_eq!(omitted, Request::Status);
872 let null: Request =
873 serde_json::from_value(serde_json::json!({"method": "status", "params": null}))
874 .unwrap();
875 assert_eq!(null, Request::Status);
876
877 // Known limitation: adjacent tagging rejects `params:{}` for a unit variant, so
878 // the server MUST dispatch on the method string rather than deserialize the whole
879 // message into `Request`. This is the pattern the daemon's dispatcher uses.
880 let empty = serde_json::json!({"method": "status", "params": {}});
881 assert!(serde_json::from_value::<Request>(empty.clone()).is_err());
882 match method_of(&empty) {
883 Some("status") => {} // dispatcher resolves Status via the method string
884 other => panic!("method_of failed to resolve status: {other:?}"),
885 }
886 }
887
888 #[test]
889 fn backend_spec_roundtrips() {
890 let run = BackendSpec::Run {
891 cmd: vec!["notes-mcp".into(), "--stdio".into()],
892 };
893 let v = serde_json::to_value(&run).unwrap();
894 assert_eq!(v["run"]["cmd"][0], "notes-mcp");
895 assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), run);
896
897 let sock = BackendSpec::Socket {
898 path: "/run/notes.sock".into(),
899 };
900 let v = serde_json::to_value(&sock).unwrap();
901 assert_eq!(v["socket"]["path"], "/run/notes.sock");
902 assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), sock);
903 }
904
905 #[test]
906 fn register_service_wire_shape() {
907 let r = Request::RegisterService(RegisterServiceParams {
908 name: "notes".into(),
909 backend: BackendSpec::Run {
910 cmd: vec!["notes-mcp".into()],
911 },
912 allow: vec!["alice".into()],
913 ephemeral: false,
914 });
915 let v = serde_json::to_value(&r).unwrap();
916 assert_eq!(
917 v,
918 serde_json::json!({
919 "method": "register_service",
920 "params": {
921 "name": "notes",
922 "backend": {"run": {"cmd": ["notes-mcp"]}},
923 "allow": ["alice"],
924 }
925 })
926 );
927 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
928 }
929
930 #[test]
931 fn invite_request_and_result_roundtrip() {
932 // Request::Invite → `{ "method": "invite", "params": { "services": [...] } }`.
933 let r = Request::Invite(InviteParams {
934 services: vec!["notes".into(), "kb".into()],
935 app_label: None,
936 });
937 let v = serde_json::to_value(&r).unwrap();
938 assert_eq!(v["method"], "invite");
939 assert_eq!(v["params"]["services"][0], "notes");
940 assert_eq!(v["params"]["services"][1], "kb");
941 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
942 // method_of resolves the tag generically (no per-variant arm).
943 assert_eq!(
944 method_of(&serde_json::json!({"method": "invite", "params": {"services": []}})),
945 Some("invite")
946 );
947
948 // InviteResult carries the copyable line + expiry (surface #2 pairing artifact).
949 let res = InviteResult {
950 invite_line: "mcpmesh-invite:ABCDEF".into(),
951 expires_at_epoch: 1_800_000_000,
952 };
953 let v = serde_json::to_value(&res).unwrap();
954 assert_eq!(v["invite_line"], "mcpmesh-invite:ABCDEF");
955 assert_eq!(v["expires_at_epoch"], 1_800_000_000u64);
956 assert_eq!(serde_json::from_value::<InviteResult>(v).unwrap(), res);
957 }
958
959 #[test]
960 fn pair_request_and_result_roundtrip() {
961 // Request::Pair → `{ "method": "pair", "params": { "invite_line": "..." } }`.
962 let r = Request::Pair(PairParams {
963 invite_line: "mcpmesh-invite:ABCDEF".into(),
964 });
965 let v = serde_json::to_value(&r).unwrap();
966 assert_eq!(v["method"], "pair");
967 assert_eq!(v["params"]["invite_line"], "mcpmesh-invite:ABCDEF");
968 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
969 // method_of resolves the tag generically (no per-variant arm).
970 assert_eq!(
971 method_of(&serde_json::json!({"method": "pair", "params": {"invite_line": "x"}})),
972 Some("pair")
973 );
974
975 // PairResult carries the inviter's suggested nickname + the display-only SAS words +
976 // the granted services (the porcelain renders each as `<peer>/<service>`).
977 let res = PairResult {
978 peer_nickname: "alice".into(),
979 sas_code: "tango-fig-cabbage".into(),
980 services: vec!["notes".into(), "kb".into()],
981 app_label: None,
982 peer_user_id: None,
983 };
984 let v = serde_json::to_value(&res).unwrap();
985 assert_eq!(v["peer_nickname"], "alice");
986 assert_eq!(v["sas_code"], "tango-fig-cabbage");
987 assert_eq!(v["services"][0], "notes");
988 assert_eq!(v["services"][1], "kb");
989 assert_eq!(serde_json::from_value::<PairResult>(v).unwrap(), res);
990
991 // Additive-only: a PairResult minted by an older daemon (no `services` key) still
992 // deserializes — the `#[serde(default)]` fills it with an empty list.
993 let old_shape = serde_json::json!({
994 "peer_nickname": "alice",
995 "sas_code": "tango-fig-cabbage",
996 });
997 let back: PairResult = serde_json::from_value(old_shape).unwrap();
998 assert_eq!(back.peer_nickname, "alice");
999 assert!(back.services.is_empty());
1000 }
1001
1002 #[test]
1003 fn roster_install_request_and_result_roundtrip() {
1004 // Request::RosterInstall → `{ "method": "roster_install", "params": { "path": ...,
1005 // "org_root_pk": ... } }`. The optional pk is present on the first-install shape.
1006 let r = Request::RosterInstall(RosterInstallParams {
1007 path: "/tmp/roster.json".into(),
1008 org_root_pk: Some("b64u:AAAA".into()),
1009 });
1010 let v = serde_json::to_value(&r).unwrap();
1011 assert_eq!(v["method"], "roster_install");
1012 assert_eq!(v["params"]["path"], "/tmp/roster.json");
1013 assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
1014 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1015 // method_of resolves the tag generically (no per-variant arm).
1016 assert_eq!(
1017 method_of(&serde_json::json!({"method": "roster_install", "params": {"path": "/x"}})),
1018 Some("roster_install")
1019 );
1020
1021 // When the pk is omitted (a subsequent install using the pinned value), it is
1022 // `skip_serializing_if`-dropped from the wire and deserializes back to `None`.
1023 let omit = Request::RosterInstall(RosterInstallParams {
1024 path: "/tmp/roster.json".into(),
1025 org_root_pk: None,
1026 });
1027 let v = serde_json::to_value(&omit).unwrap();
1028 assert!(
1029 v["params"].get("org_root_pk").is_none(),
1030 "an omitted org_root_pk must not appear on the wire: {v}"
1031 );
1032 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), omit);
1033
1034 // RosterInstallResult carries org_id + serial + severed count (roster-status vocabulary).
1035 let res = RosterInstallResult {
1036 org_id: "acme".into(),
1037 serial: 42,
1038 severed: 1,
1039 };
1040 let v = serde_json::to_value(&res).unwrap();
1041 assert_eq!(v["org_id"], "acme");
1042 assert_eq!(v["serial"], 42u64);
1043 assert_eq!(v["severed"], 1u32);
1044 assert_eq!(
1045 serde_json::from_value::<RosterInstallResult>(v).unwrap(),
1046 res
1047 );
1048
1049 // Additive-only: a result minted by an older daemon (no `severed` key) still
1050 // deserializes — the `#[serde(default)]` fills it with 0.
1051 let old_shape = serde_json::json!({ "org_id": "acme", "serial": 7 });
1052 let back: RosterInstallResult = serde_json::from_value(old_shape).unwrap();
1053 assert_eq!(back.serial, 7);
1054 assert_eq!(back.severed, 0);
1055 }
1056
1057 #[test]
1058 fn org_join_request_and_result_roundtrip() {
1059 // Request::OrgJoin → `{ "method": "org_join", "params": { org_id, org_root_pk, user_id,
1060 // user_key } }`. `user_key` is a LOCAL path string (the key never crosses the API).
1061 let r = Request::OrgJoin(OrgJoinParams {
1062 org_id: "acme".into(),
1063 org_root_pk: "b64u:AAAA".into(),
1064 user_id: "alice".into(),
1065 user_key: "/home/alice/.config/mcpmesh/user.key".into(),
1066 });
1067 let v = serde_json::to_value(&r).unwrap();
1068 assert_eq!(v["method"], "org_join");
1069 assert_eq!(v["params"]["org_id"], "acme");
1070 assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
1071 assert_eq!(v["params"]["user_id"], "alice");
1072 assert_eq!(
1073 v["params"]["user_key"],
1074 "/home/alice/.config/mcpmesh/user.key"
1075 );
1076 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1077 // method_of resolves the tag generically (no per-variant arm).
1078 assert_eq!(
1079 method_of(&serde_json::json!({"method": "org_join", "params": {"org_id": "x"}})),
1080 Some("org_join")
1081 );
1082
1083 // OrgJoinResult echoes the pinned org id (surface-clean; the fingerprint is porcelain-side).
1084 let res = OrgJoinResult {
1085 org_id: "acme".into(),
1086 };
1087 let v = serde_json::to_value(&res).unwrap();
1088 assert_eq!(v["org_id"], "acme");
1089 assert_eq!(serde_json::from_value::<OrgJoinResult>(v).unwrap(), res);
1090 }
1091
1092 #[test]
1093 fn set_roster_url_request_roundtrip() {
1094 // Request::SetRosterUrl → `{ "method": "set_roster_url", "params": { "url": "..." } }`.
1095 let r = Request::SetRosterUrl(SetRosterUrlParams {
1096 url: "https://intranet.acme.com/roster.json".into(),
1097 });
1098 let v = serde_json::to_value(&r).unwrap();
1099 assert_eq!(v["method"], "set_roster_url");
1100 assert_eq!(v["params"]["url"], "https://intranet.acme.com/roster.json");
1101 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1102 assert_eq!(
1103 method_of(&serde_json::json!({"method": "set_roster_url", "params": {"url": "x"}})),
1104 Some("set_roster_url")
1105 );
1106 }
1107
1108 #[test]
1109 fn peer_remove_request_roundtrip() {
1110 // Request::PeerRemove → `{ "method": "peer_remove", "params": { "nickname": "..." } }`.
1111 let r = Request::PeerRemove(PeerRemoveParams {
1112 nickname: "bob".into(),
1113 });
1114 let v = serde_json::to_value(&r).unwrap();
1115 assert_eq!(v["method"], "peer_remove");
1116 assert_eq!(v["params"]["nickname"], "bob");
1117 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1118 // method_of resolves the tag generically (no per-variant arm).
1119 assert_eq!(
1120 method_of(&serde_json::json!({"method": "peer_remove", "params": {"nickname": "bob"}})),
1121 Some("peer_remove")
1122 );
1123 }
1124
1125 /// The reserved/internal `peer_add` rides the SAME typed vocabulary as every other method —
1126 /// `{ "method": "peer_add", "params": { nickname, endpoint_id, allow } }` — with `allow`
1127 /// defaulting to empty when absent.
1128 #[test]
1129 fn peer_add_request_roundtrip() {
1130 let r = Request::PeerAdd(PeerAddParams {
1131 nickname: "bob".into(),
1132 endpoint_id: "96246d3f".into(),
1133 allow: vec!["notes".into()],
1134 });
1135 let v = serde_json::to_value(&r).unwrap();
1136 assert_eq!(v["method"], "peer_add");
1137 assert_eq!(v["params"]["nickname"], "bob");
1138 assert_eq!(v["params"]["endpoint_id"], "96246d3f");
1139 assert_eq!(v["params"]["allow"][0], "notes");
1140 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1141 // An absent allow list deserializes to empty (the server-side tolerance).
1142 let p: PeerAddParams =
1143 serde_json::from_value(serde_json::json!({"nickname": "bob", "endpoint_id": "x"}))
1144 .unwrap();
1145 assert!(p.allow.is_empty());
1146 }
1147
1148 #[test]
1149 fn peer_rename_request_roundtrip() {
1150 // By user_id (renames all of a person's devices in one op).
1151 let r = Request::PeerRename(PeerRenameParams {
1152 user_id: Some("b64u:BOB".into()),
1153 nickname: None,
1154 to: "Bobby".into(),
1155 });
1156 let v = serde_json::to_value(&r).unwrap();
1157 assert_eq!(v["method"], "peer_rename");
1158 assert_eq!(v["params"]["user_id"], "b64u:BOB");
1159 assert_eq!(v["params"]["to"], "Bobby");
1160 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1161 // A provisional contact is renamed by nickname; omitted user_id defaults to None.
1162 assert_eq!(
1163 method_of(
1164 &serde_json::json!({"method": "peer_rename", "params": {"nickname": "carol", "to": "Carol"}})
1165 ),
1166 Some("peer_rename")
1167 );
1168 }
1169
1170 #[test]
1171 fn status_result_roundtrips() {
1172 // Pure-pairing daemon: `roster` is None — absent from the wire (skip_serializing_if) and an
1173 // older payload with no `roster` key still deserializes to None (serde default).
1174 let s = StatusResult {
1175 stack_version: "0.1.0".into(),
1176 services: vec![ServiceInfo {
1177 name: "notes".into(),
1178 allow: vec!["alice".into()],
1179 backend: BackendKind::Run,
1180 ephemeral: false,
1181 }],
1182 peers: vec![PeerInfo {
1183 name: "alice".into(),
1184 services: vec!["notes".into()],
1185 // A paired peer that proved a self-sovereign user_id at pairing (surface-clean id).
1186 user_id: Some("b64u:alicepk".into()),
1187 }],
1188 roster: None,
1189 presence: vec![],
1190 self_user_id: Some("b64u:selfpk".into()),
1191 recent_pairings: vec![],
1192 reachability: vec![],
1193 };
1194 let v = serde_json::to_value(&s).unwrap();
1195 assert_eq!(v["services"][0]["backend"], "run");
1196 // The additive identity fields ride the wire when present.
1197 assert_eq!(v["peers"][0]["user_id"], "b64u:alicepk");
1198 assert_eq!(v["self_user_id"], "b64u:selfpk");
1199 assert!(
1200 v.get("roster").is_none(),
1201 "an absent roster must not appear on the wire: {v}"
1202 );
1203 assert!(
1204 v.get("presence").is_none(),
1205 "an empty presence must not appear on the wire: {v}"
1206 );
1207 assert!(
1208 v.get("recent_pairings").is_none(),
1209 "an empty recent_pairings must not appear on the wire: {v}"
1210 );
1211 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1212
1213 // A payload minted by an older daemon (no `roster`/`presence`/identity keys) still
1214 // deserializes — the identity fields default to None / a nickname-only peer.
1215 let old_shape = serde_json::json!({
1216 "stack_version": "0.1.0",
1217 "services": [],
1218 "peers": [{ "name": "bob", "services": [] }],
1219 });
1220 let back: StatusResult = serde_json::from_value(old_shape).unwrap();
1221 assert!(back.roster.is_none());
1222 assert!(back.presence.is_empty());
1223 assert!(back.self_user_id.is_none());
1224 assert!(back.peers[0].user_id.is_none());
1225 assert!(back.recent_pairings.is_empty());
1226
1227 // Roster daemon: a Some(RosterStatus) + an advisory presence list round-trip. `presence`
1228 // carries FLAT vocabulary only (user_id/device_label/role/online) — no EndpointId/key.
1229 let s = StatusResult {
1230 stack_version: "0.1.0".into(),
1231 services: vec![],
1232 peers: vec![],
1233 roster: Some(RosterStatus {
1234 org_id: "acme".into(),
1235 serial: 42,
1236 state: "approved".into(),
1237 org_root_fingerprint: "tango-fig-cabbage-anchor".into(),
1238 }),
1239 presence: vec![
1240 PresencePeer {
1241 user_id: "alice".into(),
1242 device_label: "laptop".into(),
1243 role: "primary".into(),
1244 online: true,
1245 },
1246 PresencePeer {
1247 user_id: "alice".into(),
1248 device_label: "desktop".into(),
1249 role: "mirror".into(),
1250 online: false,
1251 },
1252 ],
1253 self_user_id: None,
1254 recent_pairings: vec![],
1255 reachability: vec![],
1256 };
1257 let v = serde_json::to_value(&s).unwrap();
1258 assert_eq!(v["roster"]["org_id"], "acme");
1259 assert_eq!(v["roster"]["serial"], 42u64);
1260 assert_eq!(v["roster"]["state"], "approved");
1261 assert_eq!(
1262 v["roster"]["org_root_fingerprint"],
1263 "tango-fig-cabbage-anchor"
1264 );
1265 assert_eq!(v["presence"][0]["user_id"], "alice");
1266 assert_eq!(v["presence"][0]["device_label"], "laptop");
1267 assert_eq!(v["presence"][0]["role"], "primary");
1268 assert_eq!(v["presence"][0]["online"], true);
1269 assert_eq!(v["presence"][1]["online"], false);
1270 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1271 }
1272
1273 /// The `recent_pairings` status field is ADDITIVE: a populated list round-trips with
1274 /// the flat `{peer_nickname, sas_code, paired_at_epoch}` shape (nickname + SAS words + epoch —
1275 /// never an EndpointId), an empty list is dropped from the wire, and a payload minted by an
1276 /// older daemon (no key at all) still deserializes to empty.
1277 #[test]
1278 fn recent_pairings_are_additive_on_status() {
1279 let s = StatusResult {
1280 stack_version: "0.1.0".into(),
1281 services: vec![],
1282 peers: vec![],
1283 roster: None,
1284 presence: vec![],
1285 self_user_id: None,
1286 recent_pairings: vec![RecentPairing {
1287 peer_nickname: "bob".into(),
1288 sas_code: "tango-fig-cabbage".into(),
1289 paired_at_epoch: 1_800_000_000,
1290 }],
1291 reachability: vec![],
1292 };
1293 let v = serde_json::to_value(&s).unwrap();
1294 assert_eq!(v["recent_pairings"][0]["peer_nickname"], "bob");
1295 assert_eq!(v["recent_pairings"][0]["sas_code"], "tango-fig-cabbage");
1296 assert_eq!(v["recent_pairings"][0]["paired_at_epoch"], 1_800_000_000u64);
1297 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1298
1299 // A payload minted by an OLDER daemon (no `recent_pairings` key) still deserializes —
1300 // the `#[serde(default)]` fills it with an empty list.
1301 let old_shape = serde_json::json!({
1302 "stack_version": "0.1.0",
1303 "services": [],
1304 "peers": [],
1305 });
1306 let back: StatusResult = serde_json::from_value(old_shape).unwrap();
1307 assert!(back.recent_pairings.is_empty());
1308 }
1309
1310 #[test]
1311 fn blob_requests_and_results_roundtrip() {
1312 // BlobPublish → { method, params: { scope, path } }.
1313 let r = Request::BlobPublish(BlobPublishParams {
1314 scope: "docs".into(),
1315 path: "/tmp/a.bin".into(),
1316 });
1317 let v = serde_json::to_value(&r).unwrap();
1318 assert_eq!(v["method"], "blob_publish");
1319 assert_eq!(v["params"]["scope"], "docs");
1320 assert_eq!(v["params"]["path"], "/tmp/a.bin");
1321 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1322
1323 // BlobGrant → { method, params: { scope, principal } }.
1324 let r = Request::BlobGrant(BlobGrantParams {
1325 scope: "docs".into(),
1326 principal: "alice".into(),
1327 });
1328 let v = serde_json::to_value(&r).unwrap();
1329 assert_eq!(v["method"], "blob_grant");
1330 assert_eq!(v["params"]["principal"], "alice");
1331 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1332
1333 // BlobList is parameterless (method_of resolves it).
1334 assert_eq!(
1335 method_of(&serde_json::json!({"method": "blob_list"})),
1336 Some("blob_list")
1337 );
1338
1339 // BlobFetch → { method, params: { ticket, dest_path } }.
1340 let r = Request::BlobFetch(BlobFetchParams {
1341 ticket: "blobAAA".into(),
1342 dest_path: "/tmp/out.bin".into(),
1343 });
1344 let v = serde_json::to_value(&r).unwrap();
1345 assert_eq!(v["method"], "blob_fetch");
1346 assert_eq!(v["params"]["ticket"], "blobAAA");
1347 assert_eq!(v["params"]["dest_path"], "/tmp/out.bin");
1348 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1349
1350 // BlobPublishResult carries the ticket + hash (blob-reference vocabulary).
1351 let res = BlobPublishResult {
1352 ticket: "blobAAA".into(),
1353 hash: "ab".repeat(32),
1354 };
1355 let v = serde_json::to_value(&res).unwrap();
1356 assert_eq!(v["ticket"], "blobAAA");
1357 assert_eq!(serde_json::from_value::<BlobPublishResult>(v).unwrap(), res);
1358
1359 // BlobScopeList carries flat (name, hashes, grants) — no EndpointId/key leakage.
1360 let res = BlobScopeList {
1361 scopes: vec![ScopeInfo {
1362 name: "docs".into(),
1363 hashes: vec!["ab".repeat(32)],
1364 grants: vec!["alice".into()],
1365 }],
1366 };
1367 let v = serde_json::to_value(&res).unwrap();
1368 assert_eq!(v["scopes"][0]["name"], "docs");
1369 assert_eq!(v["scopes"][0]["grants"][0], "alice");
1370 assert_eq!(serde_json::from_value::<BlobScopeList>(v).unwrap(), res);
1371
1372 // BlobFetchResult carries the verified hash + byte length.
1373 let res = BlobFetchResult {
1374 hash: "ab".repeat(32),
1375 bytes_len: 4194304,
1376 };
1377 let v = serde_json::to_value(&res).unwrap();
1378 assert_eq!(v["bytes_len"], 4194304u64);
1379 assert_eq!(serde_json::from_value::<BlobFetchResult>(v).unwrap(), res);
1380 }
1381
1382 /// The three `subscribe` frame shapes round-trip with the documented `type`-tagged wire form
1383 /// (docs/local-protocol.md "Live event stream"): `snapshot` carries the flat session/reachability
1384 /// lists, `event` delegates through the `Box` so the record's fields sit VERBATIM under
1385 /// `record` (one schema with the JSONL log), and `lagged` carries the dropped count.
1386 #[test]
1387 fn stream_frames_roundtrip_with_the_documented_tags() {
1388 let snap = StreamFrame::Snapshot {
1389 active_sessions: vec![ActiveSession {
1390 peer: "bob".into(),
1391 service: "notes".into(),
1392 opened_at: 1_751_760_000,
1393 }],
1394 reachability: vec![PeerReachability {
1395 name: "bob".into(),
1396 reachable: true,
1397 rtt_ms: Some(42),
1398 age_secs: Some(3),
1399 }],
1400 };
1401 let v = serde_json::to_value(&snap).unwrap();
1402 assert_eq!(v["type"], "snapshot");
1403 assert_eq!(v["active_sessions"][0]["peer"], "bob");
1404 assert_eq!(v["active_sessions"][0]["opened_at"], 1_751_760_000i64);
1405 assert_eq!(v["reachability"][0]["name"], "bob");
1406 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), snap);
1407
1408 let event = StreamFrame::Event {
1409 record: Box::new(AuditRecord::session_open(
1410 "2026-07-03T14:02:11.480Z".into(),
1411 Some("bob".into()),
1412 "notes".into(),
1413 )),
1414 };
1415 let v = serde_json::to_value(&event).unwrap();
1416 assert_eq!(v["type"], "event");
1417 // The record's fields ride verbatim under `record` — no Box indirection on the wire.
1418 assert_eq!(v["record"]["kind"], "session_open");
1419 assert_eq!(v["record"]["peer"], "bob");
1420 assert_eq!(v["record"]["service"], "notes");
1421 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), event);
1422
1423 let lagged = StreamFrame::Lagged { dropped: 12 };
1424 let v = serde_json::to_value(&lagged).unwrap();
1425 assert_eq!(v, serde_json::json!({ "type": "lagged", "dropped": 12 }));
1426 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), lagged);
1427 }
1428
1429 /// A frame minted by a NEWER daemon (an unknown `type`) fails to deserialize rather than
1430 /// mis-parsing — the typed stream surface is closed; a forward-compatible consumer reads the
1431 /// raw `Value` stream instead (`ControlClient::open_stream`).
1432 #[test]
1433 fn unknown_stream_frame_type_is_rejected() {
1434 let future = serde_json::json!({ "type": "future_kind", "x": 1 });
1435 assert!(serde_json::from_value::<StreamFrame>(future).is_err());
1436 }
1437
1438 #[test]
1439 fn audit_summary_request_and_result_roundtrip() {
1440 // Request::AuditSummary is parameterless → `{ "method": "audit_summary" }`. Like Status, it
1441 // tolerates omitted/null params; the server dispatches on the method string (method_of).
1442 let r = Request::AuditSummary;
1443 assert_eq!(serde_json::to_value(&r).unwrap()["method"], "audit_summary");
1444 assert_eq!(
1445 method_of(&serde_json::json!({"method": "audit_summary"})),
1446 Some("audit_summary")
1447 );
1448
1449 // AuditSummaryResult carries LOCAL per-peer / per-service session counts (nicknames + service
1450 // names only — never endpoints/transport terms) + a total. Tuples mirror kb's
1451 // InsightResponse.per_peer_contribution: `["bob", 2]` on the wire.
1452 let res = AuditSummaryResult {
1453 per_peer: vec![("alice".into(), 1), ("bob".into(), 2)],
1454 per_service: vec![("kb".into(), 1), ("notes".into(), 3)],
1455 total_sessions: 4,
1456 };
1457 let v = serde_json::to_value(&res).unwrap();
1458 assert_eq!(v["per_peer"][1][0], "bob");
1459 assert_eq!(v["per_peer"][1][1], 2u64);
1460 assert_eq!(v["per_service"][1][0], "notes");
1461 assert_eq!(v["total_sessions"], 4u64);
1462 assert_eq!(
1463 serde_json::from_value::<AuditSummaryResult>(v).unwrap(),
1464 res
1465 );
1466
1467 // Additive-only: a result minted by an older daemon (no `total_sessions` key) still
1468 // deserializes — the `#[serde(default)]` fills it with 0.
1469 let old_shape = serde_json::json!({ "per_peer": [], "per_service": [] });
1470 let back: AuditSummaryResult = serde_json::from_value(old_shape).unwrap();
1471 assert_eq!(back.total_sessions, 0);
1472 assert!(back.per_peer.is_empty());
1473 }
1474}