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 std::collections::BTreeMap;
15
16use serde::{Deserialize, Serialize};
17
18/// The first exchange on any `*-local/N` socket (the family's hello convention).
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20pub struct Hello {
21 pub api: String, // "mcpmesh-local/1"
22 pub api_version: String, // "MAJOR.MINOR" of the protocol surface (see API_MINOR)
23 /// The protocol-compatibility MINOR as an integer, for a trivial machine comparison
24 /// (`api_minor >= N`) without string parsing. Distinct from `stack_version` (the crate
25 /// release train). Additive: an older daemon omits it and it defaults to 0.
26 #[serde(default)]
27 pub api_minor: u32,
28 pub stack_version: String,
29}
30
31/// The kind of backend answering a service — the two valid values, enforced at the
32/// type level and kept in lockstep with `BackendSpec`'s variants. Status reports the
33/// kind only, never the command/path (no transport vocabulary).
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum BackendKind {
37 Run,
38 Socket,
39}
40
41/// A registered service as reported by `status` (no transport vocabulary).
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43pub struct ServiceInfo {
44 pub name: String,
45 pub allow: Vec<String>, // STABLE principals (b64u:/eid:) or roster names (#38) — never nicknames
46 /// The HUMAN rendering of `allow`, index-aligned: each principal resolved to its peer's
47 /// display nickname by the daemon (which owns the store); an unresolvable stable
48 /// principal renders as a neutral placeholder — porcelain must show THESE, never raw
49 /// ids (surface discipline). Additive: default + skip-if-empty.
50 #[serde(default, skip_serializing_if = "Vec::is_empty")]
51 pub allow_display: Vec<String>,
52 pub backend: BackendKind, // "run" | "socket" (kind only, never the command/path)
53 /// True if this registration is ephemeral (#36): in-memory only, tied to the registering
54 /// control connection's lifetime, absent from config, gone on restart. Additive — an older
55 /// daemon omits it and it reads as `false` (the persistent default).
56 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
57 pub ephemeral: bool,
58}
59
60/// A known peer as reported by `status` (nickname only — never the EndpointId).
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62pub struct PeerInfo {
63 pub name: String,
64 pub services: Vec<String>,
65 /// The peer's PROVEN self-sovereign `user_id` (`b64u:<user_pk>`) if it presented a verified
66 /// device->user binding at pairing (roster peers carry it too), else `None` (nickname-only). This
67 /// is a surface-clean identity (an opaque user id, NOT an EndpointId). Additive:
68 /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so older payloads round-trip.
69 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub user_id: Option<String>,
71 /// The peer's stable DEVICE principal `eid:<hex>` (#41) — the SAME rendering the socket
72 /// backend injects into `_meta["mcpmesh/peer"]` and that appears in `[services.*].allow`.
73 /// Always present for a real peer (`Option` only for additive round-trip). Distinct from
74 /// `user_id` (the person-level `b64u:`, present only when the peer proved a binding): a
75 /// nickname is not unique, so an embedder keys caller-scoped decisions (dial the caller
76 /// back, "the requester's own data") on THIS, the authenticated endpoint. Machine-surface
77 /// authz vocabulary (like the allow lists) — human porcelain still shows the nickname.
78 /// Additive: `#[serde(default, skip_serializing_if = "Option::is_none")]`.
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub principal: Option<String>,
81}
82
83/// Advisory reachability of a paired peer (pairing-mode liveness). Surface-clean:
84/// a nickname + a bool + latency/age NUMBERS — never an endpoint-id, key, or transport path.
85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86pub struct PeerReachability {
87 pub name: String, // the peer's nickname
88 pub reachable: bool, // result of the last probe (false if never probed)
89 #[serde(default, skip_serializing_if = "Option::is_none")]
90 pub rtt_ms: Option<u64>, // last measured round-trip, if reachable
91 #[serde(default, skip_serializing_if = "Option::is_none")]
92 pub age_secs: Option<u64>, // None = never probed (consumer shows "checking…")
93 /// The peer's OPTIONAL app metadata (#40) — the same opaque ≤256B blob #39 exposes via
94 /// presence, here carried on the pairing-mode `mcpmesh/ping/1` probe pong so PAIRED peers
95 /// (which have no presence gossip) see it too. Empty when the peer set none. Advisory
96 /// display data; never an authz input. Near-real-time when `status` is read (the probe
97 /// cache has a ~20s TTL), not a steady push. Additive: default + skip-if-empty.
98 #[serde(default, skip_serializing_if = "String::is_empty")]
99 pub meta: String,
100 /// The peer's stable DEVICE principal `eid:<hex>` (#42) — the SAME rendering as
101 /// [`PeerInfo::principal`], so an embedder joins probe result + `meta` (app version) to a
102 /// peer by the AUTHENTICATED endpoint rather than the non-unique nickname. Always present
103 /// for a real row (`Option` only for additive round-trip). Machine-surface authz
104 /// vocabulary — the human `status` reachability line is unchanged. Additive:
105 /// `#[serde(default, skip_serializing_if = "Option::is_none")]`.
106 #[serde(default, skip_serializing_if = "Option::is_none")]
107 pub principal: Option<String>,
108}
109
110/// Roster-mode status. Surface-clean roster VOCABULARY only: org_id, serial, a plain
111/// state word, and the pinned org-root FINGERPRINT in short words — never raw keys/EndpointIds/serials-
112/// as-transport-vocab. Absent in a pure-pairing daemon.
113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
114pub struct RosterStatus {
115 pub org_id: String,
116 pub serial: u64,
117 pub state: String, // "pending" | "approved" | "degraded" | "stopped"
118 pub org_root_fingerprint: String, // short-word form
119}
120
121/// One reachable roster peer device as reported by `status` (the advisory presence read).
122/// ADVISORY — this is a display convenience, never an authorization surface. Surface-clean:
123/// FLAT vocabulary ONLY — a `user_id`, a human `device_label`, its `role` word, and an `online`
124/// boolean. It carries NO EndpointId / pubkey / hash / ALPN or any transport vocabulary.
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct PresencePeer {
127 pub user_id: String,
128 pub device_label: String,
129 pub role: String, // "primary" | "mirror" (roster vocabulary)
130 /// Whether the device has a live presence heartbeat (advisory — absence never blocks a dial).
131 pub online: bool,
132 /// The device's OPTIONAL embedder-set app metadata (#39) — an opaque ≤256B blob carried
133 /// (signed) on its presence heartbeat, empty when the device set none. Advisory display
134 /// data; never an authz input. Additive: default + skip-if-empty.
135 #[serde(default, skip_serializing_if = "String::is_empty")]
136 pub meta: String,
137}
138
139/// One recently completed INVITER-side pairing, surfaced by `status` so the inviter's human can
140/// read the short authentication code (SAS) and compare it with the redeemer's out-of-band —
141/// the pairing ceremony is "both humans compare the code": the redeemer sees it in its
142/// [`PairResult`]; this is the inviter's porcelain surface for the same words. DISPLAY-ONLY
143/// ceremony state: held in-memory by the daemon (a small ring), lost on restart, NEVER an
144/// authorization input or trust data. Surface-clean: a nickname + the SAS wordlist words +
145/// an epoch — never an EndpointId.
146#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
147pub struct RecentPairing {
148 /// The peer's nickname as stored by the inviter (its local name for the redeemer).
149 pub peer_nickname: String,
150 /// The display-only SAS words (e.g. `"tango-fig-cabbage"`) — the same code the redeemer's
151 /// `PairResult.sas_code` carried. Never checked programmatically.
152 pub sas_code: String,
153 /// When the pairing completed (epoch seconds) — the porcelain renders a friendly age.
154 pub paired_at_epoch: u64,
155}
156
157#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
158pub struct StatusResult {
159 pub stack_version: String,
160 pub services: Vec<ServiceInfo>,
161 pub peers: Vec<PeerInfo>,
162 /// Roster-mode status, absent in a pure-pairing daemon. Additive:
163 /// `#[serde(default, skip_serializing_if = ...)]` so a daemon/client without it round-trips.
164 #[serde(default, skip_serializing_if = "Option::is_none")]
165 pub roster: Option<RosterStatus>,
166 /// The reachable roster peer devices (the advisory presence read), each with an `online`
167 /// flag. Empty in a pure-pairing daemon / when no roster is installed. Additive:
168 /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
169 #[serde(default, skip_serializing_if = "Vec::is_empty")]
170 pub presence: Vec<PresencePeer>,
171 /// THIS daemon's own self-sovereign `user_id` (`b64u:<user_pk>`), if it has a user key (auto-
172 /// minted at boot; shared by pairing AND roster mode). Lets the operator see + share their stable
173 /// identity that multiple devices resolve to. `None` only when no user key exists. Additive:
174 /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so an older payload round-trips.
175 #[serde(default, skip_serializing_if = "Option::is_none")]
176 pub self_user_id: Option<String>,
177 /// Recent INVITER-side pairing completions, newest first (display-only pairing-ceremony aids —
178 /// see [`RecentPairing`]; in-memory on the daemon, cleared by a restart). Empty on a daemon
179 /// that has accepted no pairing since it started. Additive:
180 /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
181 #[serde(default, skip_serializing_if = "Vec::is_empty")]
182 pub recent_pairings: Vec<RecentPairing>,
183 /// Advisory reachability of paired peers, from the on-demand probe cache. Empty until the
184 /// first probe completes. Additive: default + skip-if-empty.
185 #[serde(default, skip_serializing_if = "Vec::is_empty")]
186 pub reachability: Vec<PeerReachability>,
187 /// This node's EFFECTIVE self-nickname — what a freshly minted invite would present
188 /// (config `[identity].nickname`, else the hostname, else a fingerprint; live-updated by
189 /// `set_nickname`, #37). Empty only in mesh-less control-only mode. Additive: default +
190 /// skip-if-empty so an older payload round-trips.
191 #[serde(default, skip_serializing_if = "String::is_empty")]
192 pub self_nickname: String,
193}
194
195/// Params of [`Request::RegisterService`]: the `[services.*]` entry to write/update.
196#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
197#[serde(deny_unknown_fields)]
198pub struct RegisterServiceParams {
199 pub name: String,
200 pub backend: BackendSpec,
201 pub allow: Vec<String>,
202 /// When true (#36), the registration is EPHEMERAL: kept in daemon memory only, never written
203 /// to the on-disk config, and automatically unregistered when the control connection that
204 /// registered it closes (and gone on daemon restart). For an embedder that serves a
205 /// `socket` backend from a fresh path each run, this removes the need to derive a stable
206 /// socket path solely to keep a persisted registration valid, and the stale-registration
207 /// accumulation that comes with no unregister. Default false = the persistent behavior.
208 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
209 pub ephemeral: bool,
210}
211
212/// Params of [`Request::Invite`]: the services the minted invite grants. Rejects unknown
213/// fields (so `{service: "kb"}` — a singular typo — is a loud error, not a silently
214/// grants-nothing invite), and the daemon additionally rejects an empty/absent `services`
215/// list (an invite that grants nothing is useless — #34).
216#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
217#[serde(deny_unknown_fields)]
218pub struct InviteParams {
219 #[serde(default)]
220 pub services: Vec<String>,
221 /// An OPAQUE, caller-chosen label carried through to the redeemer in the `pair` result (#31).
222 /// mcpmesh never interprets it (not a nickname, never resolved or authorized) — a per-pairing
223 /// metadata slot for the embedder (e.g. its own URN). Capped at the daemon; omit for none.
224 #[serde(default, skip_serializing_if = "Option::is_none")]
225 pub app_label: Option<String>,
226}
227
228/// Params of [`Request::Pair`]: the copyable `mcpmesh-invite:` line. Defaultable — an
229/// absent field reads as an empty line, which simply fails to decode (a clean pair error).
230#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
231#[serde(deny_unknown_fields)]
232pub struct PairParams {
233 #[serde(default)]
234 pub invite_line: String,
235}
236
237/// Params of [`Request::PeerRemove`]: the nickname to unpair.
238#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
239#[serde(deny_unknown_fields)]
240pub struct PeerRemoveParams {
241 pub nickname: String,
242}
243
244/// Params of [`Request::PeerRename`]: the contact to rename — every device sharing `user_id`
245/// when given, else the single provisional `nickname` entry — and the new nickname `to`.
246#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
247#[serde(deny_unknown_fields)]
248pub struct PeerRenameParams {
249 #[serde(default)]
250 pub user_id: Option<String>,
251 #[serde(default)]
252 pub nickname: Option<String>,
253 pub to: String,
254}
255
256/// Params of [`Request::PeerAdd`] (reserved/internal — see the variant): a raw `endpoint_id`
257/// (iroh base32) plus the nickname and service allow list to install it under.
258#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
259#[serde(deny_unknown_fields)]
260pub struct PeerAddParams {
261 pub nickname: String,
262 pub endpoint_id: String,
263 #[serde(default)]
264 pub allow: Vec<String>,
265}
266
267/// Params of [`Request::OpenSession`]: the `peer/service` target to dial. Both fields are
268/// defaultable — an empty target simply fails the dial (a clean `-32055` error).
269#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
270#[serde(deny_unknown_fields)]
271pub struct OpenSessionParams {
272 #[serde(default)]
273 pub peer: String,
274 #[serde(default)]
275 pub service: String,
276}
277
278/// Params of [`Request::RosterInstall`]: the LOCAL roster file `path`, plus the org-root pin
279/// on FIRST install (`b64u:`; omit once pinned — config carries it).
280#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
281#[serde(deny_unknown_fields)]
282pub struct RosterInstallParams {
283 pub path: String,
284 #[serde(default, skip_serializing_if = "Option::is_none")]
285 pub org_root_pk: Option<String>,
286}
287
288/// Params of [`Request::OrgJoin`]: the `[identity]` pin. `user_key` is a LOCAL path — the key
289/// never crosses the API.
290#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
291#[serde(deny_unknown_fields)]
292pub struct OrgJoinParams {
293 pub org_id: String,
294 pub org_root_pk: String,
295 pub user_id: String,
296 pub user_key: String,
297}
298
299/// Params of [`Request::SetAppMetadata`]: this node's opaque app-metadata blob (#39). The
300/// daemon NEVER interprets it — the embedder structures its own bytes (a version string,
301/// small JSON, …). Capped at 256 bytes; `""` clears it. Roster-mode only (it rides the
302/// signed presence heartbeat); a pure-pairing daemon accepts + stores it but never gossips it.
303#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
304#[serde(deny_unknown_fields)]
305pub struct SetAppMetadataParams {
306 pub metadata: String,
307}
308
309/// Params of [`Request::PeerServices`] (#52): the peer to query — a nickname, an `eid:` device
310/// principal, or a `b64u:` user_id.
311#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
312#[serde(deny_unknown_fields)]
313pub struct PeerServicesParams {
314 pub peer: String,
315}
316
317/// Result of [`Request::PeerServices`] (#52): the services the queried peer CURRENTLY grants the
318/// caller — computed authoritatively on the peer (which owns the truth), always current, only
319/// the caller's own admitted services (never the peer's full registry).
320#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
321pub struct PeerServicesResult {
322 pub services: Vec<String>,
323}
324
325/// Params of [`Request::UnregisterService`] (#50): the persistent (or ephemeral) service name
326/// to remove — the deregistration mirror of `register_service`.
327#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
328#[serde(deny_unknown_fields)]
329pub struct UnregisterServiceParams {
330 pub name: String,
331}
332
333/// Params of [`Request::ServiceAllowGrant`] / [`Request::ServiceAllowRevoke`] (#44): toggle a
334/// single stable `principal` (`b64u:`/`eid:`) on a single `service`'s allow list, WITHOUT
335/// unpairing. The per-peer "sharing" switch primitive the embedder drives.
336#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
337#[serde(deny_unknown_fields)]
338pub struct ServiceAllowParams {
339 pub service: String,
340 pub principal: String,
341}
342
343/// Params of [`Request::SetNickname`]: this node's new self-nickname (#37). Display-only
344/// semantics: it names this node in FUTURE invites/presentations; peers keep the nickname
345/// they stored at pairing time until a re-invite.
346#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
347#[serde(deny_unknown_fields)]
348pub struct SetNicknameParams {
349 pub nickname: String,
350}
351
352/// Params of [`Request::SetRosterUrl`]: the HTTPS roster URL to pin.
353#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
354#[serde(deny_unknown_fields)]
355pub struct SetRosterUrlParams {
356 pub url: String,
357}
358
359/// Params of [`Request::SetRelays`] (#53): the node's desired CUSTOM relay set. Declarative —
360/// "make the custom relay set exactly this" — applied as a live insert/remove diff against the
361/// running endpoint (iroh 1.0.3 `Endpoint::insert_relay`/`remove_relay`) when the node is already
362/// in `relay_mode = "custom"`, then persisted to `[network]`. Each entry must parse as an iroh
363/// `RelayUrl`; an empty list is rejected (custom mode requires ≥1 relay — fully disabling relays
364/// is a `relay_mode = "disabled"` restart, not this verb). Switching a node that is currently
365/// `default`/`disabled` onto custom persists the config but needs a restart to take effect (iroh
366/// cannot live-transition the relay MODE) — signalled by [`SetRelaysResult::restart_required`].
367#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
368#[serde(deny_unknown_fields)]
369pub struct SetRelaysParams {
370 pub relay_urls: Vec<String>,
371}
372
373/// Result of [`Request::SetRelays`] (#53).
374#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
375pub struct SetRelaysResult {
376 /// The persisted `relay_urls` differed from the prior config (a no-op edit → `false`).
377 pub changed: bool,
378 /// `true` iff the node's current `relay_mode` is not `custom`, so the new set was persisted
379 /// but NOT applied live — a node restart is required for it to take effect. `false` on the
380 /// live custom→custom path (already applied to the running endpoint).
381 pub restart_required: bool,
382}
383
384/// Params of [`Request::BlobPublish`]: the scope to publish into and the LOCAL file to add.
385#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
386#[serde(deny_unknown_fields)]
387pub struct BlobPublishParams {
388 pub scope: String,
389 pub path: String,
390}
391
392/// Params of [`Request::BlobGrant`]: the scope and the flat-namespace principal to grant it to.
393#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
394#[serde(deny_unknown_fields)]
395pub struct BlobGrantParams {
396 pub scope: String,
397 pub principal: String,
398}
399
400/// Params of [`Request::BlobFetch`]: the `mcpmesh/blob/1` ticket and the LOCAL export path.
401#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
402#[serde(deny_unknown_fields)]
403pub struct BlobFetchParams {
404 pub ticket: String,
405 pub dest_path: String,
406}
407
408/// Control-API requests. Serialized as `{ "method": "...", "params": {...} }`
409/// (JSON-RPC-shaped; the id/jsonrpc envelope is added by the transport layer).
410///
411/// Each param-carrying variant wraps its named `*Params` struct — the ONE wire truth for that
412/// method's params, shared by clients (which serialize whole `Request`s) and the daemon (which
413/// deserializes `params` into the same struct after its method-string dispatch). Adjacent
414/// tagging serializes a newtype variant's content as the struct's fields, so the wire shape is
415/// identical to inline variant bodies.
416///
417/// **Servers dispatch on the `method` string and deserialize `params` per-method** — tolerating
418/// omitted / null / empty-object params for parameterless methods — rather than deserializing a
419/// whole message into `Request` (adjacent tagging rejects `params:{}` for unit variants).
420/// This keeps the wire tolerant for third-party clients (the versioned, additive-only surface).
421/// Use [`method_of`] to extract the tag, then match + deserialize `params` per-method.
422#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
423#[serde(tag = "method", content = "params", rename_all = "snake_case")]
424pub enum Request {
425 /// Register/update a `[services.*]` entry idempotently.
426 RegisterService(RegisterServiceParams),
427 Status,
428 /// Mint a one-time pairing invite granting `services`. The daemon
429 /// answers an [`InviteResult`] carrying the copyable `mcpmesh-invite:` line. Tag
430 /// `"invite"` (snake_case). `method_of` needs no per-variant arm — it reads the
431 /// `method` string generically; the tag comes from `rename_all`.
432 Invite(InviteParams),
433 /// Redeem a pairing invite. The daemon dials the inviter named by
434 /// `invite_line` on `mcpmesh/pair/1`, proves the secret, writes the mutual
435 /// (dial-back) `PeerEntry`, and answers a [`PairResult`]. Tag `"pair"`
436 /// (snake_case); `method_of` reads the `method` string generically.
437 ///
438 /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
439 Pair(PairParams),
440 /// Remove a paired peer by nickname (`mcpmesh pair --remove`). The daemon drops the
441 /// peer's `PeerEntry` (identity) AND revokes its access by stripping its stable principals from every
442 /// `[services.*].allow` (authorization) — the inverse of the pairing grant. Idempotent: a
443 /// nickname with no entry / no allow membership is a clean no-op. Live in-flight sessions are
444 /// NOT severed here: existing sessions run to completion; the peer only loses the
445 /// ability to establish NEW authorized sessions. Tag `"peer_remove"` (snake_case);
446 /// `method_of` reads the `method` string generically (no per-variant arm).
447 ///
448 /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
449 PeerRemove(PeerRemoveParams),
450 /// Rename a contact's nickname (nickname) authoritatively. Renames the
451 /// PERSON — every `PeerEntry` sharing `user_id` when given (one op for all their devices), else the
452 /// single `nickname` entry (a provisional, no-`user_id` contact) — to `to`, AND rewrites the old
453 /// nickname → `to` in every `[services.*].allow` so grants follow the rename. Refuses (error frame)
454 /// when `to` is empty or already names/grants a DIFFERENT identity — the same collision guard the
455 /// pairing rendezvous uses, so a rename can't inherit another peer's access. Tag `"peer_rename"`;
456 /// host-privileged like the other pair ops.
457 PeerRename(PeerRenameParams),
458 /// RESERVED / INTERNAL (`docs/local-protocol.md` "Reserved / internal methods"): install a
459 /// peer directly from a raw `endpoint_id` — the trust-population stand-in for pairing behind
460 /// `mcpmesh internal peer add`. A deliberate, documented exception to the surface discipline
461 /// (raw endpoint identifiers otherwise never cross this socket); NOT part of the stable
462 /// vocabulary — do not build on it. Tag `"peer_add"`.
463 PeerAdd(PeerAddParams),
464 /// Open a mesh session to `peer/service`; the daemon dials and pipes.
465 /// Distinct from the proxy's job: this returns a session the client streams.
466 /// Named `open_session` rather than `connect` to avoid colliding
467 /// with the `connect` porcelain.
468 OpenSession(OpenSessionParams),
469 /// Install a signed roster from a local file (the manual `internal roster install` path).
470 /// `path` is a LOCAL file the same-uid daemon reads (the daemon runs as the caller's own
471 /// uid, so passing a path rather than the bytes crosses no trust boundary). `org_root_pk`
472 /// pins the org root on FIRST install (`b64u:`); omit it
473 /// once pinned (config carries it). Tag `"roster_install"`.
474 RosterInstall(RosterInstallParams),
475 /// Pin the org root on a JOINER — WITHOUT a roster (the joiner has none yet; its poll loop
476 /// fetches the first one). Records `[identity]` org_id / org_root_pk / user_id / user_key.
477 /// `user_key` is a LOCAL path
478 /// (the key never crosses the API). Tag `"org_join"`.
479 OrgJoin(OrgJoinParams),
480 /// Pin the HTTPS roster URL (`[roster].url`) in config. Written by `org create
481 /// --roster-url` (the operator keeps it current) AND by `join` when the org invite carries one —
482 /// so the joiner's poll loop bootstraps its FIRST roster. The daemon writes it under
483 /// `reload_lock` (single-writer), then the poll loop picks it up on the next daemon start. Tag
484 /// `"set_roster_url"`.
485 SetRosterUrl(SetRosterUrlParams),
486 /// Rename this node LIVE (#37): validate + upsert `[identity].nickname` through the
487 /// daemon's own serialized config-write path (no lost-update window against a
488 /// concurrent grant/registration) and update the in-memory name future invites
489 /// present — no restart. Ack result. Tag `"set_nickname"` (snake_case).
490 SetNickname(SetNicknameParams),
491 /// Set this node's opaque app-metadata blob (#39): validated (≤256B) and folded, signed,
492 /// into each outgoing presence heartbeat, so paired roster peers see it in their `status`
493 /// presence — no per-peer session. Ack result. Tag `"set_app_metadata"`. In-memory (lost
494 /// on restart; the embedder re-sets on startup).
495 SetAppMetadata(SetAppMetadataParams),
496 /// Set this node's CUSTOM relay set LIVE (#53): validate each URL as an iroh `RelayUrl`, diff
497 /// against the running endpoint's current custom relays and apply the delta via iroh 1.0.3
498 /// `Endpoint::insert_relay`/`remove_relay` (no endpoint rebuild, no dropped sessions), then
499 /// persist `[network] relay_mode="custom" relay_urls=[…]` under `reload_lock`. When the node
500 /// is currently `default`/`disabled`, the config is persisted but the live mode transition
501 /// isn't possible — [`SetRelaysResult::restart_required`] is `true`. Answers a
502 /// [`SetRelaysResult`]. Tag `"set_relays"`.
503 SetRelays(SetRelaysParams),
504 /// Grant a single stable principal access to a single service's allow (#44) — the per-peer
505 /// "sharing on" toggle, idempotent + serialized under the config lock. Ack result.
506 /// Remove a service registration (#50) — the deregistration mirror of `register_service`.
507 /// Removes the whole `[services.<name>]` entry (allow included) + any ephemeral one, then
508 /// hot-reloads. Idempotent. Ack result.
509 UnregisterService(UnregisterServiceParams),
510 /// Discover which services a paired peer CURRENTLY grants the caller (#52) — dials the peer
511 /// and returns the service names whose allow admits the caller's principal. Answers
512 /// [`PeerServicesResult`].
513 PeerServices(PeerServicesParams),
514 ServiceAllowGrant(ServiceAllowParams),
515 /// Revoke a single stable principal from a single service's allow (#44) — "sharing off"
516 /// WITHOUT unpairing (the peer's identity row is untouched; only NEW sessions are refused).
517 /// Idempotent. Ack result.
518 ServiceAllowRevoke(ServiceAllowParams),
519 /// Publish a LOCAL file INTO a scope: the daemon adds the bytes to its gated
520 /// app-blob store and records the hash in `scope`. `path` is a local file the same-uid daemon
521 /// reads. Answers a [`BlobPublishResult`] carrying the `mcpmesh/blob/1` ticket + hash.
522 /// Tag `"blob_publish"`.
523 BlobPublish(BlobPublishParams),
524 /// Grant a scope to a principal — any flat-namespace entry: a group name, a user_id, or a
525 /// nickname (the shared `principal_set` expansion). Tag
526 /// `"blob_grant"`.
527 BlobGrant(BlobGrantParams),
528 /// List the daemon's blob scopes (name → hashes + grants). Tag `"blob_list"`.
529 BlobList,
530 /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified streaming) and export the
531 /// verified blob to `dest_path` (a local file the same-uid daemon writes). Answers a
532 /// [`BlobFetchResult`] with the verified hash + byte length. Tag `"blob_fetch"`.
533 BlobFetch(BlobFetchParams),
534 /// Summarize this node's LOCAL audit log into per-peer / per-service SESSION counts
535 /// (local-only — the daemon reads its OWN audit dir, nothing is transmitted). The host Mesh surface
536 /// renders these as "who serves me / whom I serve / session counts". Parameterless (like `Status`);
537 /// the server dispatches on the `method` string. Tag `"audit_summary"` (snake_case);
538 /// `method_of` reads the `method` string generically (no per-variant arm).
539 AuditSummary,
540 /// Open a live event stream (pairing liveness & health telemetry). Like `open_session`, the
541 /// connection STOPS being request/response after this call and becomes a one-way push stream
542 /// of `StreamFrame`s. Parameterless. Tag `"subscribe"`.
543 Subscribe,
544}
545
546/// Result of [`Request::OrgJoin`] — the pinned org id echoed back (surface-clean; the fingerprint is
547/// computed porcelain-side from the invite's org_root_pk). Additive-only.
548#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
549pub struct OrgJoinResult {
550 pub org_id: String,
551}
552
553/// Result of a [`Request::RosterInstall`] request (the manual install path): the installed roster's
554/// org id + serial (roster-status vocabulary the confirmation line is permitted to render) plus how
555/// many live sessions the install severed. Surface-clean: NO keys / EndpointIds / paths.
556///
557/// Additive-only: any future field MUST land as
558/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
559#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
560pub struct RosterInstallResult {
561 pub org_id: String,
562 pub serial: u64,
563 /// How many live sessions were severed, for the porcelain's confirmation line.
564 #[serde(default)]
565 pub severed: u32,
566}
567
568/// Result of [`Request::BlobPublish`]: the copyable `mcpmesh/blob/1` ticket + the blob's blake3 hash.
569/// A ticket/hash here is blob-reference vocabulary (NOT a transport-vocab leak — the same
570/// carve-out as the pairing invite line). Additive-only.
571#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
572pub struct BlobPublishResult {
573 pub ticket: String,
574 pub hash: String, // bare blake3 hex
575}
576
577/// One scope in a [`BlobScopeList`]: its name + the hashes it contains + the principals it
578/// grants. Flat vocabulary ONLY — no EndpointId/pubkey/ALPN. Additive-only.
579#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
580pub struct ScopeInfo {
581 pub name: String,
582 pub hashes: Vec<String>,
583 pub grants: Vec<String>,
584}
585
586/// Result of [`Request::BlobList`]: the daemon's scopes. Additive-only.
587#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
588pub struct BlobScopeList {
589 pub scopes: Vec<ScopeInfo>,
590}
591
592/// Result of [`Request::BlobFetch`]: the verified hash + byte length written to `dest_path`.
593/// Additive-only.
594#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
595pub struct BlobFetchResult {
596 pub hash: String,
597 pub bytes_len: u64,
598}
599
600/// Result of [`Request::AuditSummary`]: LOCAL per-peer / per-service session counts
601/// aggregated from this node's OWN audit log — NEVER transmitted (local-only). Surface-clean:
602/// peer names are nicknames / user_ids (NEVER EndpointIds), service names are the registered
603/// service names (NEVER transport vocabulary). A "session" is one `SessionOpen` record. `per_peer` /
604/// `per_service` are sorted ascending by name (deterministic). Tuples mirror kb's
605/// `InsightResponse::per_peer_contribution` — `["bob", 2]` on the wire.
606///
607/// Additive-only: any future field MUST land as
608/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
609#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
610pub struct AuditSummaryResult {
611 /// Sessions opened per peer (nickname). A session with no attributed peer is NOT counted here (no
612 /// peer to attribute) but IS in `total_sessions`.
613 pub per_peer: Vec<(String, u64)>,
614 /// Sessions opened per registered service name.
615 pub per_service: Vec<(String, u64)>,
616 /// Total sessions opened (every `SessionOpen` record, including peer-less ones).
617 #[serde(default)]
618 pub total_sessions: u64,
619}
620
621/// Result of an [`Request::Invite`] request: the copyable `mcpmesh-invite:` artifact
622/// (the ONE pairing artifact deliberately carved out of the
623/// transport-vocabulary blocklist, so this is NOT a transport-vocab leak) plus its
624/// absolute expiry in epoch seconds (≤ now + 24h).
625///
626/// `invite` returns BEFORE any redemption, so the SAS — which is derived from the redeemer's
627/// endpoint id, unknown until they redeem — cannot appear here. The inviter reads its side of
628/// the SAS from [`StatusResult::recent_pairings`] once a redemption completes (a `trust`/`pair`
629/// frame on the live [`StreamFrame`] stream signals that moment). See the "embedding the pairing
630/// ceremony" note in `docs/local-protocol.md` (#35).
631///
632/// Additive-only: any future field MUST land as `#[serde(default, skip_serializing_if = ...)]`
633/// so older payloads still deserialize.
634#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
635pub struct InviteResult {
636 /// The `mcpmesh-invite:<base32>` line, copied out-of-band to the redeemer.
637 pub invite_line: String,
638 /// When the invite expires (epoch seconds); the daemon burns it at redemption or expiry.
639 pub expires_at_epoch: u64,
640}
641
642/// Result of a [`Request::Pair`] request: the inviter's suggested nickname (the
643/// redeemer's local name for the new peer) plus the display-only short authentication
644/// code (SAS) — a few words the human reads aloud to a second channel to
645/// catch a whole-invite forgery / address-swap MITM. The SAS is a pairing-ceremony
646/// artifact (like the invite line), NOT a transport-vocabulary leak.
647///
648/// Additive-only: any future field MUST land as
649/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
650#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
651pub struct PairResult {
652 /// The inviter's suggested nickname (from the invite) — the redeemer's local name for it.
653 pub peer_nickname: String,
654 /// The display-only short authentication code (e.g. `"tango-fig-42"`), shown on both
655 /// sides for the out-of-band human check. Never sent on the wire, never checked
656 /// programmatically.
657 pub sas_code: String,
658 /// The services this pairing granted the redeemer — each mountable as `<peer>/<service>`.
659 /// Populated from the invite (`invite.services`) by the redeemer-side `redeem_invite`, so
660 /// the porcelain can print the "You can mount: alice/notes" line without re-decoding the
661 /// invite. Additive: `#[serde(default, skip_serializing_if = ...)]` so a `PairResult`
662 /// minted by an older daemon (which omits `services`) still deserializes — to an empty list.
663 #[serde(default, skip_serializing_if = "Vec::is_empty")]
664 pub services: Vec<String>,
665 /// The opaque `app_label` the inviter attached at `invite` time (#31), echoed verbatim — or
666 /// absent if none was set. mcpmesh never interprets it; the embedder does. Additive.
667 #[serde(default, skip_serializing_if = "Option::is_none")]
668 pub app_label: Option<String>,
669 /// The inviter's proven self-sovereign `user_id` (`b64u:<user_pk>`), when it presented a
670 /// device→user binding at pairing (#30). This is the STABLE, portable identity the redeemer
671 /// can align with its own — and the same value it may later pass to `open_session` to dial
672 /// this peer by identity rather than by local nickname. `None` if the inviter presented no
673 /// binding (a legacy/keyless peer). Additive.
674 #[serde(default, skip_serializing_if = "Option::is_none")]
675 pub peer_user_id: Option<String>,
676}
677
678/// The event class of an [`AuditRecord`] (the four audit event classes). An additive discriminant on
679/// top of the base record schema: it removes no field and makes the JSONL self-describing so
680/// a consumer can filter by class without guessing from which optional fields are present.
681#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
682#[serde(rename_all = "snake_case")]
683pub enum AuditKind {
684 /// A mesh session opened (a backend was selected for an authenticated peer).
685 /// (A `session_open` with `status:"error"` is a synthesized FAILED-dial marker — no backend
686 /// was reached; it records an attempted-and-failed reach for the telemetry stream.)
687 SessionOpen,
688 /// A mesh session closed (the backend returned / the session tore down).
689 SessionClose,
690 /// One proxied MCP request line (method + tool NAME + args_hash). NEVER carries raw arguments.
691 Request,
692 /// A peer fetched a blob from this node's gated provider (peer + hash + allow/deny).
693 BlobFetch,
694 /// A trust mutation (pair, unpair, roster install/swap, revoke).
695 Trust,
696}
697
698/// One audit record — the union of the event classes, and the `record` payload of a
699/// [`StreamFrame::Event`]. ONE schema for the on-disk JSONL log and the live stream. Every field
700/// beyond `ts`/`kind` is optional and elided when absent (`skip_serializing_if`), so each class
701/// serializes to just its relevant keys (a session record has no `method`; a trust record has no
702/// `bytes_out`).
703///
704/// PRIVACY: the proxied-request record carries `method` + `tool` (NAME only) +
705/// `args_hash` (`"blake3:<hex>"`), and NEVER the raw arguments, the request/response content, or
706/// any tool-output bytes — only a `bytes_out` COUNT and a `status`.
707#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
708pub struct AuditRecord {
709 /// RFC3339 UTC with millisecond precision, e.g. `"2026-07-03T14:02:11.480Z"`. The `YYYY-MM`
710 /// prefix also selects the monthly file (the rotation boundary), so it is always present.
711 pub ts: String,
712 pub kind: AuditKind,
713 /// The gate-resolved authenticated peer (attributed by the endpoint_id-keyed trust gate). Absent on
714 /// local-only events with no remote peer (a manual roster install).
715 #[serde(skip_serializing_if = "Option::is_none")]
716 pub peer: Option<String>,
717 #[serde(skip_serializing_if = "Option::is_none")]
718 pub service: Option<String>,
719 #[serde(skip_serializing_if = "Option::is_none")]
720 pub method: Option<String>,
721 /// The tool NAME only (never its arguments or output) — e.g. `"read_file"` for a `tools/call`.
722 #[serde(skip_serializing_if = "Option::is_none")]
723 pub tool: Option<String>,
724 /// `"blake3:<hex>"` of the request arguments. The raw arguments are NEVER stored.
725 #[serde(skip_serializing_if = "Option::is_none")]
726 pub args_hash: Option<String>,
727 /// Byte COUNT of the response sent back to the peer — a count, never the content.
728 #[serde(skip_serializing_if = "Option::is_none")]
729 pub bytes_out: Option<u64>,
730 /// `"ok"` / `"error"` (proxied request) or `"ok"` / `"denied"` (blob fetch).
731 #[serde(skip_serializing_if = "Option::is_none")]
732 pub status: Option<String>,
733 #[serde(skip_serializing_if = "Option::is_none")]
734 pub latency_ms: Option<u64>,
735 /// Trust-event verb: `"pair"` / `"unpair"` / `"roster_install"` / `"revoke"` (kind == Trust).
736 #[serde(skip_serializing_if = "Option::is_none")]
737 pub event: Option<String>,
738 /// A reference, NEVER content: a blob hash (`BlobFetch`) or a trust-event target such as a
739 /// nickname or `org/serial` (`Trust`).
740 #[serde(skip_serializing_if = "Option::is_none")]
741 pub target: Option<String>,
742}
743
744impl AuditRecord {
745 fn base(ts: String, kind: AuditKind) -> Self {
746 Self {
747 ts,
748 kind,
749 peer: None,
750 service: None,
751 method: None,
752 tool: None,
753 args_hash: None,
754 bytes_out: None,
755 status: None,
756 latency_ms: None,
757 event: None,
758 target: None,
759 }
760 }
761
762 pub fn session_open(ts: String, peer: Option<String>, service: String) -> Self {
763 let mut r = Self::base(ts, AuditKind::SessionOpen);
764 r.peer = peer;
765 r.service = Some(service);
766 r
767 }
768
769 /// Set the record's `status` (`"ok"`/`"error"`/`"denied"`), returning `self` for chaining.
770 /// Marks a synthesized failure record — e.g. the `session_open` for a FAILED dial, which
771 /// reaches no backend and so is never audited by the far side's session guard — without a
772 /// dedicated constructor. DRY: reuses the existing optional `status` field.
773 pub fn with_status(mut self, status: &str) -> Self {
774 self.status = Some(status.into());
775 self
776 }
777
778 pub fn session_close(ts: String, peer: Option<String>, service: String) -> Self {
779 let mut r = Self::base(ts, AuditKind::SessionClose);
780 r.peer = peer;
781 r.service = Some(service);
782 r
783 }
784
785 /// A completed (request→response correlated) proxied line: method + tool NAME + args_hash, plus
786 /// the response's `bytes_out` COUNT, `status`, and `latency_ms`. PRIVACY: `args_hash` is a digest;
787 /// no raw arguments, request/response content, or tool-output bytes are ever passed in.
788 #[allow(clippy::too_many_arguments)]
789 pub fn proxied_request(
790 ts: String,
791 peer: Option<String>,
792 service: String,
793 method: String,
794 tool: Option<String>,
795 args_hash: String,
796 bytes_out: u64,
797 status: String,
798 latency_ms: u64,
799 ) -> Self {
800 let mut r = Self::base(ts, AuditKind::Request);
801 r.peer = peer;
802 r.service = Some(service);
803 r.method = Some(method);
804 r.tool = tool;
805 r.args_hash = Some(args_hash);
806 r.bytes_out = Some(bytes_out);
807 r.status = Some(status);
808 r.latency_ms = Some(latency_ms);
809 r
810 }
811
812 /// A proxied NOTIFICATION line (no `id`, so no response correlates): method + tool + args_hash,
813 /// no `bytes_out`/`status`/`latency_ms`. The line is still recorded — every proxied request is audited.
814 pub fn proxied_notification(
815 ts: String,
816 peer: Option<String>,
817 service: String,
818 method: String,
819 tool: Option<String>,
820 args_hash: String,
821 ) -> Self {
822 let mut r = Self::base(ts, AuditKind::Request);
823 r.peer = peer;
824 r.service = Some(service);
825 r.method = Some(method);
826 r.tool = tool;
827 r.args_hash = Some(args_hash);
828 r
829 }
830
831 pub fn blob_fetch(ts: String, peer: Option<String>, hash: String, status: String) -> Self {
832 let mut r = Self::base(ts, AuditKind::BlobFetch);
833 r.peer = peer;
834 r.target = Some(hash);
835 r.status = Some(status);
836 r
837 }
838
839 pub fn trust(ts: String, event: String, target: Option<String>) -> Self {
840 let mut r = Self::base(ts, AuditKind::Trust);
841 r.event = Some(event);
842 r.target = target;
843 r
844 }
845}
846
847/// One live mesh session, in a [`StreamFrame::Snapshot`]. Surface-clean: `peer` is the
848/// user_id-or-nickname the audit records carry, never an endpoint-id. `opened_at` is epoch seconds.
849#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
850pub struct ActiveSession {
851 pub peer: String,
852 pub service: String,
853 pub opened_at: i64,
854}
855
856/// One frame of the [`Request::Subscribe`] stream (pairing liveness & health telemetry). Tagged on
857/// `type` (snake_case), so a frame is `{"type":"snapshot",...}` / `{"type":"event",...}` /
858/// `{"type":"lagged",...}`. `Event.record` is the [`AuditRecord`] verbatim, so the stream and the
859/// on-disk log carry ONE schema. The daemon serializes these; an embedding consumer deserializes
860/// them (see `docs/local-protocol.md` "Live event stream").
861/// **`#[non_exhaustive]`**: a future frame kind must not break a downstream `match`. Adding
862/// `Reachability` in 0.13.0 DID break exhaustive matches — which is why that release is a MINOR,
863/// per `RELEASING.md`'s pre-1.0 rule that breaking changes bump the minor. Consumers now write a
864/// `_ =>` arm and later additions are additive for Rust as well as for JSON.
865#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
866#[serde(tag = "type", rename_all = "snake_case")]
867#[non_exhaustive]
868pub enum StreamFrame {
869 /// The FIRST frame: a point-in-time picture of the mesh (open sessions + paired-peer
870 /// reachability) so a fresh subscriber renders immediately without replaying history.
871 Snapshot {
872 active_sessions: Vec<ActiveSession>,
873 reachability: Vec<PeerReachability>,
874 },
875 /// A live audit event (session open/close, request, blob fetch, trust) — the tap on the hub.
876 /// Boxed so this (much larger) variant does not bloat every frame; serde delegates through the
877 /// `Box`, so the wire shape is the record's fields verbatim.
878 Event { record: Box<AuditRecord> },
879 /// A peer's reachability TRANSITIONED (#58): it became reachable, became unreachable, or was
880 /// probed for the first time. Pushed so an embedder does not have to poll `status` for a live
881 /// online/offline indicator — and so work queued for an unreachable peer can flush the moment
882 /// it returns, rather than on the next poll tick.
883 ///
884 /// Emitted on a CHANGE of `reachable` only. A refreshed probe with the same verdict emits
885 /// nothing, so a peer that stays up does not produce a frame per TTL refresh; `rtt_ms`/`meta`/
886 /// `services` drift is advisory detail and is not a transition. `age_secs` is `0` — the probe
887 /// just completed.
888 Reachability { peer: PeerReachability },
889 /// The subscriber fell `dropped` records behind the broadcast ring; the stream continues (a
890 /// fresh reconnect would re-`Snapshot`). Never drops the subscriber — lag is reported, never fatal.
891 Lagged { dropped: u64 },
892}
893
894/// Extract the `method` tag from a raw request value without deserializing the whole
895/// message. The daemon's dispatcher uses this: match on the method string, then deserialize
896/// `params` per-method — which tolerates omitted / null / `{}` params for parameterless
897/// methods (adjacent tagging rejects `params:{}` on unit variants).
898pub fn method_of(v: &serde_json::Value) -> Option<&str> {
899 v.get("method").and_then(serde_json::Value::as_str)
900}
901
902/// How a service is answered. Mirrors the config `[services.*]` *kinds*;
903/// Config→BackendSpec is a hand-written match, not a serde passthrough.
904#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
905#[serde(rename_all = "snake_case")]
906pub enum BackendSpec {
907 Run {
908 cmd: Vec<String>,
909 /// Per-service environment variables (#51) for the spawned child. Overlaid on the
910 /// daemon's inherited env; the injected `MCPMESH_PEER_*` identity vars ALWAYS win over
911 /// these (identity is not spoofable by a service definition). Default empty.
912 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
913 env: BTreeMap<String, String>,
914 /// Working directory to spawn the child in (#51). Default: inherit the daemon's cwd.
915 #[serde(default, skip_serializing_if = "Option::is_none")]
916 cwd: Option<String>,
917 },
918 Socket {
919 path: String,
920 },
921}
922
923/// Control-API error code: the named service exists in neither `config.toml` nor the ephemeral
924/// registry (#55). Distinct from the generic `-32000` so a caller can BRANCH on "no such service"
925/// instead of parsing a message — `service_allow_grant`/`service_allow_revoke` previously answered
926/// `{}` (success) for an unknown name, which silently included every ephemeral service.
927pub const ERR_NO_SUCH_SERVICE: i64 = -32040;
928
929pub const API_NAME: &str = "mcpmesh-local/1";
930/// The protocol-compatibility version as `"MAJOR.MINOR"`, distinct from the crate/stack version.
931///
932/// - **MAJOR** matches the `/N` in [`API_NAME`] and changes only on a breaking wire change (the
933/// transport already rejects a mismatched `api`, so an equality check on that is redundant).
934/// - **MINOR** ([`API_MINOR`]) increments on EVERY surface change within a major — additive fields,
935/// new methods, or a strictness change like params validation — bumped in the same change that
936/// makes it. A client can guard with `api_minor >= N` for a feature it needs, or refuse a daemon
937/// older than a minor it requires. It never resets except on a MAJOR bump.
938pub const API_VERSION: &str = "1.12";
939/// The integer MINOR of [`API_VERSION`] — see there. Bumped from 0 to 1 when params validation
940/// became strict (#34); to 2 with the `set_nickname` verb + `StatusResult.self_nickname` (#37);
941/// to 3 when `allow`/grant strings became STABLE principals — `b64u:`/`eid:`/roster names,
942/// never nicknames (#38); to 4 with the `set_app_metadata` verb + `PresencePeer.meta` (#39);
943/// to 5 with `PeerReachability.meta` — pairing-mode app metadata on the probe pong (#40);
944/// to 6 with `PeerInfo.principal` — the peer's eid: device principal on `status` (#41);
945/// to 7 with `PeerReachability.principal` — the same on reachability rows (#42); to 8 with the
946/// `service_allow_grant`/`service_allow_revoke` per-peer access verbs (#44); to 9 covering the
947/// `unregister_service` (#50) / `peer_services` (#52) / Run `env`+`cwd` (#51) surface that shipped
948/// in 0.10.1 without a bump, PLUS the `set_relays` live relay-set verb (#53); to 10 when
949/// `service_allow_revoke`/`peer_remove` became IMMEDIATE — no verb shape changed, but their
950/// observable contract did: a revoked principal's next session is refused even on a connection it
951/// already holds, and its live connections are severed. Previously both waited for the peer to
952/// disconnect on its own, which is unbounded (#54). A consumer can guard on
953/// `api_minor >= 10` before telling a user that revocation has taken effect; to 11 when
954/// `service_allow_grant`/`service_allow_revoke` gained EPHEMERAL-service support and became strict
955/// about an unknown service name — a name in neither the config nor the ephemeral registry now
956/// answers [`ERR_NO_SUCH_SERVICE`] instead of a silent `{}` (#55, #69); to 12 with the pushed
957/// [`StreamFrame::Reachability`] liveness transition frame (#58).
958pub const API_MINOR: u32 = 12;
959
960#[cfg(test)]
961mod tests {
962 use super::*;
963
964 /// #58: the pushed liveness frame tags as `{"type":"reachability","peer":{…}}` and carries a
965 /// whole `PeerReachability` row — the SAME shape the opening snapshot's list holds, so a
966 /// consumer projects both through one code path.
967 #[test]
968 fn reachability_frame_tags_and_round_trips() {
969 let frame = StreamFrame::Reachability {
970 peer: PeerReachability {
971 name: "bob".into(),
972 reachable: true,
973 rtt_ms: Some(12),
974 age_secs: Some(0),
975 meta: String::new(),
976 principal: Some("eid:beef".into()),
977 },
978 };
979 let v = serde_json::to_value(&frame).unwrap();
980 assert_eq!(v["type"], "reachability");
981 assert_eq!(v["peer"]["name"], "bob");
982 assert_eq!(v["peer"]["reachable"], true);
983 assert_eq!(
984 v["peer"]["age_secs"], 0,
985 "a transition frame is fresh by construction: {v}"
986 );
987 let back: StreamFrame = serde_json::from_value(v).unwrap();
988 assert_eq!(back, frame);
989 }
990
991 #[test]
992 fn peer_reachability_serde_is_additive() {
993 let r = PeerReachability {
994 name: "bob".into(),
995 reachable: true,
996 rtt_ms: Some(42),
997 age_secs: Some(3),
998 meta: String::new(),
999 principal: None,
1000 };
1001 let v = serde_json::to_value(&r).unwrap();
1002 assert_eq!(v["name"], "bob");
1003 assert_eq!(v["reachable"], true);
1004 assert_eq!(v["rtt_ms"], 42);
1005 assert_eq!(v["age_secs"], 3);
1006 // Never-probed peer: optionals elided, not null.
1007 let unknown = PeerReachability {
1008 name: "carol".into(),
1009 reachable: false,
1010 rtt_ms: None,
1011 age_secs: None,
1012 meta: String::new(),
1013 principal: None,
1014 };
1015 let uv = serde_json::to_value(&unknown).unwrap();
1016 assert!(uv.get("rtt_ms").is_none() && uv.get("age_secs").is_none());
1017 // An older StatusResult (no reachability field) still deserializes.
1018 let old = serde_json::json!({"stack_version":"0.1.0","services":[],"peers":[]});
1019 let s: StatusResult = serde_json::from_value(old).unwrap();
1020 assert!(s.reachability.is_empty());
1021 }
1022
1023 #[test]
1024 fn subscribe_method_tag_resolves() {
1025 let req = serde_json::to_value(Request::Subscribe).unwrap();
1026 assert_eq!(method_of(&req), Some("subscribe"));
1027 }
1028
1029 // --- #34: params structs reject unknown fields (the `{service: "kb"}` silent-accept bug) ---
1030
1031 #[test]
1032 fn invite_params_reject_singular_service_typo() {
1033 // The reported bug: `{"service":"kb"}` (singular) used to deserialize to
1034 // InviteParams { services: [] } and mint a grants-nothing invite that looked
1035 // successful. With deny_unknown_fields the typo is a loud parse error instead.
1036 let err = serde_json::from_value::<InviteParams>(serde_json::json!({"service": "kb"}));
1037 assert!(
1038 err.is_err(),
1039 "an unknown `service` key must be rejected, not silently ignored"
1040 );
1041 // The correct plural shape still parses.
1042 let ok: InviteParams =
1043 serde_json::from_value(serde_json::json!({"services": ["kb"]})).unwrap();
1044 assert_eq!(ok.services, vec!["kb".to_string()]);
1045 }
1046
1047 #[test]
1048 fn open_session_params_reject_unknown_field() {
1049 let err = serde_json::from_value::<OpenSessionParams>(
1050 serde_json::json!({"peer": "a", "service": "b", "nonsense": 1}),
1051 );
1052 assert!(err.is_err(), "unknown params keys must be rejected");
1053 }
1054
1055 #[test]
1056 fn set_app_metadata_request_carries_the_method_tag() {
1057 let r = Request::SetAppMetadata(SetAppMetadataParams {
1058 metadata: "v=1.2.3".into(),
1059 });
1060 let v = serde_json::to_value(&r).unwrap();
1061 assert_eq!(v["method"], "set_app_metadata");
1062 assert_eq!(v["params"]["metadata"], "v=1.2.3");
1063 assert_eq!(method_of(&v), Some("set_app_metadata"));
1064 }
1065
1066 #[test]
1067 fn set_app_metadata_params_reject_unknown_field() {
1068 let err = serde_json::from_value::<SetAppMetadataParams>(
1069 serde_json::json!({"metadata": "x", "nonsense": 1}),
1070 );
1071 assert!(err.is_err(), "unknown params keys must be rejected");
1072 }
1073
1074 /// `PresencePeer.meta` is additive — an older payload (no meta) still deserializes, and an
1075 /// empty meta does not serialize.
1076 #[test]
1077 fn peer_info_principal_is_additive() {
1078 // An older payload (no principal) still deserializes; empty does not serialize.
1079 let old = serde_json::json!({"name": "bob", "services": ["notes"]});
1080 let p: PeerInfo = serde_json::from_value(old).unwrap();
1081 assert_eq!(p.principal, None);
1082 assert!(serde_json::to_value(&p).unwrap().get("principal").is_none());
1083 // A bound peer carries BOTH the person user_id AND the device principal (#41).
1084 let full = PeerInfo {
1085 name: "bob".into(),
1086 services: vec!["notes".into()],
1087 user_id: Some("b64u:BOB".into()),
1088 principal: Some("eid:0707".into()),
1089 };
1090 let back: PeerInfo = serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
1091 assert_eq!(back.user_id.as_deref(), Some("b64u:BOB"));
1092 assert_eq!(back.principal.as_deref(), Some("eid:0707"));
1093 }
1094
1095 #[test]
1096 fn peer_reachability_principal_is_additive() {
1097 // Older payload (no principal) still deserializes; empty does not serialize; a set
1098 // value round-trips alongside the #40 meta so an embedder joins on the principal.
1099 let old = serde_json::json!({"name": "bob", "reachable": true});
1100 let r: PeerReachability = serde_json::from_value(old).unwrap();
1101 assert_eq!(r.principal, None);
1102 assert!(serde_json::to_value(&r).unwrap().get("principal").is_none());
1103 let full = PeerReachability {
1104 name: "bob".into(),
1105 reachable: true,
1106 rtt_ms: Some(12),
1107 age_secs: Some(3),
1108 meta: "v=1.2.3".into(),
1109 principal: Some("eid:0707".into()),
1110 };
1111 let back: PeerReachability =
1112 serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
1113 assert_eq!(back.principal.as_deref(), Some("eid:0707"));
1114 assert_eq!(back.meta, "v=1.2.3");
1115 }
1116
1117 #[test]
1118 fn peer_reachability_meta_is_additive() {
1119 // An older payload (no meta) still deserializes; an empty meta does not serialize.
1120 let old = serde_json::json!({"name": "bob", "reachable": true});
1121 let r: PeerReachability = serde_json::from_value(old).unwrap();
1122 assert_eq!(r.meta, "");
1123 assert!(serde_json::to_value(&r).unwrap().get("meta").is_none());
1124 // A set value round-trips.
1125 let with = PeerReachability {
1126 name: "bob".into(),
1127 reachable: true,
1128 rtt_ms: Some(12),
1129 age_secs: Some(3),
1130 meta: "v=1.2.3".into(),
1131 principal: None,
1132 };
1133 let back: PeerReachability =
1134 serde_json::from_value(serde_json::to_value(&with).unwrap()).unwrap();
1135 assert_eq!(back.meta, "v=1.2.3");
1136 }
1137
1138 #[test]
1139 fn presence_peer_meta_is_additive() {
1140 let old = serde_json::json!({
1141 "user_id": "b64u:A", "device_label": "laptop", "role": "primary", "online": true
1142 });
1143 let p: PresencePeer = serde_json::from_value(old).unwrap();
1144 assert_eq!(p.meta, "");
1145 assert!(serde_json::to_value(&p).unwrap().get("meta").is_none());
1146 }
1147
1148 #[test]
1149 fn set_nickname_request_carries_the_method_tag() {
1150 let r = Request::SetNickname(SetNicknameParams {
1151 nickname: "workbench".into(),
1152 });
1153 let v = serde_json::to_value(&r).unwrap();
1154 assert_eq!(v["method"], "set_nickname");
1155 assert_eq!(v["params"]["nickname"], "workbench");
1156 assert_eq!(method_of(&v), Some("set_nickname"));
1157 }
1158
1159 #[test]
1160 fn set_nickname_params_reject_unknown_field() {
1161 let err = serde_json::from_value::<SetNicknameParams>(
1162 serde_json::json!({"nickname": "x", "nonsense": 1}),
1163 );
1164 assert!(err.is_err(), "unknown params keys must be rejected");
1165 }
1166
1167 /// An OLDER daemon's status payload (no `self_nickname`) must still deserialize —
1168 /// the additive-only contract — and an empty name must not serialize at all.
1169 #[test]
1170 fn status_self_nickname_is_additive() {
1171 let old = serde_json::json!({
1172 "stack_version": "0.7.0", "services": [], "peers": []
1173 });
1174 let s: StatusResult = serde_json::from_value(old).unwrap();
1175 assert_eq!(s.self_nickname, "");
1176 let v = serde_json::to_value(&s).unwrap();
1177 assert!(v.get("self_nickname").is_none(), "empty name is skipped");
1178 }
1179
1180 #[test]
1181 fn api_minor_is_present_and_monotonic_from_hello() {
1182 // #34 part 2: a machine-comparable protocol-compat minor, distinct from the
1183 // crate/stack version, additive on the Hello frame.
1184 let h = Hello {
1185 api: API_NAME.into(),
1186 api_version: API_VERSION.into(),
1187 api_minor: API_MINOR,
1188 stack_version: "9.9.9".into(),
1189 };
1190 let v = serde_json::to_value(&h).unwrap();
1191 assert_eq!(v["api_minor"], API_MINOR);
1192 // An OLD Hello without api_minor still deserializes (additive contract).
1193 let old = serde_json::json!({
1194 "api": API_NAME, "api_version": "1.0", "stack_version": "0.4.0"
1195 });
1196 let back: Hello = serde_json::from_value(old).unwrap();
1197 assert_eq!(back.api_minor, 0, "absent api_minor defaults to 0");
1198 }
1199
1200 #[test]
1201 fn hello_result_roundtrips() {
1202 let h = Hello {
1203 api: "mcpmesh-local/1".into(),
1204 api_version: "1.0".into(),
1205 api_minor: 0,
1206 stack_version: "0.1.0".into(),
1207 };
1208 let v = serde_json::to_value(&h).unwrap();
1209 assert_eq!(v["api"], "mcpmesh-local/1");
1210 let back: Hello = serde_json::from_value(v).unwrap();
1211 assert_eq!(back, h);
1212 }
1213
1214 #[test]
1215 fn request_tagged_by_method() {
1216 let r = Request::Status;
1217 assert_eq!(serde_json::to_value(&r).unwrap()["method"], "status");
1218 let r = Request::OpenSession(OpenSessionParams {
1219 peer: "alice".into(),
1220 service: "notes".into(),
1221 });
1222 let v = serde_json::to_value(&r).unwrap();
1223 assert_eq!(v["method"], "open_session");
1224 assert_eq!(v["params"]["peer"], "alice");
1225 }
1226
1227 #[test]
1228 fn parameterless_method_tolerates_params_forms() {
1229 // Omitted and null params deserialize straight into the unit variant.
1230 let omitted: Request =
1231 serde_json::from_value(serde_json::json!({"method": "status"})).unwrap();
1232 assert_eq!(omitted, Request::Status);
1233 let null: Request =
1234 serde_json::from_value(serde_json::json!({"method": "status", "params": null}))
1235 .unwrap();
1236 assert_eq!(null, Request::Status);
1237
1238 // Known limitation: adjacent tagging rejects `params:{}` for a unit variant, so
1239 // the server MUST dispatch on the method string rather than deserialize the whole
1240 // message into `Request`. This is the pattern the daemon's dispatcher uses.
1241 let empty = serde_json::json!({"method": "status", "params": {}});
1242 assert!(serde_json::from_value::<Request>(empty.clone()).is_err());
1243 match method_of(&empty) {
1244 Some("status") => {} // dispatcher resolves Status via the method string
1245 other => panic!("method_of failed to resolve status: {other:?}"),
1246 }
1247 }
1248
1249 #[test]
1250 fn backend_spec_roundtrips() {
1251 let run = BackendSpec::Run {
1252 cmd: vec!["notes-mcp".into(), "--stdio".into()],
1253 env: Default::default(),
1254 cwd: None,
1255 };
1256 let v = serde_json::to_value(&run).unwrap();
1257 assert_eq!(v["run"]["cmd"][0], "notes-mcp");
1258 assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), run);
1259
1260 let sock = BackendSpec::Socket {
1261 path: "/run/notes.sock".into(),
1262 };
1263 let v = serde_json::to_value(&sock).unwrap();
1264 assert_eq!(v["socket"]["path"], "/run/notes.sock");
1265 assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), sock);
1266 }
1267
1268 #[test]
1269 fn register_service_wire_shape() {
1270 let r = Request::RegisterService(RegisterServiceParams {
1271 name: "notes".into(),
1272 backend: BackendSpec::Run {
1273 cmd: vec!["notes-mcp".into()],
1274 env: Default::default(),
1275 cwd: None,
1276 },
1277 allow: vec!["alice".into()],
1278 ephemeral: false,
1279 });
1280 let v = serde_json::to_value(&r).unwrap();
1281 assert_eq!(
1282 v,
1283 serde_json::json!({
1284 "method": "register_service",
1285 "params": {
1286 "name": "notes",
1287 "backend": {"run": {"cmd": ["notes-mcp"]}},
1288 "allow": ["alice"],
1289 }
1290 })
1291 );
1292 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1293 }
1294
1295 #[test]
1296 fn invite_request_and_result_roundtrip() {
1297 // Request::Invite → `{ "method": "invite", "params": { "services": [...] } }`.
1298 let r = Request::Invite(InviteParams {
1299 services: vec!["notes".into(), "kb".into()],
1300 app_label: None,
1301 });
1302 let v = serde_json::to_value(&r).unwrap();
1303 assert_eq!(v["method"], "invite");
1304 assert_eq!(v["params"]["services"][0], "notes");
1305 assert_eq!(v["params"]["services"][1], "kb");
1306 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1307 // method_of resolves the tag generically (no per-variant arm).
1308 assert_eq!(
1309 method_of(&serde_json::json!({"method": "invite", "params": {"services": []}})),
1310 Some("invite")
1311 );
1312
1313 // InviteResult carries the copyable line + expiry (surface #2 pairing artifact).
1314 let res = InviteResult {
1315 invite_line: "mcpmesh-invite:ABCDEF".into(),
1316 expires_at_epoch: 1_800_000_000,
1317 };
1318 let v = serde_json::to_value(&res).unwrap();
1319 assert_eq!(v["invite_line"], "mcpmesh-invite:ABCDEF");
1320 assert_eq!(v["expires_at_epoch"], 1_800_000_000u64);
1321 assert_eq!(serde_json::from_value::<InviteResult>(v).unwrap(), res);
1322 }
1323
1324 #[test]
1325 fn pair_request_and_result_roundtrip() {
1326 // Request::Pair → `{ "method": "pair", "params": { "invite_line": "..." } }`.
1327 let r = Request::Pair(PairParams {
1328 invite_line: "mcpmesh-invite:ABCDEF".into(),
1329 });
1330 let v = serde_json::to_value(&r).unwrap();
1331 assert_eq!(v["method"], "pair");
1332 assert_eq!(v["params"]["invite_line"], "mcpmesh-invite:ABCDEF");
1333 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1334 // method_of resolves the tag generically (no per-variant arm).
1335 assert_eq!(
1336 method_of(&serde_json::json!({"method": "pair", "params": {"invite_line": "x"}})),
1337 Some("pair")
1338 );
1339
1340 // PairResult carries the inviter's suggested nickname + the display-only SAS words +
1341 // the granted services (the porcelain renders each as `<peer>/<service>`).
1342 let res = PairResult {
1343 peer_nickname: "alice".into(),
1344 sas_code: "tango-fig-cabbage".into(),
1345 services: vec!["notes".into(), "kb".into()],
1346 app_label: None,
1347 peer_user_id: None,
1348 };
1349 let v = serde_json::to_value(&res).unwrap();
1350 assert_eq!(v["peer_nickname"], "alice");
1351 assert_eq!(v["sas_code"], "tango-fig-cabbage");
1352 assert_eq!(v["services"][0], "notes");
1353 assert_eq!(v["services"][1], "kb");
1354 assert_eq!(serde_json::from_value::<PairResult>(v).unwrap(), res);
1355
1356 // Additive-only: a PairResult minted by an older daemon (no `services` key) still
1357 // deserializes — the `#[serde(default)]` fills it with an empty list.
1358 let old_shape = serde_json::json!({
1359 "peer_nickname": "alice",
1360 "sas_code": "tango-fig-cabbage",
1361 });
1362 let back: PairResult = serde_json::from_value(old_shape).unwrap();
1363 assert_eq!(back.peer_nickname, "alice");
1364 assert!(back.services.is_empty());
1365 }
1366
1367 #[test]
1368 fn roster_install_request_and_result_roundtrip() {
1369 // Request::RosterInstall → `{ "method": "roster_install", "params": { "path": ...,
1370 // "org_root_pk": ... } }`. The optional pk is present on the first-install shape.
1371 let r = Request::RosterInstall(RosterInstallParams {
1372 path: "/tmp/roster.json".into(),
1373 org_root_pk: Some("b64u:AAAA".into()),
1374 });
1375 let v = serde_json::to_value(&r).unwrap();
1376 assert_eq!(v["method"], "roster_install");
1377 assert_eq!(v["params"]["path"], "/tmp/roster.json");
1378 assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
1379 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1380 // method_of resolves the tag generically (no per-variant arm).
1381 assert_eq!(
1382 method_of(&serde_json::json!({"method": "roster_install", "params": {"path": "/x"}})),
1383 Some("roster_install")
1384 );
1385
1386 // When the pk is omitted (a subsequent install using the pinned value), it is
1387 // `skip_serializing_if`-dropped from the wire and deserializes back to `None`.
1388 let omit = Request::RosterInstall(RosterInstallParams {
1389 path: "/tmp/roster.json".into(),
1390 org_root_pk: None,
1391 });
1392 let v = serde_json::to_value(&omit).unwrap();
1393 assert!(
1394 v["params"].get("org_root_pk").is_none(),
1395 "an omitted org_root_pk must not appear on the wire: {v}"
1396 );
1397 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), omit);
1398
1399 // RosterInstallResult carries org_id + serial + severed count (roster-status vocabulary).
1400 let res = RosterInstallResult {
1401 org_id: "acme".into(),
1402 serial: 42,
1403 severed: 1,
1404 };
1405 let v = serde_json::to_value(&res).unwrap();
1406 assert_eq!(v["org_id"], "acme");
1407 assert_eq!(v["serial"], 42u64);
1408 assert_eq!(v["severed"], 1u32);
1409 assert_eq!(
1410 serde_json::from_value::<RosterInstallResult>(v).unwrap(),
1411 res
1412 );
1413
1414 // Additive-only: a result minted by an older daemon (no `severed` key) still
1415 // deserializes — the `#[serde(default)]` fills it with 0.
1416 let old_shape = serde_json::json!({ "org_id": "acme", "serial": 7 });
1417 let back: RosterInstallResult = serde_json::from_value(old_shape).unwrap();
1418 assert_eq!(back.serial, 7);
1419 assert_eq!(back.severed, 0);
1420 }
1421
1422 #[test]
1423 fn org_join_request_and_result_roundtrip() {
1424 // Request::OrgJoin → `{ "method": "org_join", "params": { org_id, org_root_pk, user_id,
1425 // user_key } }`. `user_key` is a LOCAL path string (the key never crosses the API).
1426 let r = Request::OrgJoin(OrgJoinParams {
1427 org_id: "acme".into(),
1428 org_root_pk: "b64u:AAAA".into(),
1429 user_id: "alice".into(),
1430 user_key: "/home/alice/.config/mcpmesh/user.key".into(),
1431 });
1432 let v = serde_json::to_value(&r).unwrap();
1433 assert_eq!(v["method"], "org_join");
1434 assert_eq!(v["params"]["org_id"], "acme");
1435 assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
1436 assert_eq!(v["params"]["user_id"], "alice");
1437 assert_eq!(
1438 v["params"]["user_key"],
1439 "/home/alice/.config/mcpmesh/user.key"
1440 );
1441 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1442 // method_of resolves the tag generically (no per-variant arm).
1443 assert_eq!(
1444 method_of(&serde_json::json!({"method": "org_join", "params": {"org_id": "x"}})),
1445 Some("org_join")
1446 );
1447
1448 // OrgJoinResult echoes the pinned org id (surface-clean; the fingerprint is porcelain-side).
1449 let res = OrgJoinResult {
1450 org_id: "acme".into(),
1451 };
1452 let v = serde_json::to_value(&res).unwrap();
1453 assert_eq!(v["org_id"], "acme");
1454 assert_eq!(serde_json::from_value::<OrgJoinResult>(v).unwrap(), res);
1455 }
1456
1457 #[test]
1458 fn set_roster_url_request_roundtrip() {
1459 // Request::SetRosterUrl → `{ "method": "set_roster_url", "params": { "url": "..." } }`.
1460 let r = Request::SetRosterUrl(SetRosterUrlParams {
1461 url: "https://intranet.acme.com/roster.json".into(),
1462 });
1463 let v = serde_json::to_value(&r).unwrap();
1464 assert_eq!(v["method"], "set_roster_url");
1465 assert_eq!(v["params"]["url"], "https://intranet.acme.com/roster.json");
1466 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1467 assert_eq!(
1468 method_of(&serde_json::json!({"method": "set_roster_url", "params": {"url": "x"}})),
1469 Some("set_roster_url")
1470 );
1471 }
1472
1473 #[test]
1474 fn peer_remove_request_roundtrip() {
1475 // Request::PeerRemove → `{ "method": "peer_remove", "params": { "nickname": "..." } }`.
1476 let r = Request::PeerRemove(PeerRemoveParams {
1477 nickname: "bob".into(),
1478 });
1479 let v = serde_json::to_value(&r).unwrap();
1480 assert_eq!(v["method"], "peer_remove");
1481 assert_eq!(v["params"]["nickname"], "bob");
1482 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1483 // method_of resolves the tag generically (no per-variant arm).
1484 assert_eq!(
1485 method_of(&serde_json::json!({"method": "peer_remove", "params": {"nickname": "bob"}})),
1486 Some("peer_remove")
1487 );
1488 }
1489
1490 /// The reserved/internal `peer_add` rides the SAME typed vocabulary as every other method —
1491 /// `{ "method": "peer_add", "params": { nickname, endpoint_id, allow } }` — with `allow`
1492 /// defaulting to empty when absent.
1493 #[test]
1494 fn peer_add_request_roundtrip() {
1495 let r = Request::PeerAdd(PeerAddParams {
1496 nickname: "bob".into(),
1497 endpoint_id: "96246d3f".into(),
1498 allow: vec!["notes".into()],
1499 });
1500 let v = serde_json::to_value(&r).unwrap();
1501 assert_eq!(v["method"], "peer_add");
1502 assert_eq!(v["params"]["nickname"], "bob");
1503 assert_eq!(v["params"]["endpoint_id"], "96246d3f");
1504 assert_eq!(v["params"]["allow"][0], "notes");
1505 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1506 // An absent allow list deserializes to empty (the server-side tolerance).
1507 let p: PeerAddParams =
1508 serde_json::from_value(serde_json::json!({"nickname": "bob", "endpoint_id": "x"}))
1509 .unwrap();
1510 assert!(p.allow.is_empty());
1511 }
1512
1513 #[test]
1514 fn peer_rename_request_roundtrip() {
1515 // By user_id (renames all of a person's devices in one op).
1516 let r = Request::PeerRename(PeerRenameParams {
1517 user_id: Some("b64u:BOB".into()),
1518 nickname: None,
1519 to: "Bobby".into(),
1520 });
1521 let v = serde_json::to_value(&r).unwrap();
1522 assert_eq!(v["method"], "peer_rename");
1523 assert_eq!(v["params"]["user_id"], "b64u:BOB");
1524 assert_eq!(v["params"]["to"], "Bobby");
1525 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1526 // A provisional contact is renamed by nickname; omitted user_id defaults to None.
1527 assert_eq!(
1528 method_of(
1529 &serde_json::json!({"method": "peer_rename", "params": {"nickname": "carol", "to": "Carol"}})
1530 ),
1531 Some("peer_rename")
1532 );
1533 }
1534
1535 #[test]
1536 fn status_result_roundtrips() {
1537 // Pure-pairing daemon: `roster` is None — absent from the wire (skip_serializing_if) and an
1538 // older payload with no `roster` key still deserializes to None (serde default).
1539 let s = StatusResult {
1540 stack_version: "0.1.0".into(),
1541 services: vec![ServiceInfo {
1542 name: "notes".into(),
1543 allow: vec!["alice".into()],
1544 allow_display: vec![],
1545 backend: BackendKind::Run,
1546 ephemeral: false,
1547 }],
1548 peers: vec![PeerInfo {
1549 name: "alice".into(),
1550 services: vec!["notes".into()],
1551 // A paired peer that proved a self-sovereign user_id at pairing (surface-clean id).
1552 user_id: Some("b64u:alicepk".into()),
1553 principal: None,
1554 }],
1555 roster: None,
1556 presence: vec![],
1557 self_user_id: Some("b64u:selfpk".into()),
1558 recent_pairings: vec![],
1559 reachability: vec![],
1560 self_nickname: String::new(),
1561 };
1562 let v = serde_json::to_value(&s).unwrap();
1563 assert_eq!(v["services"][0]["backend"], "run");
1564 // The additive identity fields ride the wire when present.
1565 assert_eq!(v["peers"][0]["user_id"], "b64u:alicepk");
1566 assert_eq!(v["self_user_id"], "b64u:selfpk");
1567 assert!(
1568 v.get("roster").is_none(),
1569 "an absent roster must not appear on the wire: {v}"
1570 );
1571 assert!(
1572 v.get("presence").is_none(),
1573 "an empty presence must not appear on the wire: {v}"
1574 );
1575 assert!(
1576 v.get("recent_pairings").is_none(),
1577 "an empty recent_pairings must not appear on the wire: {v}"
1578 );
1579 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1580
1581 // A payload minted by an older daemon (no `roster`/`presence`/identity keys) still
1582 // deserializes — the identity fields default to None / a nickname-only peer.
1583 let old_shape = serde_json::json!({
1584 "stack_version": "0.1.0",
1585 "services": [],
1586 "peers": [{ "name": "bob", "services": [] }],
1587 });
1588 let back: StatusResult = serde_json::from_value(old_shape).unwrap();
1589 assert!(back.roster.is_none());
1590 assert!(back.presence.is_empty());
1591 assert!(back.self_user_id.is_none());
1592 assert!(back.peers[0].user_id.is_none());
1593 assert!(back.recent_pairings.is_empty());
1594
1595 // Roster daemon: a Some(RosterStatus) + an advisory presence list round-trip. `presence`
1596 // carries FLAT vocabulary only (user_id/device_label/role/online) — no EndpointId/key.
1597 let s = StatusResult {
1598 stack_version: "0.1.0".into(),
1599 services: vec![],
1600 peers: vec![],
1601 roster: Some(RosterStatus {
1602 org_id: "acme".into(),
1603 serial: 42,
1604 state: "approved".into(),
1605 org_root_fingerprint: "tango-fig-cabbage-anchor".into(),
1606 }),
1607 presence: vec![
1608 PresencePeer {
1609 user_id: "alice".into(),
1610 device_label: "laptop".into(),
1611 role: "primary".into(),
1612 online: true,
1613 meta: String::new(),
1614 },
1615 PresencePeer {
1616 user_id: "alice".into(),
1617 device_label: "desktop".into(),
1618 role: "mirror".into(),
1619 online: false,
1620 meta: String::new(),
1621 },
1622 ],
1623 self_user_id: None,
1624 recent_pairings: vec![],
1625 reachability: vec![],
1626 self_nickname: String::new(),
1627 };
1628 let v = serde_json::to_value(&s).unwrap();
1629 assert_eq!(v["roster"]["org_id"], "acme");
1630 assert_eq!(v["roster"]["serial"], 42u64);
1631 assert_eq!(v["roster"]["state"], "approved");
1632 assert_eq!(
1633 v["roster"]["org_root_fingerprint"],
1634 "tango-fig-cabbage-anchor"
1635 );
1636 assert_eq!(v["presence"][0]["user_id"], "alice");
1637 assert_eq!(v["presence"][0]["device_label"], "laptop");
1638 assert_eq!(v["presence"][0]["role"], "primary");
1639 assert_eq!(v["presence"][0]["online"], true);
1640 assert_eq!(v["presence"][1]["online"], false);
1641 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1642 }
1643
1644 /// The `recent_pairings` status field is ADDITIVE: a populated list round-trips with
1645 /// the flat `{peer_nickname, sas_code, paired_at_epoch}` shape (nickname + SAS words + epoch —
1646 /// never an EndpointId), an empty list is dropped from the wire, and a payload minted by an
1647 /// older daemon (no key at all) still deserializes to empty.
1648 #[test]
1649 fn recent_pairings_are_additive_on_status() {
1650 let s = StatusResult {
1651 stack_version: "0.1.0".into(),
1652 services: vec![],
1653 peers: vec![],
1654 roster: None,
1655 presence: vec![],
1656 self_user_id: None,
1657 recent_pairings: vec![RecentPairing {
1658 peer_nickname: "bob".into(),
1659 sas_code: "tango-fig-cabbage".into(),
1660 paired_at_epoch: 1_800_000_000,
1661 }],
1662 reachability: vec![],
1663 self_nickname: String::new(),
1664 };
1665 let v = serde_json::to_value(&s).unwrap();
1666 assert_eq!(v["recent_pairings"][0]["peer_nickname"], "bob");
1667 assert_eq!(v["recent_pairings"][0]["sas_code"], "tango-fig-cabbage");
1668 assert_eq!(v["recent_pairings"][0]["paired_at_epoch"], 1_800_000_000u64);
1669 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1670
1671 // A payload minted by an OLDER daemon (no `recent_pairings` key) still deserializes —
1672 // the `#[serde(default)]` fills it with an empty list.
1673 let old_shape = serde_json::json!({
1674 "stack_version": "0.1.0",
1675 "services": [],
1676 "peers": [],
1677 });
1678 let back: StatusResult = serde_json::from_value(old_shape).unwrap();
1679 assert!(back.recent_pairings.is_empty());
1680 }
1681
1682 #[test]
1683 fn blob_requests_and_results_roundtrip() {
1684 // BlobPublish → { method, params: { scope, path } }.
1685 let r = Request::BlobPublish(BlobPublishParams {
1686 scope: "docs".into(),
1687 path: "/tmp/a.bin".into(),
1688 });
1689 let v = serde_json::to_value(&r).unwrap();
1690 assert_eq!(v["method"], "blob_publish");
1691 assert_eq!(v["params"]["scope"], "docs");
1692 assert_eq!(v["params"]["path"], "/tmp/a.bin");
1693 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1694
1695 // BlobGrant → { method, params: { scope, principal } }.
1696 let r = Request::BlobGrant(BlobGrantParams {
1697 scope: "docs".into(),
1698 principal: "alice".into(),
1699 });
1700 let v = serde_json::to_value(&r).unwrap();
1701 assert_eq!(v["method"], "blob_grant");
1702 assert_eq!(v["params"]["principal"], "alice");
1703 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1704
1705 // BlobList is parameterless (method_of resolves it).
1706 assert_eq!(
1707 method_of(&serde_json::json!({"method": "blob_list"})),
1708 Some("blob_list")
1709 );
1710
1711 // BlobFetch → { method, params: { ticket, dest_path } }.
1712 let r = Request::BlobFetch(BlobFetchParams {
1713 ticket: "blobAAA".into(),
1714 dest_path: "/tmp/out.bin".into(),
1715 });
1716 let v = serde_json::to_value(&r).unwrap();
1717 assert_eq!(v["method"], "blob_fetch");
1718 assert_eq!(v["params"]["ticket"], "blobAAA");
1719 assert_eq!(v["params"]["dest_path"], "/tmp/out.bin");
1720 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1721
1722 // BlobPublishResult carries the ticket + hash (blob-reference vocabulary).
1723 let res = BlobPublishResult {
1724 ticket: "blobAAA".into(),
1725 hash: "ab".repeat(32),
1726 };
1727 let v = serde_json::to_value(&res).unwrap();
1728 assert_eq!(v["ticket"], "blobAAA");
1729 assert_eq!(serde_json::from_value::<BlobPublishResult>(v).unwrap(), res);
1730
1731 // BlobScopeList carries flat (name, hashes, grants) — no EndpointId/key leakage.
1732 let res = BlobScopeList {
1733 scopes: vec![ScopeInfo {
1734 name: "docs".into(),
1735 hashes: vec!["ab".repeat(32)],
1736 grants: vec!["alice".into()],
1737 }],
1738 };
1739 let v = serde_json::to_value(&res).unwrap();
1740 assert_eq!(v["scopes"][0]["name"], "docs");
1741 assert_eq!(v["scopes"][0]["grants"][0], "alice");
1742 assert_eq!(serde_json::from_value::<BlobScopeList>(v).unwrap(), res);
1743
1744 // BlobFetchResult carries the verified hash + byte length.
1745 let res = BlobFetchResult {
1746 hash: "ab".repeat(32),
1747 bytes_len: 4194304,
1748 };
1749 let v = serde_json::to_value(&res).unwrap();
1750 assert_eq!(v["bytes_len"], 4194304u64);
1751 assert_eq!(serde_json::from_value::<BlobFetchResult>(v).unwrap(), res);
1752 }
1753
1754 /// The three `subscribe` frame shapes round-trip with the documented `type`-tagged wire form
1755 /// (docs/local-protocol.md "Live event stream"): `snapshot` carries the flat session/reachability
1756 /// lists, `event` delegates through the `Box` so the record's fields sit VERBATIM under
1757 /// `record` (one schema with the JSONL log), and `lagged` carries the dropped count.
1758 #[test]
1759 fn stream_frames_roundtrip_with_the_documented_tags() {
1760 let snap = StreamFrame::Snapshot {
1761 active_sessions: vec![ActiveSession {
1762 peer: "bob".into(),
1763 service: "notes".into(),
1764 opened_at: 1_751_760_000,
1765 }],
1766 reachability: vec![PeerReachability {
1767 name: "bob".into(),
1768 reachable: true,
1769 rtt_ms: Some(42),
1770 age_secs: Some(3),
1771 meta: String::new(),
1772 principal: None,
1773 }],
1774 };
1775 let v = serde_json::to_value(&snap).unwrap();
1776 assert_eq!(v["type"], "snapshot");
1777 assert_eq!(v["active_sessions"][0]["peer"], "bob");
1778 assert_eq!(v["active_sessions"][0]["opened_at"], 1_751_760_000i64);
1779 assert_eq!(v["reachability"][0]["name"], "bob");
1780 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), snap);
1781
1782 let event = StreamFrame::Event {
1783 record: Box::new(AuditRecord::session_open(
1784 "2026-07-03T14:02:11.480Z".into(),
1785 Some("bob".into()),
1786 "notes".into(),
1787 )),
1788 };
1789 let v = serde_json::to_value(&event).unwrap();
1790 assert_eq!(v["type"], "event");
1791 // The record's fields ride verbatim under `record` — no Box indirection on the wire.
1792 assert_eq!(v["record"]["kind"], "session_open");
1793 assert_eq!(v["record"]["peer"], "bob");
1794 assert_eq!(v["record"]["service"], "notes");
1795 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), event);
1796
1797 let lagged = StreamFrame::Lagged { dropped: 12 };
1798 let v = serde_json::to_value(&lagged).unwrap();
1799 assert_eq!(v, serde_json::json!({ "type": "lagged", "dropped": 12 }));
1800 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), lagged);
1801 }
1802
1803 /// A frame minted by a NEWER daemon (an unknown `type`) fails to deserialize rather than
1804 /// mis-parsing — the typed stream surface is closed; a forward-compatible consumer reads the
1805 /// raw `Value` stream instead (`ControlClient::open_stream`).
1806 #[test]
1807 fn unknown_stream_frame_type_is_rejected() {
1808 let future = serde_json::json!({ "type": "future_kind", "x": 1 });
1809 assert!(serde_json::from_value::<StreamFrame>(future).is_err());
1810 }
1811
1812 #[test]
1813 fn audit_summary_request_and_result_roundtrip() {
1814 // Request::AuditSummary is parameterless → `{ "method": "audit_summary" }`. Like Status, it
1815 // tolerates omitted/null params; the server dispatches on the method string (method_of).
1816 let r = Request::AuditSummary;
1817 assert_eq!(serde_json::to_value(&r).unwrap()["method"], "audit_summary");
1818 assert_eq!(
1819 method_of(&serde_json::json!({"method": "audit_summary"})),
1820 Some("audit_summary")
1821 );
1822
1823 // AuditSummaryResult carries LOCAL per-peer / per-service session counts (nicknames + service
1824 // names only — never endpoints/transport terms) + a total. Tuples mirror kb's
1825 // InsightResponse.per_peer_contribution: `["bob", 2]` on the wire.
1826 let res = AuditSummaryResult {
1827 per_peer: vec![("alice".into(), 1), ("bob".into(), 2)],
1828 per_service: vec![("kb".into(), 1), ("notes".into(), 3)],
1829 total_sessions: 4,
1830 };
1831 let v = serde_json::to_value(&res).unwrap();
1832 assert_eq!(v["per_peer"][1][0], "bob");
1833 assert_eq!(v["per_peer"][1][1], 2u64);
1834 assert_eq!(v["per_service"][1][0], "notes");
1835 assert_eq!(v["total_sessions"], 4u64);
1836 assert_eq!(
1837 serde_json::from_value::<AuditSummaryResult>(v).unwrap(),
1838 res
1839 );
1840
1841 // Additive-only: a result minted by an older daemon (no `total_sessions` key) still
1842 // deserializes — the `#[serde(default)]` fills it with 0.
1843 let old_shape = serde_json::json!({ "per_peer": [], "per_service": [] });
1844 let back: AuditSummaryResult = serde_json::from_value(old_shape).unwrap();
1845 assert_eq!(back.total_sessions, 0);
1846 assert!(back.per_peer.is_empty());
1847 }
1848}