Skip to main content

mcpmesh_local_api/
protocol.rs

1//! mcpmesh-local/1 protocol types (spec §6.1). 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 (D-A).
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 (§6.1): new fields (capabilities on `Hello`, groups/user_id on
12//! `PeerInfo`, device on `OpenSession` — M3+) 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 (spec §6.1 "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, // semver of the API major.minor
21    pub stack_version: String,
22}
23
24/// The kind of backend answering a service — the two valid values, enforced at the
25/// type level and kept in lockstep with `BackendSpec`'s variants. Status reports the
26/// kind only, never the command/path (§17 no transport vocabulary).
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(rename_all = "snake_case")]
29pub enum BackendKind {
30    Run,
31    Socket,
32}
33
34/// A registered service as reported by `status` (no transport vocabulary — §17).
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36pub struct ServiceInfo {
37    pub name: String,
38    pub allow: Vec<String>,   // petnames/groups (flat namespace)
39    pub backend: BackendKind, // "run" | "socket" (kind only, never the command/path)
40}
41
42/// A known peer as reported by `status` (petname only — never the EndpointId, §1.5).
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub struct PeerInfo {
45    pub name: String,
46    pub services: Vec<String>,
47    /// The peer's PROVEN self-sovereign `user_id` (`b64u:<user_pk>`) if it presented a verified
48    /// device->user binding at pairing (roster peers carry it too), else `None` (petname-only). This
49    /// is a §1.5-clean identity (an opaque user id, NOT an EndpointId). Additive (§6.1):
50    /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so older payloads round-trip.
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub user_id: Option<String>,
53}
54
55/// Roster-mode status (spec §4.4). Surface-clean roster VOCABULARY only: org_id, serial, a plain
56/// state word, and the pinned org-root FINGERPRINT in short words — never raw keys/EndpointIds/serials-
57/// as-transport-vocab (§1.5). Absent in a pure-pairing daemon.
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59pub struct RosterStatus {
60    pub org_id: String,
61    pub serial: u64,
62    pub state: String, // "pending" | "approved" | "degraded" | "stopped"
63    pub org_root_fingerprint: String, // short-word form (§4.4)
64}
65
66/// One reachable roster peer device as reported by `status` (spec §10.1 advisory presence read).
67/// ADVISORY — this is a display convenience, never an authorization surface. Surface-clean (§1.5/§17):
68/// FLAT vocabulary ONLY — a `user_id`, a human `device_label`, its `role` word, and an `online`
69/// boolean. It carries NO EndpointId / pubkey / hash / ALPN or any transport vocabulary.
70#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
71pub struct PresencePeer {
72    pub user_id: String,
73    pub device_label: String,
74    pub role: String, // "primary" | "mirror" (roster vocabulary)
75    /// Whether the device has a live presence heartbeat (advisory — absence never blocks a dial).
76    pub online: bool,
77}
78
79/// One recently completed INVITER-side pairing, surfaced by `status` so the inviter's human can
80/// read the short authentication code (SAS) and compare it with the redeemer's out-of-band —
81/// spec §4.2's ceremony is "both humans compare the code": the redeemer sees it in its
82/// [`PairResult`]; this is the inviter's porcelain surface for the same words. DISPLAY-ONLY
83/// ceremony state: held in-memory by the daemon (a small ring), lost on restart, NEVER an
84/// authorization input or trust data. Surface-clean (§1.5): a petname + the SAS wordlist words +
85/// an epoch — never an EndpointId.
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87pub struct RecentPairing {
88    /// The peer's petname as stored by the inviter (its local name for the redeemer).
89    pub peer_petname: String,
90    /// The display-only SAS words (e.g. `"tango-fig-cabbage"`) — the same code the redeemer's
91    /// `PairResult.sas_code` carried. Never checked programmatically.
92    pub sas_code: String,
93    /// When the pairing completed (epoch seconds) — the porcelain renders a friendly age.
94    pub paired_at_epoch: u64,
95}
96
97#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
98pub struct StatusResult {
99    pub stack_version: String,
100    pub services: Vec<ServiceInfo>,
101    pub peers: Vec<PeerInfo>,
102    /// Roster-mode status (§4.4), absent in a pure-pairing daemon. Additive (§6.1):
103    /// `#[serde(default, skip_serializing_if = ...)]` so a daemon/client without it round-trips.
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub roster: Option<RosterStatus>,
106    /// The reachable roster peer devices (spec §10.1 advisory presence read), each with an `online`
107    /// flag. Empty in a pure-pairing daemon / when no roster is installed. Additive (§6.1):
108    /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
109    #[serde(default, skip_serializing_if = "Vec::is_empty")]
110    pub presence: Vec<PresencePeer>,
111    /// THIS daemon's own self-sovereign `user_id` (`b64u:<user_pk>`), if it has a user key (auto-
112    /// minted at boot; shared by pairing AND roster mode). Lets the operator see + share their stable
113    /// identity that multiple devices resolve to. `None` only when no user key exists. Additive (§6.1):
114    /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so an older payload round-trips.
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub self_user_id: Option<String>,
117    /// Recent INVITER-side pairing completions, newest first (display-only §4.2 ceremony aids —
118    /// see [`RecentPairing`]; in-memory on the daemon, cleared by a restart). Empty on a daemon
119    /// that has accepted no pairing since it started. Additive (§6.1):
120    /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
121    #[serde(default, skip_serializing_if = "Vec::is_empty")]
122    pub recent_pairings: Vec<RecentPairing>,
123}
124
125/// Control-API requests. Serialized as `{ "method": "...", "params": {...} }`
126/// (JSON-RPC-shaped; the id/jsonrpc envelope is added by the transport layer).
127///
128/// Clients construct and serialize requests via this enum. **Servers dispatch on the
129/// `method` string and deserialize `params` per-method** — tolerating omitted / null /
130/// empty-object params for parameterless methods — rather than deserializing a whole
131/// message into `Request` (adjacent tagging rejects `params:{}` for unit variants).
132/// This keeps the wire tolerant for third-party clients (§6.1 versioned surface).
133/// Use [`method_of`] to extract the tag, then match + deserialize `params` per-method.
134#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
135#[serde(tag = "method", content = "params", rename_all = "snake_case")]
136pub enum Request {
137    /// Register/update a `[services.*]` entry idempotently (spec §6.1).
138    RegisterService {
139        name: String,
140        backend: BackendSpec,
141        allow: Vec<String>,
142    },
143    Status,
144    /// Mint a one-time pairing invite granting `services` (spec §4.2). The daemon
145    /// answers an [`InviteResult`] carrying the copyable `mcpmesh-invite:` line. Tag
146    /// `"invite"` (snake_case). `method_of` needs no per-variant arm — it reads the
147    /// `method` string generically; the tag comes from `rename_all`.
148    Invite {
149        services: Vec<String>,
150    },
151    /// Redeem a pairing invite (spec §4.2). The daemon dials the inviter named by
152    /// `invite_line` on `mcpmesh/pair/1`, proves the secret, writes the mutual
153    /// (dial-back) [`PeerEntry`], and answers a [`PairResult`]. Tag `"pair"`
154    /// (snake_case); `method_of` reads the `method` string generically.
155    ///
156    /// [`PeerEntry`]: crate — the durable allowlist row lives in the daemon crate.
157    Pair {
158        invite_line: String,
159    },
160    /// Remove a paired peer by petname (spec §4.2, `mcpmesh pair --remove`). The daemon drops the
161    /// peer's [`PeerEntry`] (identity) AND revokes its access by removing the petname from every
162    /// `[services.*].allow` (authorization) — the inverse of the pairing grant. Idempotent: a
163    /// petname with no entry / no allow membership is a clean no-op. Live in-flight sessions are
164    /// NOT severed here (M3/D8): existing sessions run to completion; the peer only loses the
165    /// ability to establish NEW authorized sessions. Tag `"peer_remove"` (snake_case);
166    /// `method_of` reads the `method` string generically (no per-variant arm).
167    ///
168    /// [`PeerEntry`]: crate — the durable allowlist row lives in the daemon crate.
169    PeerRemove {
170        petname: String,
171    },
172    /// Rename a contact's nickname (petname) authoritatively (Contacts rename spec). Renames the
173    /// PERSON — every `PeerEntry` sharing `user_id` when given (one op for all their devices), else the
174    /// single `petname` entry (a provisional, no-`user_id` contact) — to `to`, AND rewrites the old
175    /// petname → `to` in every `[services.*].allow` so grants follow the rename. Refuses (error frame)
176    /// when `to` is empty or already names/grants a DIFFERENT identity — the same collision guard the
177    /// pairing rendezvous uses, so a rename can't inherit another peer's access. Tag `"peer_rename"`;
178    /// host-privileged like the other pair ops.
179    PeerRename {
180        #[serde(default)]
181        user_id: Option<String>,
182        #[serde(default)]
183        petname: Option<String>,
184        to: String,
185    },
186    /// Open a mesh session to `peer/service`; the daemon dials and pipes.
187    /// Distinct from the proxy's job: this returns a session the client streams.
188    /// Spec §6.1's `connect(peer[,device],service)` — renamed to avoid colliding
189    /// with the `connect` porcelain.
190    OpenSession {
191        peer: String,
192        service: String,
193    },
194    /// Install a signed roster from a local file (spec §4.3 manual `internal roster install`).
195    /// `path` is a LOCAL file the same-uid daemon reads (P12/P14 trust boundary — passing a path
196    /// not the bytes is fine). `org_root_pk` pins the org root on FIRST install (`b64u:`); omit it
197    /// once pinned (config carries it). Tag `"roster_install"`.
198    RosterInstall {
199        path: String,
200        #[serde(default, skip_serializing_if = "Option::is_none")]
201        org_root_pk: Option<String>,
202    },
203    /// Pin the org root on a JOINER (spec §4.4 step 2) — WITHOUT a roster (the joiner has none yet,
204    /// D5). Records `[identity]` org_id / org_root_pk / user_id / user_key. `user_key` is a LOCAL path
205    /// (the key never crosses the API). Tag `"org_join"`.
206    OrgJoin {
207        org_id: String,
208        org_root_pk: String,
209        user_id: String,
210        user_key: String,
211    },
212    /// Pin the HTTPS roster URL (`[roster].url`) in config (spec §4.3 M3c). Written by `org create
213    /// --roster-url` (the operator keeps it current) AND by `join` when the org invite carries one —
214    /// so the joiner's poll loop bootstraps its FIRST roster (D5). The daemon writes it under
215    /// `reload_lock` (single-writer), then the poll loop picks it up on the next daemon start. Tag
216    /// `"set_roster_url"`.
217    SetRosterUrl {
218        url: String,
219    },
220    /// Publish a LOCAL file INTO a scope (spec §9, M4a): the daemon adds the bytes to its gated
221    /// app-blob store and records the hash in `scope`. `path` is a local file the same-uid daemon
222    /// reads (P12/P14). Answers a [`BlobPublishResult`] carrying the `mcpmesh/blob/1` ticket + hash.
223    /// Tag `"blob_publish"`.
224    BlobPublish {
225        scope: String,
226        path: String,
227    },
228    /// Grant a scope to a principal — any §5 flat-namespace entry: a group name, a user_id, or a
229    /// petname (the shared `principal_set` expansion). Tag
230    /// `"blob_grant"`.
231    BlobGrant {
232        scope: String,
233        principal: String,
234    },
235    /// List the daemon's blob scopes (name → hashes + grants). Tag `"blob_list"`.
236    BlobList,
237    /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified streaming) and export the
238    /// verified blob to `dest_path` (a local file the same-uid daemon writes). Answers a
239    /// [`BlobFetchResult`] with the verified hash + byte length. Tag `"blob_fetch"`.
240    BlobFetch {
241        ticket: String,
242        dest_path: String,
243    },
244    /// Summarize this node's LOCAL audit log into per-peer / per-service SESSION counts (spec §11.3
245    /// local-only — the daemon reads its OWN audit dir, nothing is transmitted). The host Mesh surface
246    /// renders these as "who serves me / whom I serve / session counts". Parameterless (like `Status`);
247    /// the server dispatches on the `method` string. Tag `"audit_summary"` (snake_case);
248    /// `method_of` reads the `method` string generically (no per-variant arm).
249    AuditSummary,
250}
251
252/// Result of [`Request::OrgJoin`] — the pinned org id echoed back (surface-clean; the fingerprint is
253/// computed porcelain-side from the invite's org_root_pk). Additive-only (§6.1).
254#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
255pub struct OrgJoinResult {
256    pub org_id: String,
257}
258
259/// Result of a [`Request::RosterInstall`] request (spec §4.3 manual path): the installed roster's
260/// org id + serial (roster-status vocabulary the confirmation line is permitted to render) plus how
261/// many live sessions the install severed (D8). Surface-clean: NO keys / EndpointIds / paths.
262///
263/// Additive-only (§6.1): any future field MUST land as
264/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
265#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
266pub struct RosterInstallResult {
267    pub org_id: String,
268    pub serial: u64,
269    /// How many live sessions were severed (D8), for the porcelain's confirmation line.
270    #[serde(default)]
271    pub severed: u32,
272}
273
274/// Result of [`Request::BlobPublish`]: the copyable `mcpmesh/blob/1` ticket + the blob's blake3 hash.
275/// A ticket/hash here is the §9 blob-reference vocabulary (NOT a §1.5 transport-vocab leak — the same
276/// carve-out as the pairing invite line). Additive-only (§6.1).
277#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
278pub struct BlobPublishResult {
279    pub ticket: String,
280    pub hash: String, // bare blake3 hex
281}
282
283/// One scope in a [`BlobScopeList`] (spec §9): its name + the hashes it contains + the principals it
284/// grants. Flat vocabulary ONLY (§1.5) — no EndpointId/pubkey/ALPN. Additive-only (§6.1).
285#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
286pub struct ScopeInfo {
287    pub name: String,
288    pub hashes: Vec<String>,
289    pub grants: Vec<String>,
290}
291
292/// Result of [`Request::BlobList`]: the daemon's scopes. Additive-only (§6.1).
293#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
294pub struct BlobScopeList {
295    pub scopes: Vec<ScopeInfo>,
296}
297
298/// Result of [`Request::BlobFetch`]: the verified hash + byte length written to `dest_path`.
299/// Additive-only (§6.1).
300#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
301pub struct BlobFetchResult {
302    pub hash: String,
303    pub bytes_len: u64,
304}
305
306/// Result of [`Request::AuditSummary`] (spec §11.3): LOCAL per-peer / per-service session counts
307/// aggregated from this node's OWN audit log — NEVER transmitted (§11.3 local-only). Surface-clean
308/// (§1.5): peer names are petnames / user_ids (NEVER EndpointIds), service names are the registered
309/// service names (NEVER transport vocabulary). A "session" is one `SessionOpen` record. `per_peer` /
310/// `per_service` are sorted ascending by name (deterministic). Tuples mirror kb's
311/// `InsightResponse::per_peer_contribution` — `["bob", 2]` on the wire.
312///
313/// Additive-only (§6.1): any future field MUST land as
314/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
315#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
316pub struct AuditSummaryResult {
317    /// Sessions opened per peer (petname). A session with no attributed peer is NOT counted here (no
318    /// peer to attribute) but IS in `total_sessions`.
319    pub per_peer: Vec<(String, u64)>,
320    /// Sessions opened per registered service name.
321    pub per_service: Vec<(String, u64)>,
322    /// Total sessions opened (every `SessionOpen` record, including peer-less ones).
323    #[serde(default)]
324    pub total_sessions: u64,
325}
326
327/// Result of an [`Request::Invite`] request: the copyable `mcpmesh-invite:` artifact
328/// (spec §1.5 surface #2 — the ONE pairing artifact deliberately carved out of the
329/// transport-vocabulary blocklist, so this is NOT a transport-vocab leak) plus its
330/// absolute expiry in epoch seconds (≤ now + 24h).
331///
332/// Additive-only (§6.1): any future field (e.g. the computed SAS, once the inviter side
333/// surfaces it) MUST land as `#[serde(default, skip_serializing_if = ...)]` so older
334/// payloads still deserialize.
335#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
336pub struct InviteResult {
337    /// The `mcpmesh-invite:<base32>` line, copied out-of-band to the redeemer.
338    pub invite_line: String,
339    /// When the invite expires (epoch seconds); the daemon burns it at redemption or expiry.
340    pub expires_at_epoch: u64,
341}
342
343/// Result of a [`Request::Pair`] request: the inviter's suggested petname (the
344/// redeemer's local name for the new peer) plus the display-only short authentication
345/// code (SAS, spec §4.2) — a few words the human reads aloud to a second channel to
346/// catch a whole-invite forgery / address-swap MITM. The SAS is a pairing-ceremony
347/// artifact (like the invite line), NOT a §1.5 transport-vocabulary leak.
348///
349/// Additive-only (§6.1): any future field MUST land as
350/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
351#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
352pub struct PairResult {
353    /// The inviter's suggested petname (from the invite) — the redeemer's local name for it.
354    pub peer_petname: String,
355    /// The display-only short authentication code (e.g. `"tango-fig-42"`), shown on both
356    /// sides for the out-of-band human check. Never sent on the wire, never checked
357    /// programmatically.
358    pub sas_code: String,
359    /// The services this pairing granted the redeemer — each mountable as `<peer>/<service>`.
360    /// Populated from the invite (`invite.services`) by the redeemer-side `redeem_invite`, so
361    /// the porcelain can print the "You can mount: alice/notes" line without re-decoding the
362    /// invite. Additive (§6.1): `#[serde(default, skip_serializing_if = ...)]` so a `PairResult`
363    /// minted by an older daemon (which omits `services`) still deserializes — to an empty list.
364    #[serde(default, skip_serializing_if = "Vec::is_empty")]
365    pub services: Vec<String>,
366}
367
368/// Extract the `method` tag from a raw request value without deserializing the whole
369/// message. Task 3's dispatcher uses this: match on the method string, then deserialize
370/// `params` per-method — which tolerates omitted / null / `{}` params for parameterless
371/// methods (adjacent tagging rejects `params:{}` on unit variants).
372pub fn method_of(v: &serde_json::Value) -> Option<&str> {
373    v.get("method").and_then(serde_json::Value::as_str)
374}
375
376/// How a service is answered (spec §6.2). Mirrors the config `[services.*]` *kinds*;
377/// Config→BackendSpec is a hand-written match (Task 4/9), not a serde passthrough.
378#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
379#[serde(rename_all = "snake_case")]
380pub enum BackendSpec {
381    Run { cmd: Vec<String> },
382    Socket { path: String },
383}
384
385pub const API_NAME: &str = "mcpmesh-local/1";
386pub const API_VERSION: &str = "1.0";
387
388#[cfg(test)]
389mod tests {
390    use super::*;
391
392    #[test]
393    fn hello_result_roundtrips() {
394        let h = Hello {
395            api: "mcpmesh-local/1".into(),
396            api_version: "1.0".into(),
397            stack_version: "0.1.0".into(),
398        };
399        let v = serde_json::to_value(&h).unwrap();
400        assert_eq!(v["api"], "mcpmesh-local/1");
401        let back: Hello = serde_json::from_value(v).unwrap();
402        assert_eq!(back, h);
403    }
404
405    #[test]
406    fn request_tagged_by_method() {
407        let r = Request::Status;
408        assert_eq!(serde_json::to_value(&r).unwrap()["method"], "status");
409        let r = Request::OpenSession {
410            peer: "alice".into(),
411            service: "notes".into(),
412        };
413        let v = serde_json::to_value(&r).unwrap();
414        assert_eq!(v["method"], "open_session");
415        assert_eq!(v["params"]["peer"], "alice");
416    }
417
418    #[test]
419    fn parameterless_method_tolerates_params_forms() {
420        // Omitted and null params deserialize straight into the unit variant.
421        let omitted: Request =
422            serde_json::from_value(serde_json::json!({"method": "status"})).unwrap();
423        assert_eq!(omitted, Request::Status);
424        let null: Request =
425            serde_json::from_value(serde_json::json!({"method": "status", "params": null}))
426                .unwrap();
427        assert_eq!(null, Request::Status);
428
429        // Known limitation: adjacent tagging rejects `params:{}` for a unit variant, so
430        // the server MUST dispatch on the method string rather than deserialize the whole
431        // message into `Request`. This is the pattern the Task 3 dispatcher uses.
432        let empty = serde_json::json!({"method": "status", "params": {}});
433        assert!(serde_json::from_value::<Request>(empty.clone()).is_err());
434        match method_of(&empty) {
435            Some("status") => {} // dispatcher resolves Status via the method string
436            other => panic!("method_of failed to resolve status: {other:?}"),
437        }
438    }
439
440    #[test]
441    fn backend_spec_roundtrips() {
442        let run = BackendSpec::Run {
443            cmd: vec!["notes-mcp".into(), "--stdio".into()],
444        };
445        let v = serde_json::to_value(&run).unwrap();
446        assert_eq!(v["run"]["cmd"][0], "notes-mcp");
447        assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), run);
448
449        let sock = BackendSpec::Socket {
450            path: "/run/notes.sock".into(),
451        };
452        let v = serde_json::to_value(&sock).unwrap();
453        assert_eq!(v["socket"]["path"], "/run/notes.sock");
454        assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), sock);
455    }
456
457    #[test]
458    fn register_service_wire_shape() {
459        let r = Request::RegisterService {
460            name: "notes".into(),
461            backend: BackendSpec::Run {
462                cmd: vec!["notes-mcp".into()],
463            },
464            allow: vec!["alice".into()],
465        };
466        let v = serde_json::to_value(&r).unwrap();
467        assert_eq!(
468            v,
469            serde_json::json!({
470                "method": "register_service",
471                "params": {
472                    "name": "notes",
473                    "backend": {"run": {"cmd": ["notes-mcp"]}},
474                    "allow": ["alice"],
475                }
476            })
477        );
478        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
479    }
480
481    #[test]
482    fn invite_request_and_result_roundtrip() {
483        // Request::Invite → `{ "method": "invite", "params": { "services": [...] } }`.
484        let r = Request::Invite {
485            services: vec!["notes".into(), "kb".into()],
486        };
487        let v = serde_json::to_value(&r).unwrap();
488        assert_eq!(v["method"], "invite");
489        assert_eq!(v["params"]["services"][0], "notes");
490        assert_eq!(v["params"]["services"][1], "kb");
491        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
492        // method_of resolves the tag generically (no per-variant arm).
493        assert_eq!(
494            method_of(&serde_json::json!({"method": "invite", "params": {"services": []}})),
495            Some("invite")
496        );
497
498        // InviteResult carries the copyable line + expiry (surface #2 pairing artifact).
499        let res = InviteResult {
500            invite_line: "mcpmesh-invite:ABCDEF".into(),
501            expires_at_epoch: 1_800_000_000,
502        };
503        let v = serde_json::to_value(&res).unwrap();
504        assert_eq!(v["invite_line"], "mcpmesh-invite:ABCDEF");
505        assert_eq!(v["expires_at_epoch"], 1_800_000_000u64);
506        assert_eq!(serde_json::from_value::<InviteResult>(v).unwrap(), res);
507    }
508
509    #[test]
510    fn pair_request_and_result_roundtrip() {
511        // Request::Pair → `{ "method": "pair", "params": { "invite_line": "..." } }`.
512        let r = Request::Pair {
513            invite_line: "mcpmesh-invite:ABCDEF".into(),
514        };
515        let v = serde_json::to_value(&r).unwrap();
516        assert_eq!(v["method"], "pair");
517        assert_eq!(v["params"]["invite_line"], "mcpmesh-invite:ABCDEF");
518        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
519        // method_of resolves the tag generically (no per-variant arm).
520        assert_eq!(
521            method_of(&serde_json::json!({"method": "pair", "params": {"invite_line": "x"}})),
522            Some("pair")
523        );
524
525        // PairResult carries the inviter's suggested petname + the display-only SAS words +
526        // the granted services (the porcelain renders each as `<peer>/<service>`).
527        let res = PairResult {
528            peer_petname: "alice".into(),
529            sas_code: "tango-fig-cabbage".into(),
530            services: vec!["notes".into(), "kb".into()],
531        };
532        let v = serde_json::to_value(&res).unwrap();
533        assert_eq!(v["peer_petname"], "alice");
534        assert_eq!(v["sas_code"], "tango-fig-cabbage");
535        assert_eq!(v["services"][0], "notes");
536        assert_eq!(v["services"][1], "kb");
537        assert_eq!(serde_json::from_value::<PairResult>(v).unwrap(), res);
538
539        // Additive-only: a PairResult minted by an older daemon (no `services` key) still
540        // deserializes — the `#[serde(default)]` fills it with an empty list.
541        let old_shape = serde_json::json!({
542            "peer_petname": "alice",
543            "sas_code": "tango-fig-cabbage",
544        });
545        let back: PairResult = serde_json::from_value(old_shape).unwrap();
546        assert_eq!(back.peer_petname, "alice");
547        assert!(back.services.is_empty());
548    }
549
550    #[test]
551    fn roster_install_request_and_result_roundtrip() {
552        // Request::RosterInstall → `{ "method": "roster_install", "params": { "path": ...,
553        // "org_root_pk": ... } }`. The optional pk is present on the first-install shape.
554        let r = Request::RosterInstall {
555            path: "/tmp/roster.json".into(),
556            org_root_pk: Some("b64u:AAAA".into()),
557        };
558        let v = serde_json::to_value(&r).unwrap();
559        assert_eq!(v["method"], "roster_install");
560        assert_eq!(v["params"]["path"], "/tmp/roster.json");
561        assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
562        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
563        // method_of resolves the tag generically (no per-variant arm).
564        assert_eq!(
565            method_of(&serde_json::json!({"method": "roster_install", "params": {"path": "/x"}})),
566            Some("roster_install")
567        );
568
569        // When the pk is omitted (a subsequent install using the pinned value), it is
570        // `skip_serializing_if`-dropped from the wire and deserializes back to `None`.
571        let omit = Request::RosterInstall {
572            path: "/tmp/roster.json".into(),
573            org_root_pk: None,
574        };
575        let v = serde_json::to_value(&omit).unwrap();
576        assert!(
577            v["params"].get("org_root_pk").is_none(),
578            "an omitted org_root_pk must not appear on the wire: {v}"
579        );
580        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), omit);
581
582        // RosterInstallResult carries org_id + serial + severed count (roster-status vocabulary).
583        let res = RosterInstallResult {
584            org_id: "acme".into(),
585            serial: 42,
586            severed: 1,
587        };
588        let v = serde_json::to_value(&res).unwrap();
589        assert_eq!(v["org_id"], "acme");
590        assert_eq!(v["serial"], 42u64);
591        assert_eq!(v["severed"], 1u32);
592        assert_eq!(
593            serde_json::from_value::<RosterInstallResult>(v).unwrap(),
594            res
595        );
596
597        // Additive-only: a result minted by an older daemon (no `severed` key) still
598        // deserializes — the `#[serde(default)]` fills it with 0.
599        let old_shape = serde_json::json!({ "org_id": "acme", "serial": 7 });
600        let back: RosterInstallResult = serde_json::from_value(old_shape).unwrap();
601        assert_eq!(back.serial, 7);
602        assert_eq!(back.severed, 0);
603    }
604
605    #[test]
606    fn org_join_request_and_result_roundtrip() {
607        // Request::OrgJoin → `{ "method": "org_join", "params": { org_id, org_root_pk, user_id,
608        // user_key } }`. `user_key` is a LOCAL path string (the key never crosses the API).
609        let r = Request::OrgJoin {
610            org_id: "acme".into(),
611            org_root_pk: "b64u:AAAA".into(),
612            user_id: "alice".into(),
613            user_key: "/home/alice/.config/mcpmesh/user.key".into(),
614        };
615        let v = serde_json::to_value(&r).unwrap();
616        assert_eq!(v["method"], "org_join");
617        assert_eq!(v["params"]["org_id"], "acme");
618        assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
619        assert_eq!(v["params"]["user_id"], "alice");
620        assert_eq!(
621            v["params"]["user_key"],
622            "/home/alice/.config/mcpmesh/user.key"
623        );
624        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
625        // method_of resolves the tag generically (no per-variant arm).
626        assert_eq!(
627            method_of(&serde_json::json!({"method": "org_join", "params": {"org_id": "x"}})),
628            Some("org_join")
629        );
630
631        // OrgJoinResult echoes the pinned org id (surface-clean; the fingerprint is porcelain-side).
632        let res = OrgJoinResult {
633            org_id: "acme".into(),
634        };
635        let v = serde_json::to_value(&res).unwrap();
636        assert_eq!(v["org_id"], "acme");
637        assert_eq!(serde_json::from_value::<OrgJoinResult>(v).unwrap(), res);
638    }
639
640    #[test]
641    fn set_roster_url_request_roundtrip() {
642        // Request::SetRosterUrl → `{ "method": "set_roster_url", "params": { "url": "..." } }`.
643        let r = Request::SetRosterUrl {
644            url: "https://intranet.acme.com/roster.json".into(),
645        };
646        let v = serde_json::to_value(&r).unwrap();
647        assert_eq!(v["method"], "set_roster_url");
648        assert_eq!(v["params"]["url"], "https://intranet.acme.com/roster.json");
649        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
650        assert_eq!(
651            method_of(&serde_json::json!({"method": "set_roster_url", "params": {"url": "x"}})),
652            Some("set_roster_url")
653        );
654    }
655
656    #[test]
657    fn peer_remove_request_roundtrip() {
658        // Request::PeerRemove → `{ "method": "peer_remove", "params": { "petname": "..." } }`.
659        let r = Request::PeerRemove {
660            petname: "bob".into(),
661        };
662        let v = serde_json::to_value(&r).unwrap();
663        assert_eq!(v["method"], "peer_remove");
664        assert_eq!(v["params"]["petname"], "bob");
665        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
666        // method_of resolves the tag generically (no per-variant arm).
667        assert_eq!(
668            method_of(&serde_json::json!({"method": "peer_remove", "params": {"petname": "bob"}})),
669            Some("peer_remove")
670        );
671    }
672
673    #[test]
674    fn peer_rename_request_roundtrip() {
675        // By user_id (renames all of a person's devices in one op).
676        let r = Request::PeerRename {
677            user_id: Some("b64u:BOB".into()),
678            petname: None,
679            to: "Bobby".into(),
680        };
681        let v = serde_json::to_value(&r).unwrap();
682        assert_eq!(v["method"], "peer_rename");
683        assert_eq!(v["params"]["user_id"], "b64u:BOB");
684        assert_eq!(v["params"]["to"], "Bobby");
685        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
686        // A provisional contact is renamed by petname; omitted user_id defaults to None.
687        assert_eq!(
688            method_of(
689                &serde_json::json!({"method": "peer_rename", "params": {"petname": "carol", "to": "Carol"}})
690            ),
691            Some("peer_rename")
692        );
693    }
694
695    #[test]
696    fn status_result_roundtrips() {
697        // Pure-pairing daemon: `roster` is None — absent from the wire (skip_serializing_if) and an
698        // older payload with no `roster` key still deserializes to None (serde default).
699        let s = StatusResult {
700            stack_version: "0.1.0".into(),
701            services: vec![ServiceInfo {
702                name: "notes".into(),
703                allow: vec!["alice".into()],
704                backend: BackendKind::Run,
705            }],
706            peers: vec![PeerInfo {
707                name: "alice".into(),
708                services: vec!["notes".into()],
709                // A paired peer that proved a self-sovereign user_id at pairing (§1.5-clean id).
710                user_id: Some("b64u:alicepk".into()),
711            }],
712            roster: None,
713            presence: vec![],
714            self_user_id: Some("b64u:selfpk".into()),
715            recent_pairings: vec![],
716        };
717        let v = serde_json::to_value(&s).unwrap();
718        assert_eq!(v["services"][0]["backend"], "run");
719        // The additive identity fields ride the wire when present.
720        assert_eq!(v["peers"][0]["user_id"], "b64u:alicepk");
721        assert_eq!(v["self_user_id"], "b64u:selfpk");
722        assert!(
723            v.get("roster").is_none(),
724            "an absent roster must not appear on the wire: {v}"
725        );
726        assert!(
727            v.get("presence").is_none(),
728            "an empty presence must not appear on the wire: {v}"
729        );
730        assert!(
731            v.get("recent_pairings").is_none(),
732            "an empty recent_pairings must not appear on the wire: {v}"
733        );
734        assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
735
736        // A payload minted by an older daemon (no `roster`/`presence`/identity keys) still
737        // deserializes — the identity fields default to None / a petname-only peer.
738        let old_shape = serde_json::json!({
739            "stack_version": "0.1.0",
740            "services": [],
741            "peers": [{ "name": "bob", "services": [] }],
742        });
743        let back: StatusResult = serde_json::from_value(old_shape).unwrap();
744        assert!(back.roster.is_none());
745        assert!(back.presence.is_empty());
746        assert!(back.self_user_id.is_none());
747        assert!(back.peers[0].user_id.is_none());
748        assert!(back.recent_pairings.is_empty());
749
750        // Roster daemon: a Some(RosterStatus) + an advisory presence list round-trip. `presence`
751        // carries FLAT vocabulary only (user_id/device_label/role/online) — no EndpointId/key.
752        let s = StatusResult {
753            stack_version: "0.1.0".into(),
754            services: vec![],
755            peers: vec![],
756            roster: Some(RosterStatus {
757                org_id: "acme".into(),
758                serial: 42,
759                state: "approved".into(),
760                org_root_fingerprint: "tango-fig-cabbage-anchor".into(),
761            }),
762            presence: vec![
763                PresencePeer {
764                    user_id: "alice".into(),
765                    device_label: "laptop".into(),
766                    role: "primary".into(),
767                    online: true,
768                },
769                PresencePeer {
770                    user_id: "alice".into(),
771                    device_label: "desktop".into(),
772                    role: "mirror".into(),
773                    online: false,
774                },
775            ],
776            self_user_id: None,
777            recent_pairings: vec![],
778        };
779        let v = serde_json::to_value(&s).unwrap();
780        assert_eq!(v["roster"]["org_id"], "acme");
781        assert_eq!(v["roster"]["serial"], 42u64);
782        assert_eq!(v["roster"]["state"], "approved");
783        assert_eq!(
784            v["roster"]["org_root_fingerprint"],
785            "tango-fig-cabbage-anchor"
786        );
787        assert_eq!(v["presence"][0]["user_id"], "alice");
788        assert_eq!(v["presence"][0]["device_label"], "laptop");
789        assert_eq!(v["presence"][0]["role"], "primary");
790        assert_eq!(v["presence"][0]["online"], true);
791        assert_eq!(v["presence"][1]["online"], false);
792        assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
793    }
794
795    /// The `recent_pairings` status field is ADDITIVE (§6.1): a populated list round-trips with
796    /// the flat `{peer_petname, sas_code, paired_at_epoch}` shape (petname + SAS words + epoch —
797    /// never an EndpointId), an empty list is dropped from the wire, and a payload minted by an
798    /// older daemon (no key at all) still deserializes to empty.
799    #[test]
800    fn recent_pairings_are_additive_on_status() {
801        let s = StatusResult {
802            stack_version: "0.1.0".into(),
803            services: vec![],
804            peers: vec![],
805            roster: None,
806            presence: vec![],
807            self_user_id: None,
808            recent_pairings: vec![RecentPairing {
809                peer_petname: "bob".into(),
810                sas_code: "tango-fig-cabbage".into(),
811                paired_at_epoch: 1_800_000_000,
812            }],
813        };
814        let v = serde_json::to_value(&s).unwrap();
815        assert_eq!(v["recent_pairings"][0]["peer_petname"], "bob");
816        assert_eq!(v["recent_pairings"][0]["sas_code"], "tango-fig-cabbage");
817        assert_eq!(v["recent_pairings"][0]["paired_at_epoch"], 1_800_000_000u64);
818        assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
819
820        // A payload minted by an OLDER daemon (no `recent_pairings` key) still deserializes —
821        // the `#[serde(default)]` fills it with an empty list.
822        let old_shape = serde_json::json!({
823            "stack_version": "0.1.0",
824            "services": [],
825            "peers": [],
826        });
827        let back: StatusResult = serde_json::from_value(old_shape).unwrap();
828        assert!(back.recent_pairings.is_empty());
829    }
830
831    #[test]
832    fn blob_requests_and_results_roundtrip() {
833        // BlobPublish → { method, params: { scope, path } }.
834        let r = Request::BlobPublish {
835            scope: "docs".into(),
836            path: "/tmp/a.bin".into(),
837        };
838        let v = serde_json::to_value(&r).unwrap();
839        assert_eq!(v["method"], "blob_publish");
840        assert_eq!(v["params"]["scope"], "docs");
841        assert_eq!(v["params"]["path"], "/tmp/a.bin");
842        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
843
844        // BlobGrant → { method, params: { scope, principal } }.
845        let r = Request::BlobGrant {
846            scope: "docs".into(),
847            principal: "alice".into(),
848        };
849        let v = serde_json::to_value(&r).unwrap();
850        assert_eq!(v["method"], "blob_grant");
851        assert_eq!(v["params"]["principal"], "alice");
852        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
853
854        // BlobList is parameterless (method_of resolves it).
855        assert_eq!(
856            method_of(&serde_json::json!({"method": "blob_list"})),
857            Some("blob_list")
858        );
859
860        // BlobFetch → { method, params: { ticket, dest_path } }.
861        let r = Request::BlobFetch {
862            ticket: "blobAAA".into(),
863            dest_path: "/tmp/out.bin".into(),
864        };
865        let v = serde_json::to_value(&r).unwrap();
866        assert_eq!(v["method"], "blob_fetch");
867        assert_eq!(v["params"]["ticket"], "blobAAA");
868        assert_eq!(v["params"]["dest_path"], "/tmp/out.bin");
869        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
870
871        // BlobPublishResult carries the ticket + hash (blob-reference vocabulary, §9).
872        let res = BlobPublishResult {
873            ticket: "blobAAA".into(),
874            hash: "ab".repeat(32),
875        };
876        let v = serde_json::to_value(&res).unwrap();
877        assert_eq!(v["ticket"], "blobAAA");
878        assert_eq!(serde_json::from_value::<BlobPublishResult>(v).unwrap(), res);
879
880        // BlobScopeList carries flat (name, hashes, grants) — no EndpointId/key leakage.
881        let res = BlobScopeList {
882            scopes: vec![ScopeInfo {
883                name: "docs".into(),
884                hashes: vec!["ab".repeat(32)],
885                grants: vec!["alice".into()],
886            }],
887        };
888        let v = serde_json::to_value(&res).unwrap();
889        assert_eq!(v["scopes"][0]["name"], "docs");
890        assert_eq!(v["scopes"][0]["grants"][0], "alice");
891        assert_eq!(serde_json::from_value::<BlobScopeList>(v).unwrap(), res);
892
893        // BlobFetchResult carries the verified hash + byte length.
894        let res = BlobFetchResult {
895            hash: "ab".repeat(32),
896            bytes_len: 4194304,
897        };
898        let v = serde_json::to_value(&res).unwrap();
899        assert_eq!(v["bytes_len"], 4194304u64);
900        assert_eq!(serde_json::from_value::<BlobFetchResult>(v).unwrap(), res);
901    }
902
903    #[test]
904    fn audit_summary_request_and_result_roundtrip() {
905        // Request::AuditSummary is parameterless → `{ "method": "audit_summary" }`. Like Status, it
906        // tolerates omitted/null params; the server dispatches on the method string (method_of).
907        let r = Request::AuditSummary;
908        assert_eq!(serde_json::to_value(&r).unwrap()["method"], "audit_summary");
909        assert_eq!(
910            method_of(&serde_json::json!({"method": "audit_summary"})),
911            Some("audit_summary")
912        );
913
914        // AuditSummaryResult carries LOCAL per-peer / per-service session counts (petnames + service
915        // names only — never endpoints/transport terms) + a total. Tuples mirror kb's
916        // InsightResponse.per_peer_contribution: `["bob", 2]` on the wire.
917        let res = AuditSummaryResult {
918            per_peer: vec![("alice".into(), 1), ("bob".into(), 2)],
919            per_service: vec![("kb".into(), 1), ("notes".into(), 3)],
920            total_sessions: 4,
921        };
922        let v = serde_json::to_value(&res).unwrap();
923        assert_eq!(v["per_peer"][1][0], "bob");
924        assert_eq!(v["per_peer"][1][1], 2u64);
925        assert_eq!(v["per_service"][1][0], "notes");
926        assert_eq!(v["total_sessions"], 4u64);
927        assert_eq!(
928            serde_json::from_value::<AuditSummaryResult>(v).unwrap(),
929            res
930        );
931
932        // Additive-only (§6.1): a result minted by an older daemon (no `total_sessions` key) still
933        // deserializes — the `#[serde(default)]` fills it with 0.
934        let old_shape = serde_json::json!({ "per_peer": [], "per_service": [] });
935        let back: AuditSummaryResult = serde_json::from_value(old_shape).unwrap();
936        assert_eq!(back.total_sessions, 0);
937        assert!(back.per_peer.is_empty());
938    }
939}