switchboard-relay 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ """switchboard: a local MCP server for inter-session messaging in Claude Code."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ from switchboard.store import Message, Participant, Store, default_db_path
6
+
7
+ try:
8
+ __version__ = version("switchboard-relay")
9
+ except PackageNotFoundError: # pragma: no cover - running from a source tree, not installed
10
+ __version__ = "0+unknown"
11
+
12
+ __all__ = ["Message", "Participant", "Store", "__version__", "default_db_path"]
switchboard/server.py ADDED
@@ -0,0 +1,640 @@
1
+ """FastMCP server exposing the switchboard tools.
2
+
3
+ Two ways to run the same server:
4
+
5
+ * **stdio (default)** -- ``switchboard``. Every Claude Code session spawns its
6
+ own stdio process; durability and cross-session delivery come from a shared
7
+ SQLite database. ``wait()`` long-polls that database. This is the v1 default
8
+ and satisfies all of switchboard's core goals. It cannot *push* -- a session's
9
+ process has no handle to another session's process -- so recipients poll.
10
+
11
+ * **HTTP daemon (opt-in)** -- ``switchboard serve``. One process holds every
12
+ session's connection, so ``send()`` can additionally emit a Channels
13
+ notification (``notifications/claude/channel``) straight into a connected
14
+ recipient. This is the experimental push path; see the README.
15
+
16
+ Identity is bound per MCP connection: ``register(name, role)`` associates the
17
+ calling session with an address, and subsequent ``inbox()``/``wait()``/``send()``
18
+ calls resolve "who am I" from that connection. In stdio there is exactly one
19
+ connection per process; in the daemon there are many, keyed by the live
20
+ ``ServerSession`` object.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import argparse
26
+ import os
27
+ import sys
28
+ import time
29
+ from dataclasses import dataclass
30
+ from pathlib import Path
31
+ from typing import Any, Optional
32
+
33
+ import anyio
34
+ from mcp.server.fastmcp import Context, FastMCP
35
+
36
+ from switchboard.store import DEFAULT_TTL_SECONDS, Store, default_db_path
37
+
38
+ # How often wait() checks the mailbox, and how often it heartbeats the caller's
39
+ # liveness while parked. Poll is a balance between latency and DB churn.
40
+ _WAIT_POLL_SECONDS = 0.25
41
+ _WAIT_HEARTBEAT_SECONDS = 10.0
42
+
43
+ _CHANNEL_METHOD = "notifications/claude/channel"
44
+
45
+
46
+ def _now() -> float:
47
+ return time.time()
48
+
49
+
50
+ def _resolve_ttl() -> float:
51
+ raw = os.environ.get("SWITCHBOARD_TTL")
52
+ if not raw:
53
+ return DEFAULT_TTL_SECONDS
54
+ try:
55
+ val = float(raw)
56
+ return val if val > 0 else DEFAULT_TTL_SECONDS
57
+ except ValueError:
58
+ return DEFAULT_TTL_SECONDS
59
+
60
+
61
+ def _clamp_timeout(value: Any, *, default: float = 30.0, cap: float = 3600.0) -> float:
62
+ """Coerce a caller-supplied timeout to a sane [0, cap] range."""
63
+ try:
64
+ v = float(value)
65
+ except (TypeError, ValueError):
66
+ v = default
67
+ return max(0.0, min(v, cap))
68
+
69
+
70
+ @dataclass
71
+ class _Conn:
72
+ """One connected participant: an address bound to a live MCP session."""
73
+
74
+ name: str
75
+ role: str
76
+ session: Any # mcp.server.session.ServerSession
77
+
78
+
79
+ class Switchboard:
80
+ """Wires the durable :class:`~switchboard.store.Store` to MCP tools.
81
+
82
+ Holds the in-process connection registry used for identity resolution and
83
+ (in daemon mode) for pushing notifications to connected recipients. The
84
+ durable state lives entirely in the store; this registry is soft state that
85
+ is rebuilt as sessions register.
86
+ """
87
+
88
+ def __init__(self, store: Store, *, ttl: float = DEFAULT_TTL_SECONDS):
89
+ self.store = store
90
+ self.ttl = ttl
91
+ # id(ctx.session) -> _Conn. Keyed by object identity because one
92
+ # ServerSession maps to exactly one client connection for its lifetime.
93
+ self._conns: dict[int, _Conn] = {}
94
+ # Optional identity seeded from the environment so scripted worker
95
+ # sessions can be launched pre-addressed (SWITCHBOARD_NAME/ROLE) without
96
+ # an explicit register() call.
97
+ self._default_name = (os.environ.get("SWITCHBOARD_NAME") or "").strip()
98
+ self._default_role = (os.environ.get("SWITCHBOARD_ROLE") or "").strip()
99
+ # Push is opt-in. It only does anything in daemon mode (a recipient
100
+ # connected to the same process) AND only makes sense when recipients
101
+ # are Claude sessions subscribed as a channel -- a stock MCP client
102
+ # rejects the custom notification method. Off by default keeps the
103
+ # common path pure durable-poll with no surprises.
104
+ self._push_enabled = (os.environ.get("SWITCHBOARD_PUSH") or "").strip().lower() in (
105
+ "1",
106
+ "true",
107
+ "yes",
108
+ "on",
109
+ )
110
+
111
+ # -- identity -----------------------------------------------------------
112
+
113
+ def _bind(self, ctx: Context, name: str, role: str) -> _Conn:
114
+ conn = _Conn(name=name, role=role, session=ctx.session)
115
+ self._conns[id(ctx.session)] = conn
116
+ return conn
117
+
118
+ def _resolve(self, ctx: Context) -> _Conn:
119
+ """Return the caller's bound identity, or raise a helpful error."""
120
+ conn = self._conns.get(id(ctx.session))
121
+ if conn is not None:
122
+ return conn
123
+ if self._default_name:
124
+ # Lazily register the environment-seeded identity for this session.
125
+ self.store.register(self._default_name, self._default_role, now=_now())
126
+ return self._bind(ctx, self._default_name, self._default_role)
127
+ raise ValueError(
128
+ 'This session is not registered. Call register(name="...", '
129
+ 'role="...") first so switchboard knows which mailbox is yours '
130
+ "(or launch with $SWITCHBOARD_NAME set)."
131
+ )
132
+
133
+ # -- push (daemon mode) -------------------------------------------------
134
+
135
+ def _push_targets(self, address: str, *, exclude_session_id: int) -> list[_Conn]:
136
+ return [
137
+ c
138
+ for sid, c in self._conns.items()
139
+ if sid != exclude_session_id and (c.name == address or (c.role and c.role == address))
140
+ ]
141
+
142
+ async def _push(self, conn: _Conn, *, content: str, meta: dict[str, str]) -> bool:
143
+ """Best-effort Channels notification to a connected recipient.
144
+
145
+ Returns True if the notification was handed to the transport. Never
146
+ raises: push is an optimization layered on top of durable delivery, so
147
+ any failure (old SDK, closed stream, recipient not a channel) simply
148
+ falls back to the recipient polling inbox()/wait().
149
+ """
150
+ try:
151
+ import mcp.types as types
152
+ from pydantic import BaseModel, ConfigDict
153
+
154
+ class _ChannelParams(BaseModel):
155
+ model_config = ConfigDict(extra="allow")
156
+
157
+ notification = types.Notification[_ChannelParams, str](
158
+ method=_CHANNEL_METHOD,
159
+ params=_ChannelParams.model_validate({"content": content, "meta": meta}),
160
+ )
161
+ # related_request_id is intentionally omitted: this notification
162
+ # targets a *different* session than the current request, so it must
163
+ # ride the recipient's standalone stream, not our request's stream.
164
+ await conn.session.send_notification(notification) # type: ignore[arg-type]
165
+ return True
166
+ except Exception:
167
+ return False
168
+
169
+ # -- tool implementations ----------------------------------------------
170
+
171
+ def register(self, ctx: Context, name: str, role: str = "") -> dict:
172
+ name = (name or "").strip()
173
+ if not name:
174
+ raise ValueError('name must be a non-empty string, e.g. "lead" or "worker:feature-x".')
175
+ role = (role or "").strip()
176
+ p = self.store.register(name, role, now=_now())
177
+ self._bind(ctx, p.name, p.role)
178
+ return {
179
+ "ok": True,
180
+ "you": p.name,
181
+ "role": p.role,
182
+ "ttl_seconds": self.ttl,
183
+ "participants": self._participants_payload(),
184
+ }
185
+
186
+ def participants(self, ctx: Context) -> dict:
187
+ # A read is also a heartbeat for the caller, if registered.
188
+ conn = self._conns.get(id(ctx.session))
189
+ if conn is not None:
190
+ self.store.touch(conn.name, now=_now())
191
+ payload = self._participants_payload()
192
+ return {"participants": payload, "count": len(payload)}
193
+
194
+ def send(self, ctx: Context, to: str, body: str, reply_to: Optional[int] = None) -> dict:
195
+ conn = self._resolve(ctx)
196
+ to = (to or "").strip()
197
+ if not to:
198
+ raise ValueError("`to` must be a non-empty address (a participant name or role).")
199
+ now = _now()
200
+ mid = self.store.send(to, body, sender=conn.name, reply_to=reply_to, now=now)
201
+ self.store.touch(conn.name, now=now)
202
+ return {"id": mid, "to": to, "from": conn.name, "reply_to": reply_to}
203
+
204
+ async def _notify(
205
+ self, ctx: Context, *, sender: str, to: str, mid: int, reply_to: Optional[int]
206
+ ) -> bool:
207
+ """Best-effort push nudge to any connected recipient(s) of ``to``.
208
+
209
+ Returns True if at least one live delivery was made. This is a *nudge*,
210
+ not the message itself: the durable inbox row is the single source of
211
+ truth. Deliberately omitting the body keeps push consistent with
212
+ drain-once semantics -- when a role is addressed every connected member
213
+ is nudged but only the one that drains the row receives it; the others
214
+ just find an empty inbox, which is harmless. Embedding the body here
215
+ would let multiple role members act on a message only one of them owns.
216
+ No-op unless push is enabled (daemon mode).
217
+ """
218
+ if not self._push_enabled:
219
+ return False
220
+ targets = self._push_targets(to, exclude_session_id=id(ctx.session))
221
+ if not targets:
222
+ return False
223
+ content = (
224
+ f"New switchboard message from {sender} (id {mid}). "
225
+ f"Call inbox() (or wait()) to read it."
226
+ )
227
+ meta = {
228
+ "source": "switchboard",
229
+ "msg_from": str(sender),
230
+ "msg_to": str(to),
231
+ "msg_id": str(mid),
232
+ }
233
+ if reply_to is not None:
234
+ meta["reply_to"] = str(reply_to)
235
+ delivered = False
236
+ for t in targets:
237
+ if await self._push(t, content=content, meta=meta):
238
+ delivered = True
239
+ return delivered
240
+
241
+ async def send_async(
242
+ self, ctx: Context, to: str, body: str, reply_to: Optional[int] = None
243
+ ) -> dict:
244
+ result = self.send(ctx, to, body, reply_to)
245
+ result["delivered_live"] = await self._notify(
246
+ ctx, sender=result["from"], to=result["to"], mid=result["id"], reply_to=reply_to
247
+ )
248
+ return result
249
+
250
+ async def ask(self, ctx: Context, to: str, body: str, timeout_s: float = 30.0) -> dict:
251
+ """Send a question and block until its reply arrives (or timeout).
252
+
253
+ Sends ``body`` to ``to``, then waits for a message addressed back to us
254
+ whose ``reply_to`` is this question's id -- draining only that reply and
255
+ leaving any other inbox messages untouched.
256
+ """
257
+ conn = self._resolve(ctx)
258
+ to = (to or "").strip()
259
+ if not to:
260
+ raise ValueError("`to` must be a non-empty address (a participant name or role).")
261
+ now = _now()
262
+ qid = self.store.send(to, body, sender=conn.name, now=now)
263
+ self.store.touch(conn.name, now=now)
264
+ await self._notify(ctx, sender=conn.name, to=to, mid=qid, reply_to=None)
265
+
266
+ timeout_s = _clamp_timeout(timeout_s)
267
+ deadline = _now() + timeout_s
268
+ last_heartbeat = 0.0
269
+ while True:
270
+ now = _now()
271
+ if now - last_heartbeat >= _WAIT_HEARTBEAT_SECONDS:
272
+ self.store.touch(conn.name, now=now)
273
+ last_heartbeat = now
274
+ reply = self.store.take_reply(conn.name, conn.role, reply_to=qid)
275
+ if reply is not None:
276
+ self.store.touch(conn.name, now=_now())
277
+ return {
278
+ "you": conn.name,
279
+ "asked": to,
280
+ "question_id": qid,
281
+ "reply": reply.to_dict(),
282
+ "timed_out": False,
283
+ }
284
+ if now >= deadline:
285
+ self.store.touch(conn.name, now=now)
286
+ return {
287
+ "you": conn.name,
288
+ "asked": to,
289
+ "question_id": qid,
290
+ "reply": None,
291
+ "timed_out": True,
292
+ }
293
+ await anyio.sleep(min(_WAIT_POLL_SECONDS, max(0.0, deadline - now)))
294
+
295
+ async def broadcast(self, ctx: Context, body: str) -> dict:
296
+ """Send ``body`` to every currently-live participant except the sender."""
297
+ conn = self._resolve(ctx)
298
+ now = _now()
299
+ recipients = [
300
+ p for p in self.store.participants(now=now, ttl=self.ttl) if p.name != conn.name
301
+ ]
302
+ delivered = []
303
+ for p in recipients:
304
+ mid = self.store.send(p.name, body, sender=conn.name, now=now)
305
+ live = await self._notify(ctx, sender=conn.name, to=p.name, mid=mid, reply_to=None)
306
+ delivered.append({"to": p.name, "id": mid, "delivered_live": live})
307
+ self.store.touch(conn.name, now=_now())
308
+ return {"from": conn.name, "delivered": delivered, "count": len(delivered)}
309
+
310
+ def unregister(self, ctx: Context) -> dict:
311
+ """Remove the caller from the participant registry (a clean leave)."""
312
+ conn = self._conns.pop(id(ctx.session), None)
313
+ name = conn.name if conn is not None else (self._default_name or None)
314
+ if not name:
315
+ return {"ok": True, "was_registered": False, "you": None}
316
+ removed = self.store.unregister(name)
317
+ return {"ok": True, "was_registered": removed, "you": name}
318
+
319
+ def inbox(self, ctx: Context, peek: bool = False, since: Optional[int] = None) -> dict:
320
+ conn = self._resolve(ctx)
321
+ self.store.touch(conn.name, now=_now())
322
+ msgs = self.store.inbox(conn.name, conn.role, peek=peek, since=since)
323
+ return {
324
+ "you": conn.name,
325
+ "messages": [m.to_dict() for m in msgs],
326
+ "count": len(msgs),
327
+ "peek": peek,
328
+ }
329
+
330
+ async def wait(self, ctx: Context, timeout_s: float = 30.0) -> dict:
331
+ conn = self._resolve(ctx)
332
+ timeout_s = _clamp_timeout(timeout_s)
333
+ deadline = _now() + timeout_s
334
+ last_heartbeat = 0.0
335
+ while True:
336
+ now = _now()
337
+ if now - last_heartbeat >= _WAIT_HEARTBEAT_SECONDS:
338
+ self.store.touch(conn.name, now=now)
339
+ last_heartbeat = now
340
+ if self.store.has_messages(conn.name, conn.role):
341
+ msgs = self.store.inbox(conn.name, conn.role) # drain
342
+ if msgs:
343
+ self.store.touch(conn.name, now=_now())
344
+ return {
345
+ "you": conn.name,
346
+ "messages": [m.to_dict() for m in msgs],
347
+ "count": len(msgs),
348
+ "timed_out": False,
349
+ }
350
+ if now >= deadline:
351
+ self.store.touch(conn.name, now=now)
352
+ return {"you": conn.name, "messages": [], "count": 0, "timed_out": True}
353
+ await anyio.sleep(min(_WAIT_POLL_SECONDS, max(0.0, deadline - now)))
354
+
355
+ # -- helpers ------------------------------------------------------------
356
+
357
+ def _participants_payload(self) -> list[dict]:
358
+ now = _now()
359
+ # Opportunistic housekeeping so the table does not grow unbounded.
360
+ self.store.prune_participants(now=now, ttl=self.ttl)
361
+ out = []
362
+ for p in self.store.participants(now=now, ttl=self.ttl):
363
+ d = p.to_dict()
364
+ d["idle_seconds"] = round(now - p.last_seen, 1)
365
+ out.append(d)
366
+ return out
367
+
368
+
369
+ # -- FastMCP wiring ---------------------------------------------------------
370
+
371
+ # Tool docstrings are what Claude reads to decide when/how to call each tool, so
372
+ # they double as the user-facing tool descriptions. Keep them action-oriented.
373
+
374
+
375
+ def build_server(store: Optional[Store] = None, *, ttl: Optional[float] = None) -> FastMCP:
376
+ store = store if store is not None else Store()
377
+ sb = Switchboard(store, ttl=ttl if ttl is not None else _resolve_ttl())
378
+
379
+ mcp = FastMCP(
380
+ "switchboard",
381
+ instructions=(
382
+ "Shared message bus for independent Claude Code sessions. Call "
383
+ 'register(name) once to claim an address (e.g. "lead" or '
384
+ '"worker:feature-x"), then send(to, body) to message another '
385
+ "session and inbox()/wait() to receive. For a question that needs an "
386
+ "answer, ask(to, body) sends and blocks for the reply in one call. "
387
+ "Messages are durable: they wait in the recipient's mailbox until read."
388
+ ),
389
+ )
390
+ # Expose the wiring for tests and daemon introspection.
391
+ mcp._switchboard = sb # type: ignore[attr-defined]
392
+
393
+ @mcp.tool()
394
+ def register(name: str, role: str = "", ctx: Context = None) -> dict[str, Any]: # type: ignore[assignment]
395
+ """Claim an address on the switchboard for this session.
396
+
397
+ `name` is your address that others send to (e.g. "lead",
398
+ "worker:feature-x"). `role` is an optional shared address for a group
399
+ (e.g. "worker") -- a message sent to a role is delivered to any
400
+ participant that reads with that role. Re-call to refresh your presence
401
+ (a heartbeat) or change your role. Returns the current live participants.
402
+ """
403
+ return sb.register(ctx, name, role)
404
+
405
+ @mcp.tool()
406
+ def participants(ctx: Context = None) -> dict[str, Any]: # type: ignore[assignment]
407
+ """List participants seen within the TTL window (name, role, idle_seconds)."""
408
+ return sb.participants(ctx)
409
+
410
+ @mcp.tool()
411
+ async def send( # type: ignore[assignment]
412
+ to: str, body: str, reply_to: Optional[int] = None, ctx: Context = None
413
+ ) -> dict[str, Any]:
414
+ """Send a message to another participant's durable inbox.
415
+
416
+ `to` is an address: a participant name or a role. `body` is the message
417
+ text. Pass `reply_to` with a message id you received to thread a reply.
418
+ Delivery is durable -- the message waits even if `to` is offline or has
419
+ not registered yet. Returns the new message `id`.
420
+ """
421
+ return await sb.send_async(ctx, to, body, reply_to)
422
+
423
+ @mcp.tool()
424
+ def inbox( # type: ignore[assignment]
425
+ peek: bool = False, since: Optional[int] = None, ctx: Context = None
426
+ ) -> dict[str, Any]:
427
+ """Read messages addressed to you (by your name or role).
428
+
429
+ By default this DRAINS your inbox: messages are returned once and then
430
+ removed. Pass `peek=True` to read without removing. Pass `since=<id>` to
431
+ only return messages newer than that id (useful with peek to poll).
432
+ """
433
+ return sb.inbox(ctx, peek=peek, since=since)
434
+
435
+ @mcp.tool()
436
+ async def wait(timeout_s: float = 30.0, ctx: Context = None) -> dict[str, Any]: # type: ignore[assignment]
437
+ """Block until a message arrives for you, then drain and return it.
438
+
439
+ Long-polls your inbox for up to `timeout_s` seconds (capped at 3600).
440
+ Returns as soon as any message is available, draining it like inbox().
441
+ On timeout returns an empty list with `timed_out=true`. Ideal for a
442
+ long-running "lead" session parked in a /loop waiting for questions.
443
+ """
444
+ return await sb.wait(ctx, timeout_s)
445
+
446
+ @mcp.tool()
447
+ async def ask( # type: ignore[assignment]
448
+ to: str, body: str, timeout_s: float = 30.0, ctx: Context = None
449
+ ) -> dict[str, Any]:
450
+ """Send a question to another participant and block until they reply.
451
+
452
+ Sends `body` to `to`, then waits up to `timeout_s` seconds (capped at
453
+ 3600) for a reply threaded to this question, and returns it. This is the
454
+ one-call request/response: a worker can `ask("lead", "...")` and get the
455
+ answer back directly, as long as the responder replies with `reply_to`
456
+ set to the returned `question_id`. The responder should address the reply
457
+ to the question's `from` (your unique name) -- that is where ask() looks;
458
+ replying to a shared role could let a role peer drain it first. On timeout
459
+ returns `timed_out=true` and `reply=null` (the question still sits durably
460
+ in the recipient's inbox). Other messages in your inbox are left untouched.
461
+ """
462
+ return await sb.ask(ctx, to, body, timeout_s)
463
+
464
+ @mcp.tool()
465
+ async def broadcast(body: str, ctx: Context = None) -> dict[str, Any]: # type: ignore[assignment]
466
+ """Send `body` to every currently-live participant except yourself.
467
+
468
+ Delivers one durable message per live participant (those seen within the
469
+ TTL window). Returns the per-recipient message ids. Recipients that are
470
+ registered but idle past the TTL are skipped.
471
+ """
472
+ return await sb.broadcast(ctx, body)
473
+
474
+ @mcp.tool()
475
+ def unregister(ctx: Context = None) -> dict[str, Any]: # type: ignore[assignment]
476
+ """Leave the switchboard: remove yourself from the participant registry.
477
+
478
+ A courteous way to drop out so you stop showing in participants(). Your
479
+ mailbox is preserved -- any unread messages remain and are delivered if
480
+ you register under the same name again.
481
+ """
482
+ return sb.unregister(ctx)
483
+
484
+ return mcp
485
+
486
+
487
+ # -- CLI --------------------------------------------------------------------
488
+
489
+
490
+ def _build_arg_parser() -> argparse.ArgumentParser:
491
+ parser = argparse.ArgumentParser(
492
+ prog="switchboard",
493
+ description="A local MCP server for inter-session messaging between Claude Code sessions.",
494
+ )
495
+ parser.add_argument(
496
+ "--db",
497
+ default=None,
498
+ help="Path to the SQLite database (default: $SWITCHBOARD_DB or ~/.claude/switchboard.db).",
499
+ )
500
+ parser.add_argument(
501
+ "--ttl",
502
+ type=float,
503
+ default=None,
504
+ help="Participant liveness window in seconds (default: $SWITCHBOARD_TTL or 300).",
505
+ )
506
+ parser.add_argument("--version", action="store_true", help="Print version and exit.")
507
+
508
+ sub = parser.add_subparsers(dest="cmd")
509
+ serve = sub.add_parser(
510
+ "serve",
511
+ help="Run as a shared HTTP daemon (streamable-http) enabling push. Experimental.",
512
+ )
513
+ serve.add_argument("--host", default=os.environ.get("SWITCHBOARD_HOST", "127.0.0.1"))
514
+ serve.add_argument("--port", type=int, default=int(os.environ.get("SWITCHBOARD_PORT", "8765")))
515
+
516
+ # Human-facing inspection commands (read the DB directly; no MCP server).
517
+ sub.add_parser("participants", help="Print live participants and exit.")
518
+ tail = sub.add_parser("tail", help="Print queued (undelivered) messages and exit.")
519
+ tail.add_argument("-f", "--follow", action="store_true", help="Keep polling for new messages.")
520
+ tail.add_argument(
521
+ "--interval", type=float, default=1.0, help="Follow poll interval in seconds (default 1)."
522
+ )
523
+ prune = sub.add_parser(
524
+ "prune", help="Delete old undelivered messages and expired participants (housekeeping)."
525
+ )
526
+ prune.add_argument(
527
+ "--older-than-days",
528
+ type=float,
529
+ default=7.0,
530
+ help="Delete queued messages older than this many days (default 7).",
531
+ )
532
+ return parser
533
+
534
+
535
+ def _open_store_ro(db_path) -> Optional[Store]:
536
+ """Open the store for a read-only peek, or None if it does not exist yet.
537
+
538
+ Avoids materializing the database file (and its WAL sidecars) just to run an
539
+ inspection command against a system that has never started the server.
540
+ """
541
+ p = Path(str(db_path)).expanduser()
542
+ if str(p) != ":memory:" and not p.exists():
543
+ return None
544
+ return Store(db_path)
545
+
546
+
547
+ def _cli_participants(db_path, ttl: float) -> int:
548
+ store = _open_store_ro(db_path)
549
+ if store is None:
550
+ print("No live participants.")
551
+ return 0
552
+ now = _now()
553
+ parts = store.participants(now=now, ttl=ttl)
554
+ if not parts:
555
+ print("No live participants.")
556
+ return 0
557
+ for p in parts:
558
+ role = f" [{p.role}]" if p.role else ""
559
+ print(f"{p.name}{role} idle={round(now - p.last_seen, 1)}s")
560
+ return 0
561
+
562
+
563
+ def _print_pending(store: Store, since: int) -> int:
564
+ """Print all queued messages with id > ``since``; return the new high-water id."""
565
+ last = since
566
+ while True:
567
+ batch = store.pending_messages(since=last)
568
+ if not batch:
569
+ return last
570
+ for m in batch:
571
+ reply = f" (reply_to #{m.reply_to})" if m.reply_to is not None else ""
572
+ print(f"#{m.id} {m.sender} -> {m.to}: {m.body}{reply}")
573
+ last = batch[-1].id
574
+
575
+
576
+ def _cli_tail(db_path, *, follow: bool = False, interval: float = 1.0) -> int:
577
+ store = _open_store_ro(db_path)
578
+ if store is None:
579
+ return 0
580
+ last_id = _print_pending(store, 0)
581
+ while follow: # pragma: no cover - interactive follow loop (Ctrl-C to exit)
582
+ time.sleep(max(0.1, interval))
583
+ last_id = _print_pending(store, last_id)
584
+ return 0
585
+
586
+
587
+ def _cli_prune(db_path, ttl: float, older_than_days: float) -> int:
588
+ store = _open_store_ro(db_path)
589
+ if store is None:
590
+ print("Nothing to prune (no database).")
591
+ return 0
592
+ now = _now()
593
+ msgs = store.prune_messages(older_than=now - older_than_days * 86400.0)
594
+ parts = store.prune_participants(now=now, ttl=ttl)
595
+ print(f"Pruned {msgs} old message(s) and {parts} expired participant(s).")
596
+ return 0
597
+
598
+
599
+ def main(argv: Optional[list[str]] = None) -> int:
600
+ parser = _build_arg_parser()
601
+ args = parser.parse_args(argv)
602
+
603
+ if args.version:
604
+ from switchboard import __version__
605
+
606
+ print(f"switchboard {__version__}")
607
+ return 0
608
+
609
+ db_path = args.db or os.environ.get("SWITCHBOARD_DB") or default_db_path()
610
+ ttl = args.ttl if args.ttl is not None else _resolve_ttl()
611
+
612
+ # Human-facing inspection commands read the DB directly -- no server, and no
613
+ # side effect of creating the DB if it does not exist yet.
614
+ if args.cmd == "participants":
615
+ return _cli_participants(db_path, ttl)
616
+ if args.cmd == "tail":
617
+ return _cli_tail(db_path, follow=args.follow, interval=args.interval)
618
+ if args.cmd == "prune":
619
+ return _cli_prune(db_path, ttl, args.older_than_days)
620
+
621
+ store = Store(db_path)
622
+ mcp = build_server(store, ttl=ttl)
623
+
624
+ if args.cmd == "serve":
625
+ mcp.settings.host = args.host
626
+ mcp.settings.port = args.port
627
+ print(
628
+ f"switchboard daemon (streamable-http) on http://{args.host}:{args.port}"
629
+ f"{mcp.settings.streamable_http_path} db={store.db_path}",
630
+ file=sys.stderr,
631
+ )
632
+ mcp.run(transport="streamable-http")
633
+ else:
634
+ # Default: stdio, one process per Claude Code session.
635
+ mcp.run()
636
+ return 0
637
+
638
+
639
+ if __name__ == "__main__":
640
+ raise SystemExit(main())