mcpmesh_node/node.rs
1//! The supported embedding surface: build ([`NodeBuilder`]) and drive ([`Node`]) a full
2//! in-process mesh node. The node is its OWN mesh identity under its OWN root directory —
3//! it never touches the per-user daemon's state, socket, or singleton lock, so it coexists
4//! freely with a running `mcpmesh` daemon (and with other embedded nodes under other roots).
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7
8use mcpmesh_local_api::client::ClientError;
9use mcpmesh_local_api::{ControlClient, connect_control_io};
10
11use crate::config::Config;
12use crate::control::serve_control_io;
13use crate::daemon::boot::{BootOverrides, BootedNode, start_node};
14use crate::paths::NodePaths;
15
16/// Everything that can refuse a [`NodeBuilder::start`]. Embedders branch on
17/// [`DataDirInUse`](StartError::DataDirInUse) (another node owns this root — one node per
18/// root, enforced by redb's exclusive database lock) and [`Config`](StartError::Config)
19/// (a malformed `config.toml` / programmatic config, worth showing to a human); everything
20/// else is opaque infrastructure failure.
21#[derive(Debug, thiserror::Error)]
22pub enum StartError {
23 #[error("config error: {0:#}")]
24 Config(#[source] anyhow::Error),
25 #[error("data dir already in use by another node: {path}")]
26 DataDirInUse { path: PathBuf },
27 #[error(transparent)]
28 Other(anyhow::Error),
29}
30
31impl StartError {
32 /// Classify a boot error by its CHAIN (the boot body stays plain-`anyhow`, so inner
33 /// `?` sites never re-wrap): a `redb` open refusal on the peer store → `DataDirInUse`
34 /// (its exact variant differs by platform/lock path, so any database-open error on the
35 /// store path counts); a `figment` error anywhere → `Config`; else `Other`.
36 pub(crate) fn classify(e: anyhow::Error, _config_path: &Path, db_path: &Path) -> StartError {
37 if e.chain()
38 .any(|c| c.downcast_ref::<redb::DatabaseError>().is_some())
39 {
40 return StartError::DataDirInUse {
41 path: db_path.to_path_buf(),
42 };
43 }
44 if e.chain()
45 .any(|c| c.downcast_ref::<figment::Error>().is_some())
46 {
47 return StartError::Config(e);
48 }
49 StartError::Other(e)
50 }
51}
52
53/// Build a [`Node`]: pick a root directory, optionally inject a [`Config`], then
54/// [`start`](NodeBuilder::start).
55pub struct NodeBuilder {
56 root: PathBuf,
57 config: Option<Config>,
58 identity_conflict: Option<std::sync::Arc<crate::diag::IdentityConflict>>,
59 overrides: BootOverrides,
60}
61
62impl NodeBuilder {
63 /// A node rooted at `root` — the ONE directory holding its whole world (`config/`,
64 /// `data/`, `state/`; layout-identical to a `mcpmesh --profile <root>` profile dir).
65 /// Missing pieces are created on start: the first start mints the device key, and an
66 /// absent `config/config.toml` boots the spec defaults.
67 pub fn new(root: impl Into<PathBuf>) -> Self {
68 Self {
69 root: root.into(),
70 config: None,
71 identity_conflict: None,
72 overrides: BootOverrides::default(),
73 }
74 }
75
76 /// Use this configuration instead of reading `<root>/config/config.toml`. The type IS
77 /// the config-file vocabulary (`docs/config.md`) — one schema, two front doors.
78 /// Config-persisting control verbs (a non-ephemeral `register_service`, pairing
79 /// grants) still write `<root>/config/config.toml`.
80 pub fn config(mut self, config: Config) -> Self {
81 self.config = Some(config);
82 self
83 }
84
85 /// Share the duplicate-identity observation with the host's `tracing` subscriber (#134).
86 ///
87 /// Two nodes booted from COPIES of one mesh root present the same endpoint id; the relay can
88 /// serve only one, and the displaced node's peers go unreachable with nothing saying why. iroh
89 /// 1.0.3 exposes that report **only as a log event**, so detecting it needs a layer in the
90 /// process's subscriber — and an embedded node cannot install one, because the subscriber is
91 /// global and your application owns it.
92 ///
93 /// Pass the SAME `Arc` you gave [`IdentityConflictLayer`](crate::diag::IdentityConflictLayer),
94 /// so that what the layer records is what this node's `status` reports:
95 ///
96 /// ```ignore
97 /// use std::sync::Arc;
98 /// use tracing_subscriber::prelude::*;
99 /// use mcpmesh_node::diag::{IdentityConflict, IdentityConflictLayer};
100 ///
101 /// let conflict = Arc::new(IdentityConflict::default());
102 /// tracing_subscriber::registry()
103 /// .with(my_fmt_layer)
104 /// .with(IdentityConflictLayer::new(conflict.clone()))
105 /// .init();
106 ///
107 /// let node = NodeBuilder::new(root).identity_conflict(conflict).start().await?;
108 /// ```
109 ///
110 /// Without it, `status.self_network.identity_conflict_epoch` is always absent — which means
111 /// "not observable here", NOT "this identity is unique". Nothing else changes: the node boots,
112 /// serves, and behaves identically either way.
113 pub fn identity_conflict(
114 mut self,
115 shared: std::sync::Arc<crate::diag::IdentityConflict>,
116 ) -> Self {
117 self.identity_conflict = Some(shared);
118 self
119 }
120
121 /// Run as `key` instead of reading (or minting) `<root>/config/device.key` (#85).
122 ///
123 /// **What this is for.** The default posture is 32 raw ed25519 secret bytes at 0600, in a
124 /// directory the node owns — no passphrase, no keychain, no hardware seam. An embedder could
125 /// not fix that from outside: the file is inside the mesh root it is told not to hand-write,
126 /// and there was no way to supply a decrypted key at boot. This is that way — unwrap the key
127 /// from wherever your platform keeps secrets and hand it over.
128 ///
129 /// **When set, no DEVICE key file is read, minted, or written.** So that secret never lands on
130 /// disk. (The node still mints `<root>/config/user.key` — the pairing-identity key — which this
131 /// seam does not cover; #85 asks 2-3 are about that one and are not shipped.) The on-disk key
132 /// never exists to be
133 /// stolen — and a node whose embedder holds the key cannot silently fall back to a file one,
134 /// which would boot happily under a DIFFERENT identity and leave every peer unable to reach it.
135 ///
136 /// **Custody moves to you.** mcpmesh cannot recover this identity if you lose the key: there is
137 /// no escrow and no recovery path (#85 asks 2-3, not shipped). It is also the identity every
138 /// peer pinned at pairing, so replacing it makes this node a stranger to all of them.
139 ///
140 /// The key must stay STABLE across restarts of the same node — passing a fresh one each boot
141 /// mints a new identity every time.
142 pub fn device_key(mut self, key: mcpmesh_trust::ed25519_dalek::SigningKey) -> Self {
143 self.overrides.device_key = Some(key);
144 self
145 }
146
147 /// Boot the node: identity, stores, gates, the iroh endpoint, and every serving loop
148 /// the daemon runs. Requires a multi-thread tokio runtime (the node spawns its serving
149 /// loops onto the ambient runtime). Installs a process-default rustls `CryptoProvider`
150 /// (ring) if the host application has not installed one — idempotent, the host's wins.
151 pub async fn start(self) -> Result<Node, StartError> {
152 let paths = NodePaths::under_root(&self.root);
153 let booted = start_node(paths, self.config, self.overrides).await?;
154 // #134: adopt the host's shared observation, so the layer IN THEIR subscriber and this
155 // node's `status` read the same cell. Set after boot rather than threaded through it —
156 // the field is only ever read by the status projection, never during construction.
157 if let (Some(shared), Some(mesh)) = (self.identity_conflict, booted.state.mesh()) {
158 mesh.adopt_identity_conflict(shared);
159 }
160 Ok(Node { booted })
161 }
162}
163
164/// A running in-process node. Dropping it does NOT stop serving — call
165/// [`shutdown`](Node::shutdown).
166pub struct Node {
167 booted: BootedNode,
168}
169
170/// Hand-rolled: the boot internals are not `Debug`; the identity is the one diagnostic
171/// a `{:?}` needs.
172impl std::fmt::Debug for Node {
173 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174 f.debug_struct("Node")
175 .field("endpoint_id", &self.endpoint_id())
176 .finish_non_exhaustive()
177 }
178}
179
180impl Node {
181 /// A control connection to THIS node: the same typed `mcpmesh-local/1` client a
182 /// sidecar consumer gets from `connect_control_default`, over an in-memory pipe.
183 /// Cheap; open one per concurrent conversation — a session/stream upgrade
184 /// (`open_session`, `subscribe`) consumes its connection, exactly as on the socket.
185 pub async fn control(&self) -> Result<ControlClient, ClientError> {
186 let (client_io, server_io) = tokio::io::duplex(64 * 1024);
187 let (server_read, server_write) = tokio::io::split(server_io);
188 let state = self.booted.state.clone();
189 let track_state = state.clone();
190 let handle = tokio::spawn(async move {
191 if let Err(e) = serve_control_io(server_read, server_write, state).await {
192 tracing::debug!(%e, "in-process control connection ended");
193 }
194 });
195 // Tracked like a socket connection's serving task (`serve_control`'s per-connection
196 // spawn): without this, an attached `subscribe()` stream never notices `shutdown` (see
197 // `Node::shutdown`) and outlives the node, holding its `Arc<DaemonState>`/mesh/redb lock
198 // open.
199 track_state.track_control_task(handle);
200 let (client_read, client_write) = tokio::io::split(client_io);
201 connect_control_io(client_read, client_write).await
202 }
203
204 /// This node's mesh identity — what a peer's invite/pair flow binds to.
205 pub fn endpoint_id(&self) -> iroh::EndpointId {
206 self.mesh().endpoint.id()
207 }
208
209 /// Serve a custom protocol on `alpn`, through this node's existing trust gate (#67).
210 ///
211 /// **What this is for.** mcpmesh has already built the hard parts of a P2P application
212 /// platform — identity, pairing, a trust gate, relay fallback, discovery, rate limiting, a
213 /// connection registry — and exposes one protocol shape on top: request/response MCP over
214 /// bi-streams. Anything that does not fit (realtime media wanting datagrams, efficient bulk
215 /// transfer, an app-level overlay) was out of reach however well the identity layer suited it.
216 /// The alternative was a SECOND endpoint with a second identity, which discards the gate, the
217 /// pairing relationship and the relay config — and makes your users pair twice.
218 ///
219 /// **Your handler runs behind the same gate as every built-in protocol.** An unauthorized or
220 /// revoked peer is closed before `accept` is called; the connection is entered in the registry,
221 /// so revoking that peer SEVERS it mid-protocol rather than waiting for it to end. You get the
222 /// authenticated `EndpointId` from `connection.remote_id()`, and it is the same identity
223 /// `_meta["mcpmesh/peer"]` names on the MCP path.
224 ///
225 /// ```no_run
226 /// use std::sync::Arc;
227 /// use mcpmesh_node::iroh;
228 ///
229 /// #[derive(Debug)]
230 /// struct MyProto;
231 ///
232 /// impl iroh::protocol::ProtocolHandler for MyProto {
233 /// async fn accept(
234 /// &self,
235 /// conn: iroh::endpoint::Connection,
236 /// ) -> Result<(), iroh::protocol::AcceptError> {
237 /// let _peer = conn.remote_id(); // the AUTHENTICATED caller
238 /// Ok(())
239 /// }
240 /// }
241 ///
242 /// # fn f(node: &mcpmesh_node::Node) -> anyhow::Result<()> {
243 /// node.accept_protocol(b"app/myproto/1", Arc::new(MyProto))?;
244 /// # Ok(()) }
245 /// ```
246 ///
247 /// **The `mcpmesh/` prefix is reserved** and registering under it is an error — the accept loop
248 /// dispatches its own protocols by exact ALPN before consulting this registry, so a handler
249 /// there would be silently dead, and one on a name mcpmesh adds later would flip from working
250 /// to dead on an upgrade. `app/…` is the suggested convention.
251 ///
252 /// **Takes effect for connections negotiated from now on.** ALPN is chosen at handshake, so a
253 /// peer already connected cannot use the new protocol. Register during startup, before you
254 /// announce the node as ready, unless that is genuinely what you want.
255 ///
256 /// Registering the same `alpn` twice replaces the handler; connections already running under
257 /// the old one continue on it.
258 pub fn accept_protocol(
259 &self,
260 alpn: &[u8],
261 handler: Arc<dyn iroh::protocol::DynProtocolHandler>,
262 ) -> anyhow::Result<()> {
263 self.mesh().register_app_protocol(alpn, handler)
264 }
265
266 /// This node's currently-dialable address (#67) — its endpoint id plus whatever direct
267 /// addresses and relay it has, exactly what a pairing invite embeds.
268 ///
269 /// For handing an address to a peer OUT-OF-BAND, when your application has its own channel for
270 /// that and does not want a pairing invite. Carries transport vocabulary by nature, which is
271 /// why it is a typed accessor rather than anything on the control surface.
272 ///
273 /// A snapshot: addresses change as the network does, and immediately after boot it may hold
274 /// only local ones. It authorizes nothing — a peer dialling this still faces the trust gate.
275 pub fn endpoint_addr(&self) -> iroh::EndpointAddr {
276 self.mesh().endpoint.addr()
277 }
278
279 /// Dial `peer` on a custom `alpn` — the client half of [`accept_protocol`](Self::accept_protocol)
280 /// (#67).
281 ///
282 /// `peer` may be a paired nickname, a `b64u:` user_id, an `eid:` device principal, or — in
283 /// roster mode — a rostered user_id. That resolution, plus the stored dial-address hint and
284 /// this node's relay configuration, is most of what makes this worth using over a raw endpoint:
285 /// an embedder holding only "alice" has no way to turn that into an address, and one that stood
286 /// up its own endpoint would not have the pairing that produced it.
287 ///
288 /// For a person with several devices the candidates are tried IN ORDER — roster candidates
289 /// first, primary before mirror — and the first that connects wins. That is weaker than
290 /// `open_session`'s staggered race, which this deliberately does not reproduce: racing means
291 /// opening connections you then abandon, and an embedder's protocol may not be safe to
292 /// half-open. Each attempt is bounded by the same `DIAL_TIMEOUT` the service dial uses, so an
293 /// unreachable first device costs that timeout rather than hanging.
294 ///
295 /// ```no_run
296 /// # async fn f(node: &mcpmesh_node::Node) -> anyhow::Result<()> {
297 /// let conn = node.connect_protocol("alice", b"app/myproto/1").await?;
298 /// let (send, recv) = conn.open_bi().await?;
299 /// # Ok(()) }
300 /// ```
301 ///
302 ///
303 /// **This does not authorize anything.** It dials; the REMOTE side's gate decides whether to
304 /// admit you, and will close the connection if you are not paired with them. Symmetrically,
305 /// your own handler is protected by your gate — see `accept_protocol`.
306 ///
307 /// Errors when `peer` resolves to nobody, or when the dial fails. A peer that is simply offline
308 /// is a dial failure, not a distinct condition.
309 pub async fn connect_protocol(
310 &self,
311 peer: &str,
312 alpn: &[u8],
313 ) -> anyhow::Result<iroh::endpoint::Connection> {
314 let mesh = self.mesh();
315 let candidates = crate::daemon::dial::protocol_candidates(mesh, peer).await?;
316 anyhow::ensure!(
317 !candidates.is_empty(),
318 "no peer '{peer}' — 'status' lists your peers and roster members"
319 );
320 let mut last: Option<anyhow::Error> = None;
321 for endpoint_id in candidates {
322 let Ok(id) = iroh::EndpointId::from_bytes(&endpoint_id) else {
323 continue; // a corrupt stored id is skipped, not fatal — another device may work
324 };
325 // The stored last-addr hint, attached exactly as the service dial attaches it. It is
326 // what lets a hermetic/localhost mesh with no discovery reach a peer it has never
327 // dialled, and a hint recorded for a DIFFERENT id is discarded rather than dialled.
328 let store = mesh.store.clone();
329 let entry = crate::util::blocking("join connect_protocol store read", move || {
330 store.resolve(&endpoint_id)
331 })
332 .await??;
333 let addr = crate::daemon::dial::stored_dial_addr(
334 entry.and_then(|e| e.last_addr).as_deref(),
335 id,
336 );
337 // Bounded, like every other dial in the codebase: an unreachable candidate must cost a
338 // timeout, not the caller's future.
339 match tokio::time::timeout(
340 crate::daemon::dial::DIAL_TIMEOUT,
341 mesh.endpoint.connect(addr, alpn),
342 )
343 .await
344 {
345 Ok(Ok(conn)) => return Ok(conn),
346 Ok(Err(e)) => last = Some(anyhow::Error::new(e)),
347 Err(_) => last = Some(anyhow::anyhow!("dial timed out")),
348 }
349 }
350 Err(match last {
351 Some(e) => e.context(format!("dial '{peer}' on a custom protocol")),
352 None => anyhow::anyhow!("dial '{peer}' on a custom protocol: no usable candidate"),
353 })
354 }
355
356 /// Sign an application payload with this node's DEVICE key, under the embedder's own
357 /// `domain` (#59).
358 ///
359 /// **What this is for.** mcpmesh authenticates the transport: inside a session,
360 /// `_meta["mcpmesh/peer"]` says who is calling. That answers nothing about a payload which
361 /// outlives its connection — anything store-and-forward (offline delivery, a relay, a mailbox,
362 /// an app-level overlay) handles bytes whose author is not the peer that delivered them, and
363 /// the transport authenticated the FORWARDER. This attributes the ORIGIN, against the same
364 /// identity the transport already proves, so an embedder needs no second key, no second
365 /// backup/revocation story, and no binding protocol tying the two together.
366 ///
367 /// **`domain` is yours; pick one per statement KIND** (`b"chat/message/1"`,
368 /// `b"mailbox/receipt/1"`). A signature is only as narrow as its domain, and sharing one across
369 /// two shapes lets a value from either be read as the other. mcpmesh's own domains are out of
370 /// reach whatever you choose — see [`mcpmesh_trust::app`] for why that is a property of the
371 /// preimage rather than of your discipline.
372 ///
373 /// Verify with [`verify_app`](Self::verify_app), which needs no node.
374 ///
375 /// **Not a control verb, deliberately.** Signing over the JSON-RPC socket would put the device
376 /// key's authority behind an IPC surface shared by every consumer of that socket. This is an
377 /// in-process seam for the embedder that owns the node.
378 pub fn sign_app(&self, domain: &[u8], msg: &[u8]) -> [u8; 64] {
379 // Derived from the endpoint rather than held as a field: the signing key is then the one
380 // whose public half IS `endpoint_id()`, by construction. A separately-stored copy could be
381 // absent or stale, and a signing API that fails open or signs under the wrong identity is
382 // worse than none.
383 //
384 // Hardening note, the same residual `DeviceKey::secret_bytes` documents: `to_bytes()` hands
385 // back a plain `[u8; 32]` that is not zeroized, and the `SigningKey` built from it is
386 // scrubbed on drop but the array is not. Per call rather than once — accepted, because the
387 // alternative is caching the key material for the node's whole life, which is a larger
388 // residual, not a smaller one.
389 let signing = mcpmesh_trust::ed25519_dalek::SigningKey::from_bytes(
390 &self.mesh().endpoint.secret_key().to_bytes(),
391 );
392 mcpmesh_trust::sign_app(&signing, domain, msg)
393 }
394
395 /// Verify an application payload signed by `endpoint_id` under `domain` (#59).
396 ///
397 /// An associated function: verification needs no node, which is the point — a consumer checking
398 /// a relayed payload has the peer's `EndpointId` and nothing else.
399 ///
400 /// Returns `false` for a bad signature, a mismatched domain/message, or malformed bytes. It
401 /// never panics: every input is attacker-supplied by construction.
402 ///
403 /// It answers "which device produced these bytes" and nothing else. Whether that device was
404 /// ENTITLED to make the statement is the embedder's authorization question, answered from the
405 /// embedder's own state.
406 pub fn verify_app(
407 endpoint_id: &iroh::EndpointId,
408 domain: &[u8],
409 msg: &[u8],
410 sig: &[u8; 64],
411 ) -> bool {
412 mcpmesh_trust::verify_app(endpoint_id.as_bytes(), domain, msg, sig)
413 }
414
415 /// Resolves once shutdown has been requested — by [`shutdown`](Node::shutdown) from
416 /// another handle, or by the control protocol's `shutdown` verb (e.g. an operator
417 /// driving this node's control connection).
418 pub async fn wait(&self) {
419 self.booted.state.shutdown_requested().await;
420 }
421
422 /// Stop serving: raise the shutdown signal, stop the accept/poll/background loops and
423 /// every live control connection (subscription streams end immediately; in-flight control
424 /// requests get a dropped connection — acceptable, shutdown means shutdown), and close the
425 /// endpoint (a graceful QUIC close — live sessions end cleanly).
426 pub async fn shutdown(self) {
427 // One teardown path, shared with the boot tests (#105) so neither can drift from the other.
428 crate::daemon::boot::shutdown_booted(self.booted).await;
429 }
430
431 fn mesh(&self) -> &Arc<crate::daemon::MeshState> {
432 self.booted
433 .state
434 .mesh()
435 .expect("a started Node always owns a mesh")
436 }
437}