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