@murmurv2/mcp-server 0.1.0 → 0.2.0

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.
package/dist/src/index.js CHANGED
@@ -1,39 +1,92 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { readFileSync } from "node:fs";
2
+ import { chmodSync, closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { createInterface } from "node:readline";
5
- import { SQLiteDedupeOutboxStore, SQLiteMessageStore, } from "@murmurv2/core";
5
+ import { ChannelRosterStore, SQLiteDedupeOutboxStore, SQLiteMessageStore, stableEnvelopePayload, } from "@murmurv2/core";
6
6
  import { encryptPayload, signEnvelope } from "@murmurv2/security";
7
+ import { NatsBroker } from "@murmurv2/broker-nats";
8
+ import { buildReplyMatcher, waitForReply } from "./request-reply.js";
7
9
  // --- Load agent config (optional — gracefully degrade if missing) ---
8
10
  const dataDir = process.env.DATA_DIR || ".data";
9
11
  const configPath = path.join(dataDir, "agent-config.json");
10
12
  const dbPath = process.env.MURMUR_STORE_PATH ?? path.join(dataDir, "murmur.db");
13
+ const channelRosterPath = process.env.MURMUR_CHANNEL_ROSTER_PATH ?? path.join(dataDir, "channel-roster.db");
14
+ const readPrivateAgentConfig = (filePath) => {
15
+ process.umask(0o077);
16
+ const dirStats = lstatSync(path.dirname(filePath));
17
+ if (dirStats.isSymbolicLink() || !dirStats.isDirectory())
18
+ throw new Error("agent-config-directory-invalid");
19
+ if (typeof process.getuid === "function" && dirStats.uid !== process.getuid()) {
20
+ throw new Error("agent-config-directory-owner-mismatch");
21
+ }
22
+ chmodSync(path.dirname(filePath), 0o700);
23
+ const pathStats = lstatSync(filePath);
24
+ if (pathStats.isSymbolicLink() || !pathStats.isFile())
25
+ throw new Error("agent-config-file-invalid");
26
+ if (typeof process.getuid === "function" && pathStats.uid !== process.getuid()) {
27
+ throw new Error("agent-config-file-owner-mismatch");
28
+ }
29
+ chmodSync(filePath, 0o600);
30
+ const fd = openSync(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
31
+ try {
32
+ const openedStats = fstatSync(fd);
33
+ if (!openedStats.isFile())
34
+ throw new Error("agent-config-file-invalid");
35
+ if (typeof process.getuid === "function" && openedStats.uid !== process.getuid()) {
36
+ throw new Error("agent-config-file-owner-mismatch");
37
+ }
38
+ return JSON.parse(readFileSync(fd, "utf8"));
39
+ }
40
+ finally {
41
+ closeSync(fd);
42
+ }
43
+ };
11
44
  let agentConfig = null;
12
45
  try {
13
- agentConfig = JSON.parse(readFileSync(configPath, "utf8"));
46
+ agentConfig = readPrivateAgentConfig(configPath);
14
47
  }
15
48
  catch {
16
49
  // Agent config not found — send/inbox/peers tools will be unavailable
17
50
  }
18
51
  const store = new SQLiteMessageStore(dbPath);
52
+ const channelRoster = new ChannelRosterStore(channelRosterPath);
19
53
  // Outbox store — shared with daemon, only created if agent config exists
20
54
  let outbox = null;
21
55
  if (agentConfig) {
22
56
  outbox = new SQLiteDedupeOutboxStore(dbPath);
23
57
  }
24
- // --- Stable envelope payload for signing ---
25
- const stableEnvelopePayload = (envelope) => {
26
- return JSON.stringify({
27
- schemaVersion: envelope.schemaVersion,
28
- msgId: envelope.msgId,
29
- conversationId: envelope.conversationId,
30
- senderAgentId: envelope.senderAgentId,
31
- recipients: [...envelope.recipients],
32
- createdAt: envelope.createdAt,
33
- payloadCiphertext: envelope.payloadCiphertext,
34
- payloadNonce: envelope.payloadNonce,
35
- });
58
+ // Lazy read-only NATS tap for wake-accelerated murmur_request. Optional — if NATS is
59
+ // unreachable we degrade gracefully to pure store polling. A failed connect does NOT
60
+ // disable acceleration forever: it's retried after a cooldown so a transient outage at
61
+ // startup doesn't permanently fall back to slow polling (per CODEX-VOLT review).
62
+ const WAKE_BROKER_RETRY_COOLDOWN_MS = 30_000;
63
+ let wakeBroker = null;
64
+ let wakeBrokerNextRetry = 0;
65
+ const getWakeBroker = async (now = Date.now) => {
66
+ if (!agentConfig)
67
+ return null;
68
+ if (wakeBroker)
69
+ return wakeBroker;
70
+ if (now() < wakeBrokerNextRetry)
71
+ return null; // in cooldown after a recent failure
72
+ try {
73
+ const broker = new NatsBroker({
74
+ url: agentConfig.natsUrl,
75
+ token: agentConfig.natsToken,
76
+ jetstream: false,
77
+ });
78
+ await broker.connect();
79
+ wakeBroker = broker;
80
+ }
81
+ catch {
82
+ // graceful degrade — store polling still resolves the reply; retry after cooldown
83
+ wakeBroker = null;
84
+ wakeBrokerNextRetry = now() + WAKE_BROKER_RETRY_COOLDOWN_MS;
85
+ }
86
+ return wakeBroker;
36
87
  };
88
+ // stableEnvelopePayload is the canonical signing form from @murmurv2/core
89
+ // (single source of truth shared by daemon / bridges / runner / demos).
37
90
  // --- JSON-RPC helpers ---
38
91
  const send = (payload) => {
39
92
  process.stdout.write(`${JSON.stringify(payload)}\n`);
@@ -92,6 +145,62 @@ const handleTool = async (name, args) => {
92
145
  const messages = await store.searchMessages(query, Number.isFinite(limit) ? limit : 50);
93
146
  return { messages: messages.map(asMessage) };
94
147
  }
148
+ if (name === "channel_create") {
149
+ const channelId = String(args.channelId ?? "").trim();
150
+ if (!channelId)
151
+ throw new Error("channelId is required");
152
+ const conversationId = String(args.conversationId ?? "").trim();
153
+ if (!conversationId)
154
+ throw new Error("conversationId is required");
155
+ const type = String(args.type ?? "").trim();
156
+ if (!["dm", "group", "consult"].includes(type))
157
+ throw new Error("type must be one of: dm, group, consult");
158
+ const members = Array.isArray(args.members) ? args.members : [];
159
+ const channel = channelRoster.createChannel({
160
+ channelId,
161
+ conversationId,
162
+ type: type,
163
+ metadata: typeof args.metadata === "object" && args.metadata && !Array.isArray(args.metadata) ? args.metadata : undefined,
164
+ members: members.map((member) => ({
165
+ memberId: String(member.memberId ?? "").trim(),
166
+ memberSlot: member.memberSlot === undefined ? undefined : String(member.memberSlot),
167
+ agentId: String(member.agentId ?? "").trim(),
168
+ role: member.role === undefined ? undefined : String(member.role),
169
+ personaId: member.personaId === undefined ? undefined : String(member.personaId),
170
+ model: member.model === undefined ? undefined : String(member.model),
171
+ baseInstructionsHash: member.baseInstructionsHash === undefined ? undefined : String(member.baseInstructionsHash),
172
+ eligibility: typeof member.eligibility === "object" && member.eligibility && !Array.isArray(member.eligibility) ? member.eligibility : undefined,
173
+ metadata: typeof member.metadata === "object" && member.metadata && !Array.isArray(member.metadata) ? member.metadata : undefined,
174
+ })),
175
+ });
176
+ return { channel, members: channelRoster.listChannelMembers(channelId) };
177
+ }
178
+ if (name === "channel_list") {
179
+ const conversationId = String(args.conversationId ?? "").trim();
180
+ if (!conversationId)
181
+ throw new Error("conversationId is required");
182
+ return { channels: channelRoster.listChannelsForConversation(conversationId) };
183
+ }
184
+ if (name === "channel_members") {
185
+ const channelId = String(args.channelId ?? "").trim();
186
+ if (!channelId)
187
+ throw new Error("channelId is required");
188
+ return { members: channelRoster.listChannelMembers(channelId) };
189
+ }
190
+ if (name === "channel_evaluate_addressing") {
191
+ const selfAgentId = String(args.selfAgentId ?? "").trim();
192
+ if (!selfAgentId)
193
+ throw new Error("selfAgentId is required");
194
+ return {
195
+ decision: channelRoster.evaluateAddressing({
196
+ channelId: args.channelId === undefined ? undefined : String(args.channelId),
197
+ selfAgentId,
198
+ senderAgentId: args.senderAgentId === undefined ? undefined : String(args.senderAgentId),
199
+ addresseeMemberId: args.addresseeMemberId === undefined ? undefined : String(args.addresseeMemberId),
200
+ addresseeAgentId: args.addresseeAgentId === undefined ? undefined : String(args.addresseeAgentId),
201
+ }),
202
+ };
203
+ }
95
204
  // === New agent-to-agent tools (require agent config) ===
96
205
  if (name === "murmur_send") {
97
206
  if (!agentConfig || !outbox)
@@ -195,16 +304,63 @@ const handleTool = async (name, args) => {
195
304
  createdAt: sentAt,
196
305
  transport: "nats",
197
306
  });
198
- // Poll for response
307
+ // Wait for the reply. Store polling is the durable fallback and always runs;
308
+ // an optional read-only NATS tap on our own subject accelerates the wait by
309
+ // re-checking the store as soon as a matching envelope is observed. The tap is
310
+ // signal-only — the daemon stays the source of truth for decrypt + persistence.
311
+ const graceMs = Number(args.grace_ms ?? 250);
199
312
  const deadline = Date.now() + timeoutMs;
313
+ const matchReply = buildReplyMatcher(conversationId, to);
314
+ const broker = await getWakeBroker();
315
+ // Holder object: the tap is attached inside a callback, so a plain `let` would be
316
+ // narrowed to `null` by control-flow analysis. A mutable property keeps its type.
317
+ const tap = {
318
+ attach: null,
319
+ sub: null,
320
+ };
321
+ let wokenBySignal = false;
322
+ let onSignal;
323
+ if (broker) {
324
+ onSignal = (wake) => {
325
+ tap.attach = broker
326
+ .subscribeRaw(agentConfig.subject, (env) => {
327
+ if (matchReply(env)) {
328
+ wokenBySignal = true;
329
+ wake();
330
+ }
331
+ })
332
+ .then((sub) => {
333
+ tap.sub = sub;
334
+ })
335
+ .catch(() => {
336
+ /* tap failed to attach — store polling still resolves the reply */
337
+ });
338
+ };
339
+ }
200
340
  let reply = null;
201
- while (Date.now() < deadline) {
202
- const inbound = await store.getInboundAfter(conversationId, sentAt, 1);
203
- if (inbound.length > 0) {
204
- reply = inbound[0];
205
- break;
341
+ try {
342
+ reply = await waitForReply({
343
+ checkStore: async () => {
344
+ const inbound = await store.getInboundAfter(conversationId, sentAt, 1);
345
+ return inbound.length > 0 ? inbound[0] : null;
346
+ },
347
+ pollMs,
348
+ graceMs,
349
+ deadline,
350
+ onSignal,
351
+ });
352
+ }
353
+ finally {
354
+ if (tap.attach)
355
+ await tap.attach;
356
+ if (tap.sub) {
357
+ try {
358
+ await tap.sub.unsubscribe();
359
+ }
360
+ catch {
361
+ /* ignore unsubscribe errors */
362
+ }
206
363
  }
207
- await new Promise((r) => setTimeout(r, pollMs));
208
364
  }
209
365
  if (reply) {
210
366
  return {
@@ -213,6 +369,11 @@ const handleTool = async (name, args) => {
213
369
  conversationId,
214
370
  sentAt,
215
371
  reply: asMessage(reply),
372
+ // Precise telemetry (per CODEX-VOLT review): tapAttached = the read-only NATS
373
+ // tap was live for this wait; wokenBySignal = a matching envelope actually
374
+ // short-circuited the poll (true acceleration, not merely "broker available").
375
+ tapAttached: tap.sub !== null,
376
+ wokenBySignal,
216
377
  };
217
378
  }
218
379
  return {
@@ -275,6 +436,75 @@ const tools = [
275
436
  required: ["query"],
276
437
  },
277
438
  },
439
+ {
440
+ name: "channel_create",
441
+ description: "Create a typed Murmur channel roster entry with optional members.",
442
+ inputSchema: {
443
+ type: "object",
444
+ properties: {
445
+ channelId: { type: "string", description: "Stable channel/routing ID, distinct from conversationId" },
446
+ conversationId: { type: "string", description: "Legacy history label associated with the channel" },
447
+ type: { type: "string", enum: ["dm", "group", "consult"] },
448
+ metadata: { type: "object" },
449
+ members: {
450
+ type: "array",
451
+ items: {
452
+ type: "object",
453
+ properties: {
454
+ memberId: { type: "string" },
455
+ memberSlot: { type: "string" },
456
+ agentId: { type: "string" },
457
+ role: { type: "string" },
458
+ personaId: { type: "string" },
459
+ model: { type: "string" },
460
+ baseInstructionsHash: { type: "string" },
461
+ eligibility: { type: "object" },
462
+ metadata: { type: "object" },
463
+ },
464
+ required: ["memberId", "agentId"],
465
+ },
466
+ },
467
+ },
468
+ required: ["channelId", "conversationId", "type"],
469
+ },
470
+ },
471
+ {
472
+ name: "channel_list",
473
+ description: "List typed channels associated with a legacy conversationId.",
474
+ inputSchema: {
475
+ type: "object",
476
+ properties: {
477
+ conversationId: { type: "string" },
478
+ },
479
+ required: ["conversationId"],
480
+ },
481
+ },
482
+ {
483
+ name: "channel_members",
484
+ description: "List active and historical members for a typed channel.",
485
+ inputSchema: {
486
+ type: "object",
487
+ properties: {
488
+ channelId: { type: "string" },
489
+ },
490
+ required: ["channelId"],
491
+ },
492
+ },
493
+ {
494
+ name: "channel_evaluate_addressing",
495
+ description: "Evaluate channel membership/addressing into reject/append/wake decisions.",
496
+ inputSchema: {
497
+ type: "object",
498
+ properties: {
499
+ channelId: { type: "string" },
500
+ selfAgentId: { type: "string" },
501
+ senderAgentId: { type: "string" },
502
+ addresseeMemberId: { type: "string" },
503
+ addresseeAgentId: { type: "string" },
504
+ },
505
+ required: ["selfAgentId"],
506
+ },
507
+ },
278
508
  {
279
509
  name: "murmur_send",
280
510
  description: "Send an encrypted, signed message to another agent via NATS. Message is queued in outbox and delivered by murmur-daemon.",
@@ -290,7 +520,7 @@ const tools = [
290
520
  },
291
521
  {
292
522
  name: "murmur_request",
293
- description: "Send a message and wait for the reply. Combines murmur_send + automatic polling — the tool blocks until the peer responds or timeout is reached. Ideal for autonomous agent-to-agent conversations.",
523
+ description: "Send a message and wait for the reply. Combines murmur_send with a durable store-poll, accelerated by a read-only NATS tap so the reply is returned as soon as it lands (falls back to pure polling when NATS is unavailable). The tool blocks until the peer responds or timeout is reached. Ideal for autonomous agent-to-agent conversations.",
294
524
  inputSchema: {
295
525
  type: "object",
296
526
  properties: {
@@ -298,7 +528,8 @@ const tools = [
298
528
  text: { type: "string", description: "Message text (will be encrypted)" },
299
529
  conversationId: { type: "string", description: "Optional conversation ID" },
300
530
  timeout_ms: { type: "number", description: "Max wait time in ms (default: 300000 = 5 min)" },
301
- poll_interval_ms: { type: "number", description: "Poll interval in ms (default: 10000 = 10s)" },
531
+ poll_interval_ms: { type: "number", description: "Store-poll fallback interval in ms (default: 10000 = 10s)" },
532
+ grace_ms: { type: "number", description: "Delay after a wake signal before re-checking the store, to let the daemon persist (default: 250)" },
302
533
  },
303
534
  required: ["to", "text"],
304
535
  },
@@ -0,0 +1,46 @@
1
+ import type { LocalMessageRecord } from "@murmurv2/core";
2
+ /**
3
+ * Pure wait-loop for the request/reply ("native-request-reply") flow.
4
+ *
5
+ * Design B (locked with CODEX-VOLT):
6
+ * - The outbox stays the source of truth: sending happens elsewhere, this only WAITS.
7
+ * - Store polling is the durable fallback and ALWAYS runs, so a reply is found even
8
+ * when no live wake signal is available (NATS down / `onSignal` omitted).
9
+ * - An optional `onSignal` source (a read-only NATS tap on the agent's own subject)
10
+ * accelerates the wait: when a matching envelope arrives we re-check the store
11
+ * immediately instead of waiting out the poll interval. The signal NEVER carries
12
+ * the reply itself — decryption + persistence stay the daemon's job — it only nudges
13
+ * us to re-poll the store the daemon writes into.
14
+ *
15
+ * Lost-wakeup safety: the wake promise is armed BEFORE each store check, so a signal
16
+ * that fires between the check and the race still short-circuits the wait.
17
+ */
18
+ export interface ReplyWaiterDeps {
19
+ /** Return the reply record if one has arrived, else null. */
20
+ checkStore: () => Promise<LocalMessageRecord | null>;
21
+ /** Poll interval in ms (fallback cadence when no signal fires). */
22
+ pollMs: number;
23
+ /** Grace delay in ms after a signal, to let the daemon persist before re-checking. */
24
+ graceMs: number;
25
+ /** Absolute deadline as epoch ms (Date.now()-style). */
26
+ deadline: number;
27
+ /**
28
+ * Optional wake-signal registration. Called once with a callback; invoke the
29
+ * callback whenever a relevant inbound envelope is observed. Omit for pure-poll.
30
+ */
31
+ onSignal?: (wake: () => void) => void;
32
+ /** Injectable clock (tests). Defaults to Date.now. */
33
+ now?: () => number;
34
+ /** Injectable sleep (tests). Defaults to setTimeout. */
35
+ sleep?: (ms: number) => Promise<void>;
36
+ }
37
+ export declare function waitForReply(deps: ReplyWaiterDeps): Promise<LocalMessageRecord | null>;
38
+ /**
39
+ * Build a predicate that matches an inbound envelope as the awaited reply:
40
+ * same conversation AND sent by the peer we are waiting on. Envelope metadata is
41
+ * plaintext (conversationId / senderAgentId), so this needs no decryption.
42
+ */
43
+ export declare const buildReplyMatcher: (conversationId: string, fromAgentId: string) => (envelope: {
44
+ conversationId: string;
45
+ senderAgentId: string;
46
+ }) => boolean;
@@ -0,0 +1,40 @@
1
+ export async function waitForReply(deps) {
2
+ const now = deps.now ?? (() => Date.now());
3
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
4
+ let signaled = false;
5
+ let wakeResolve = null;
6
+ if (deps.onSignal) {
7
+ deps.onSignal(() => {
8
+ signaled = true;
9
+ wakeResolve?.();
10
+ });
11
+ }
12
+ while (now() < deps.deadline) {
13
+ // Arm the wake BEFORE checking the store to avoid a lost wakeup: a signal that
14
+ // fires while checkStore() is in flight still resolves this promise.
15
+ signaled = false;
16
+ const wake = new Promise((resolve) => {
17
+ wakeResolve = resolve;
18
+ });
19
+ const found = await deps.checkStore();
20
+ if (found)
21
+ return found;
22
+ const remaining = deps.deadline - now();
23
+ if (remaining <= 0)
24
+ break;
25
+ const waitMs = Math.min(deps.pollMs, remaining);
26
+ await Promise.race([wake, sleep(waitMs)]);
27
+ if (signaled) {
28
+ const graceRemaining = deps.deadline - now();
29
+ if (graceRemaining > 0)
30
+ await sleep(Math.min(deps.graceMs, graceRemaining));
31
+ }
32
+ }
33
+ return null;
34
+ }
35
+ /**
36
+ * Build a predicate that matches an inbound envelope as the awaited reply:
37
+ * same conversation AND sent by the peer we are waiting on. Envelope metadata is
38
+ * plaintext (conversationId / senderAgentId), so this needs no decryption.
39
+ */
40
+ export const buildReplyMatcher = (conversationId, fromAgentId) => (envelope) => envelope.conversationId === conversationId && envelope.senderAgentId === fromAgentId;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@murmurv2/mcp-server",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "main": "dist/src/index.js",
6
6
  "types": "dist/src/index.d.ts",
@@ -9,13 +9,14 @@
9
9
  "prepack": "npm run build"
10
10
  },
11
11
  "dependencies": {
12
- "@murmurv2/core": "^0.1.0",
12
+ "@murmurv2/broker-nats": "^0.3.0",
13
+ "@murmurv2/core": "^0.4.0",
13
14
  "@murmurv2/security": "^0.1.0"
14
15
  },
15
16
  "license": "MIT",
16
17
  "repository": {
17
18
  "type": "git",
18
- "url": "git+https://github.com/alexfrmn/mur-mur-v2.git",
19
+ "url": "git+https://github.com/alexfrmn/murmur.git",
19
20
  "directory": "packages/mcp-server"
20
21
  },
21
22
  "publishConfig": {
@@ -25,5 +26,25 @@
25
26
  "dist/src",
26
27
  "LICENSE"
27
28
  ],
28
- "description": "Murmur V2 MCP server — 7 tools for agent-to-agent messaging over the Model Context Protocol."
29
+ "description": "Murmur V2 MCP server — agent-to-agent messaging and scoped-channel roster tools over the Model Context Protocol.",
30
+ "homepage": "https://github.com/alexfrmn/murmur#readme",
31
+ "bugs": {
32
+ "url": "https://github.com/alexfrmn/murmur/issues"
33
+ },
34
+ "keywords": [
35
+ "murmur",
36
+ "agent-communication",
37
+ "agent-to-agent",
38
+ "a2a",
39
+ "agent-bus",
40
+ "message-bus",
41
+ "ai-agents",
42
+ "multi-agent",
43
+ "mcp",
44
+ "model-context-protocol",
45
+ "claude-code",
46
+ "codex",
47
+ "mcp-server",
48
+ "tools"
49
+ ]
29
50
  }