@murmurv2/mcp-server 0.2.0 → 0.2.3

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,44 @@
1
+ export interface AgentConfig {
2
+ agentId: string;
3
+ memberId?: string;
4
+ natsUrl: string;
5
+ natsToken?: string;
6
+ subject: string;
7
+ subjectScoping?: {
8
+ enabled?: boolean;
9
+ channelIds?: string[];
10
+ };
11
+ dataDir: string;
12
+ keys: {
13
+ encryption: {
14
+ publicKey: string;
15
+ privateKey: string;
16
+ };
17
+ signing: {
18
+ publicKey: string;
19
+ privateKey: string;
20
+ };
21
+ };
22
+ peers: Record<string, {
23
+ encryption: {
24
+ publicKey: string;
25
+ };
26
+ signing: {
27
+ publicKey: string;
28
+ };
29
+ subject: string;
30
+ subjectScoping?: boolean;
31
+ channelId?: string;
32
+ memberId?: string;
33
+ }>;
34
+ }
35
+ /** Peer-only refresh; a process remains bound to its first valid identity/runtime. */
36
+ export declare class AgentConfigCache {
37
+ private readonly filePath;
38
+ private cached;
39
+ private pinnedIdentity;
40
+ private pinnedBinding;
41
+ private directory;
42
+ constructor(filePath: string);
43
+ read(force?: boolean): AgentConfig;
44
+ }
@@ -0,0 +1,89 @@
1
+ import { chmodSync, closeSync, constants, fchmodSync, fstatSync, lstatSync, openSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ const sameFile = (a, b) => a.ino === b.ino && (process.platform === "win32"
4
+ ? a.dev === 0n || b.dev === 0n || BigInt.asUintN(32, a.dev) === BigInt.asUintN(32, b.dev)
5
+ : a.dev === b.dev);
6
+ const stamp = (s) => [s.dev, s.ino, s.mtimeNs, s.ctimeNs, s.size, s.mode, s.uid].join(":");
7
+ const validateFile = (s) => {
8
+ if (s.isSymbolicLink() || !s.isFile())
9
+ throw new Error("agent-config-file-invalid");
10
+ if (typeof process.getuid === "function" && s.uid !== BigInt(process.getuid()))
11
+ throw new Error("agent-config-file-owner-mismatch");
12
+ };
13
+ const identity = (c) => JSON.stringify([c.agentId,
14
+ c.keys?.encryption?.publicKey, c.keys?.encryption?.privateKey,
15
+ c.keys?.signing?.publicKey, c.keys?.signing?.privateKey]);
16
+ const binding = (c) => JSON.stringify([c.memberId, c.subject, c.natsUrl, c.natsToken, c.dataDir,
17
+ c.subjectScoping?.enabled, [...(c.subjectScoping?.channelIds ?? [])].sort()]);
18
+ /** Peer-only refresh; a process remains bound to its first valid identity/runtime. */
19
+ export class AgentConfigCache {
20
+ filePath;
21
+ cached = null;
22
+ pinnedIdentity;
23
+ pinnedBinding;
24
+ directory;
25
+ constructor(filePath) {
26
+ this.filePath = filePath;
27
+ }
28
+ read(force = false) {
29
+ try {
30
+ process.umask(0o077);
31
+ const dir = path.dirname(this.filePath);
32
+ const directory = lstatSync(dir, { bigint: true });
33
+ if (directory.isSymbolicLink() || !directory.isDirectory())
34
+ throw new Error("agent-config-directory-invalid");
35
+ if (typeof process.getuid === "function" && directory.uid !== BigInt(process.getuid()))
36
+ throw new Error("agent-config-directory-owner-mismatch");
37
+ if (this.directory && !sameFile(this.directory, directory))
38
+ throw new Error("agent-config-profile-changed-restart-required");
39
+ chmodSync(dir, 0o700);
40
+ const before = lstatSync(this.filePath, { bigint: true });
41
+ validateFile(before);
42
+ if (!force && this.cached?.stamp === stamp(before))
43
+ return this.cached.config;
44
+ const fd = openSync(this.filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
45
+ let config, finalStats;
46
+ try {
47
+ const opened = fstatSync(fd, { bigint: true });
48
+ validateFile(opened);
49
+ if (!sameFile(before, opened) || before.size !== opened.size || before.mtimeNs !== opened.mtimeNs)
50
+ throw new Error("agent-config-file-changed");
51
+ fchmodSync(fd, 0o600);
52
+ const reading = fstatSync(fd, { bigint: true });
53
+ const contents = readFileSync(fd, "utf8");
54
+ finalStats = fstatSync(fd, { bigint: true });
55
+ const after = lstatSync(this.filePath, { bigint: true });
56
+ validateFile(after);
57
+ if (!sameFile(opened, after) || stamp(reading) !== stamp(finalStats)
58
+ || after.size !== finalStats.size || after.mtimeNs !== finalStats.mtimeNs || after.ctimeNs !== finalStats.ctimeNs
59
+ || !sameFile(directory, lstatSync(dir, { bigint: true })))
60
+ throw new Error("agent-config-file-changed");
61
+ // Path and handle dev differ on Node 22.13/Windows; cache the path stamp.
62
+ finalStats = after;
63
+ config = JSON.parse(contents);
64
+ }
65
+ finally {
66
+ closeSync(fd);
67
+ }
68
+ if (!config || typeof config.agentId !== "string" || !config.agentId.trim()
69
+ || !config.peers || typeof config.peers !== "object" || Array.isArray(config.peers))
70
+ throw new Error("agent-config-invalid");
71
+ const nextIdentity = identity(config), nextBinding = binding(config);
72
+ if (this.pinnedIdentity !== undefined && nextIdentity !== this.pinnedIdentity)
73
+ throw new Error("agent-config-identity-changed-restart-required");
74
+ if (this.pinnedBinding !== undefined && nextBinding !== this.pinnedBinding)
75
+ throw new Error("agent-config-runtime-changed-restart-required");
76
+ this.pinnedIdentity = nextIdentity;
77
+ this.pinnedBinding = nextBinding;
78
+ this.directory = directory;
79
+ this.cached = { config, stamp: stamp(finalStats) };
80
+ return config;
81
+ }
82
+ catch (error) {
83
+ this.cached = null; // Never send with old peer keys after any read/parse/policy failure.
84
+ if (error instanceof Error && /^agent-config-[a-z-]+$/.test(error.message))
85
+ throw error;
86
+ throw new Error("agent-config-unavailable-retry-or-restart");
87
+ }
88
+ }
89
+ }
@@ -0,0 +1,6 @@
1
+ export declare const codexTaskConversationId: (threadId: string | undefined) => string | null;
2
+ export declare const defaultPeerConversationId: ({ to, agentId, codexThreadId, }: {
3
+ to: string;
4
+ agentId: string;
5
+ codexThreadId?: string;
6
+ }) => string;
@@ -0,0 +1,6 @@
1
+ const THREAD_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2
+ export const codexTaskConversationId = (threadId) => {
3
+ const value = String(threadId ?? "").trim();
4
+ return THREAD_ID_PATTERN.test(value) ? `codex:task:${value}` : null;
5
+ };
6
+ export const defaultPeerConversationId = ({ to, agentId, codexThreadId, }) => codexTaskConversationId(codexThreadId) ?? `dm:${agentId}:${to}`;
package/dist/src/index.js CHANGED
@@ -1,58 +1,137 @@
1
- import { randomUUID } from "node:crypto";
2
- import { chmodSync, closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, } from "node:fs";
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { chmodSync, closeSync, constants, mkdirSync, openSync, readFileSync, rmSync, writeFileSync, } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { createInterface } from "node:readline";
5
- import { ChannelRosterStore, SQLiteDedupeOutboxStore, SQLiteMessageStore, stableEnvelopePayload, } from "@murmurv2/core";
5
+ import { ChannelRosterStore, SQLiteDedupeOutboxStore, SQLiteMessageStore, stableEnvelopePayload, resolveMessageSubject, channelScopedSubject, } from "@murmurv2/core";
6
6
  import { encryptPayload, signEnvelope } from "@murmurv2/security";
7
7
  import { NatsBroker } from "@murmurv2/broker-nats";
8
- import { buildReplyMatcher, waitForReply } from "./request-reply.js";
8
+ import { codexTaskConversationId, defaultPeerConversationId } from "./codex-routing.js";
9
+ import { buildReplyMatcher, createReplySignalTap, requestDelivery, requestTiming, waitForReply } from "./request-reply.js";
10
+ import { AgentConfigCache } from "./agent-config.js";
9
11
  // --- Load agent config (optional — gracefully degrade if missing) ---
10
12
  const dataDir = process.env.DATA_DIR || ".data";
11
13
  const configPath = path.join(dataDir, "agent-config.json");
12
14
  const dbPath = process.env.MURMUR_STORE_PATH ?? path.join(dataDir, "murmur.db");
13
15
  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");
16
+ // One stdio connection is one chat session. Callers cannot impersonate another
17
+ // session/agent through tool arguments; hosts may supply their stable session ID.
18
+ const presenceSessionId = (process.env.MURMUR_SESSION_ID || process.env.CODEX_THREAD_ID || process.env.CLAUDE_CODE_SESSION_ID || `mcp:${randomUUID()}`).trim();
19
+ const requestWaitDir = path.resolve(dataDir, ".codex-request-waits");
20
+ const taskBindingDir = path.resolve(dataDir, ".codex-task-bindings");
21
+ const privateDigestPath = (directory, conversationId, peerId) => {
22
+ const key = createHash("sha256").update(`${conversationId}\0${peerId}`).digest("hex");
23
+ return path.join(directory, `${key}.json`);
24
+ };
25
+ const requestWaitPath = (conversationId, peerId) => {
26
+ return privateDigestPath(requestWaitDir, conversationId, peerId);
27
+ };
28
+ const armSynchronousReplySuppression = (conversationId, peerId, timeoutMs) => {
29
+ try {
30
+ mkdirSync(requestWaitDir, { recursive: true, mode: 0o700 });
31
+ chmodSync(requestWaitDir, 0o700);
32
+ const markerPath = requestWaitPath(conversationId, peerId);
33
+ const marker = {
34
+ conversationId,
35
+ peerId,
36
+ pid: process.pid,
37
+ expiresAt: Date.now() + Math.max(1_000, timeoutMs) + 60_000,
38
+ };
39
+ const create = () => {
40
+ const fd = openSync(markerPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);
41
+ try {
42
+ writeFileSync(fd, JSON.stringify(marker));
43
+ }
44
+ finally {
45
+ closeSync(fd);
46
+ }
47
+ return markerPath;
48
+ };
49
+ try {
50
+ return create();
51
+ }
52
+ catch (error) {
53
+ if (error.code !== "EEXIST")
54
+ throw error;
55
+ let existingLive = true;
56
+ try {
57
+ const existing = JSON.parse(readFileSync(markerPath, "utf8"));
58
+ existingLive = Number(existing.expiresAt) >= Date.now();
59
+ if (existingLive && Number.isSafeInteger(existing.pid) && Number(existing.pid) > 0) {
60
+ try {
61
+ process.kill(Number(existing.pid), 0);
62
+ }
63
+ catch {
64
+ existingLive = false;
65
+ }
66
+ }
67
+ }
68
+ catch {
69
+ existingLive = false;
70
+ }
71
+ if (existingLive)
72
+ throw new Error("murmur-request-already-pending-for-peer-and-conversation");
73
+ rmSync(markerPath, { force: true });
74
+ return create();
75
+ }
21
76
  }
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");
77
+ catch (error) {
78
+ if (error.message === "murmur-request-already-pending-for-peer-and-conversation")
79
+ throw error;
80
+ // Suppression is only a convenience. Request/reply must still work if the
81
+ // marker cannot be written.
82
+ return null;
28
83
  }
29
- chmodSync(filePath, 0o600);
30
- const fd = openSync(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
84
+ };
85
+ const shortenSynchronousReplySuppression = (markerPath, graceMs = 5_000) => {
86
+ if (!markerPath)
87
+ return;
31
88
  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"));
89
+ const marker = JSON.parse(readFileSync(markerPath, "utf8"));
90
+ writeFileSync(markerPath, JSON.stringify({ ...marker, expiresAt: Date.now() + graceMs }), { mode: 0o600 });
91
+ const timer = setTimeout(() => clearSynchronousReplySuppression(markerPath), graceMs);
92
+ timer.unref();
39
93
  }
40
- finally {
41
- closeSync(fd);
94
+ catch {
95
+ // The receive hook may already have atomically claimed the marker.
42
96
  }
43
97
  };
44
- let agentConfig = null;
98
+ const recordCodexTaskPeerBinding = (conversationId, peerId) => {
99
+ const ownTaskConversationId = codexTaskConversationId(process.env.CODEX_THREAD_ID);
100
+ if (!ownTaskConversationId || conversationId !== ownTaskConversationId)
101
+ return;
102
+ try {
103
+ mkdirSync(taskBindingDir, { recursive: true, mode: 0o700 });
104
+ chmodSync(taskBindingDir, 0o700);
105
+ const bindingPath = privateDigestPath(taskBindingDir, conversationId, peerId);
106
+ writeFileSync(bindingPath, JSON.stringify({ conversationId, peerId, createdAt: new Date().toISOString() }), { mode: 0o600 });
107
+ chmodSync(bindingPath, 0o600);
108
+ }
109
+ catch {
110
+ // Binding is a local auto-delivery authorization. A write failure safely
111
+ // degrades replies to inbox-only delivery on the receiving hook.
112
+ }
113
+ };
114
+ const clearSynchronousReplySuppression = (markerPath) => {
115
+ if (!markerPath)
116
+ return;
117
+ try {
118
+ rmSync(markerPath, { force: true });
119
+ }
120
+ catch {
121
+ // Best-effort cleanup; stale markers have an expiry and are ignored by the hook.
122
+ }
123
+ };
124
+ const configCache = new AgentConfigCache(configPath);
125
+ let initialConfig = null;
45
126
  try {
46
- agentConfig = readPrivateAgentConfig(configPath);
47
- }
48
- catch {
49
- // Agent config not found — send/inbox/peers tools will be unavailable
127
+ initialConfig = configCache.read();
50
128
  }
129
+ catch { /* Optional until a config-bound tool is used. */ }
51
130
  const store = new SQLiteMessageStore(dbPath);
52
131
  const channelRoster = new ChannelRosterStore(channelRosterPath);
53
132
  // Outbox store — shared with daemon, only created if agent config exists
54
133
  let outbox = null;
55
- if (agentConfig) {
134
+ if (initialConfig) {
56
135
  outbox = new SQLiteDedupeOutboxStore(dbPath);
57
136
  }
58
137
  // Lazy read-only NATS tap for wake-accelerated murmur_request. Optional — if NATS is
@@ -61,29 +140,45 @@ if (agentConfig) {
61
140
  // startup doesn't permanently fall back to slow polling (per CODEX-VOLT review).
62
141
  const WAKE_BROKER_RETRY_COOLDOWN_MS = 30_000;
63
142
  let wakeBroker = null;
143
+ let wakeBrokerConnecting = null;
64
144
  let wakeBrokerNextRetry = 0;
65
- const getWakeBroker = async (now = Date.now) => {
66
- if (!agentConfig)
67
- return null;
145
+ const getWakeBroker = async (agentConfig, now = Date.now) => {
68
146
  if (wakeBroker)
69
147
  return wakeBroker;
148
+ if (wakeBrokerConnecting)
149
+ return wakeBrokerConnecting;
70
150
  if (now() < wakeBrokerNextRetry)
71
151
  return null; // in cooldown after a recent failure
152
+ const broker = new NatsBroker({
153
+ url: agentConfig.natsUrl,
154
+ token: agentConfig.natsToken,
155
+ jetstream: false,
156
+ // The tap is optional. Daemon reconnect policy must not make this tool wait
157
+ // forever before it can poll the durable local store.
158
+ waitOnFirstConnect: false,
159
+ maxReconnectAttempts: 0,
160
+ connectMaxAttempts: 1,
161
+ connectTimeoutMs: 2_000,
162
+ });
163
+ wakeBrokerConnecting = (async () => {
164
+ try {
165
+ await broker.connect();
166
+ wakeBroker = broker;
167
+ }
168
+ catch {
169
+ // graceful degrade — store polling still resolves the reply; retry after cooldown
170
+ wakeBroker = null;
171
+ wakeBrokerNextRetry = now() + WAKE_BROKER_RETRY_COOLDOWN_MS;
172
+ void broker.close().catch(() => { });
173
+ }
174
+ return wakeBroker;
175
+ })();
72
176
  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;
177
+ return await wakeBrokerConnecting;
80
178
  }
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;
179
+ finally {
180
+ wakeBrokerConnecting = null;
85
181
  }
86
- return wakeBroker;
87
182
  };
88
183
  // stableEnvelopePayload is the canonical signing form from @murmurv2/core
89
184
  // (single source of truth shared by daemon / bridges / runner / demos).
@@ -110,9 +205,40 @@ const asMessage = (r) => ({
110
205
  text: r.text,
111
206
  createdAt: r.createdAt,
112
207
  transport: r.transport,
208
+ channelId: r.channelId,
209
+ senderMemberId: r.senderMemberId,
210
+ addresseeMemberId: r.addresseeMemberId,
113
211
  });
212
+ const optionalString = (value) => {
213
+ if (value === undefined || value === null)
214
+ return undefined;
215
+ const result = String(value).trim();
216
+ return result || undefined;
217
+ };
218
+ const resolveRoutingMetadata = (args, config, peer) => {
219
+ const channelId = optionalString(args.channelId) ?? optionalString(peer.channelId);
220
+ const senderMemberId = optionalString(args.senderMemberId) ?? optionalString(config.memberId);
221
+ const addresseeMemberId = optionalString(args.addresseeMemberId) ?? optionalString(peer.memberId);
222
+ if (!channelId && !senderMemberId && !addresseeMemberId)
223
+ return {};
224
+ if (!channelId || !senderMemberId) {
225
+ throw new Error("channelId and senderMemberId are required together for structured routing");
226
+ }
227
+ return { channelId, senderMemberId, addresseeMemberId };
228
+ };
114
229
  // --- Tool handlers ---
230
+ const CONFIG_TOOLS = new Set(["murmur_send", "murmur_request", "murmur_inbox", "murmur_peers",
231
+ "channel_presence_heartbeat", "channel_presence_leave"]);
115
232
  const handleTool = async (name, args) => {
233
+ const startedAt = Date.now();
234
+ // Capture one immutable snapshot for this call. Another concurrent request may
235
+ // refresh the peer list without changing the keys/routing of this in-flight call.
236
+ let agentConfig = CONFIG_TOOLS.has(name) ? configCache.read() : null;
237
+ if (agentConfig && (name === "murmur_send" || name === "murmur_request")
238
+ && !Object.hasOwn(agentConfig.peers, String(args.to ?? "").trim()))
239
+ agentConfig = configCache.read(true);
240
+ if (agentConfig && !outbox)
241
+ outbox = new SQLiteDedupeOutboxStore(dbPath);
116
242
  // === Original tools ===
117
243
  if (name === "send_message") {
118
244
  const text = String(args.text ?? "").trim();
@@ -187,6 +313,31 @@ const handleTool = async (name, args) => {
187
313
  throw new Error("channelId is required");
188
314
  return { members: channelRoster.listChannelMembers(channelId) };
189
315
  }
316
+ if (name === "channel_presence") {
317
+ const channelId = String(args.channelId ?? "").trim();
318
+ if (!channelId)
319
+ throw new Error("channelId is required");
320
+ return { scope: "local", sessions: channelRoster.listChannelPresence(channelId) };
321
+ }
322
+ if (name === "channel_presence_heartbeat" || name === "channel_presence_leave") {
323
+ if (!agentConfig)
324
+ throw new Error("agent config not loaded — presence requires a local agent identity");
325
+ if (args.agentId !== undefined || args.sessionId !== undefined)
326
+ throw new Error("presence identity is bound to this MCP server");
327
+ const identity = {
328
+ channelId: String(args.channelId ?? "").trim(),
329
+ memberId: String(args.memberId ?? agentConfig.memberId ?? "").trim(),
330
+ agentId: agentConfig.agentId,
331
+ sessionId: presenceSessionId,
332
+ };
333
+ if (name === "channel_presence_leave")
334
+ return { left: channelRoster.leaveChannelSession(identity) };
335
+ return { scope: "local", presence: channelRoster.heartbeatChannelSession({
336
+ ...identity,
337
+ status: args.status,
338
+ ttlMs: args.ttlMs,
339
+ }) };
340
+ }
190
341
  if (name === "channel_evaluate_addressing") {
191
342
  const selfAgentId = String(args.selfAgentId ?? "").trim();
192
343
  if (!selfAgentId)
@@ -196,6 +347,7 @@ const handleTool = async (name, args) => {
196
347
  channelId: args.channelId === undefined ? undefined : String(args.channelId),
197
348
  selfAgentId,
198
349
  senderAgentId: args.senderAgentId === undefined ? undefined : String(args.senderAgentId),
350
+ senderMemberId: args.senderMemberId === undefined ? undefined : String(args.senderMemberId),
199
351
  addresseeMemberId: args.addresseeMemberId === undefined ? undefined : String(args.addresseeMemberId),
200
352
  addresseeAgentId: args.addresseeAgentId === undefined ? undefined : String(args.addresseeAgentId),
201
353
  }),
@@ -211,11 +363,16 @@ const handleTool = async (name, args) => {
211
363
  const text = String(args.text ?? "").trim();
212
364
  if (!text)
213
365
  throw new Error("'text' is required");
214
- const peer = agentConfig.peers[to];
366
+ const peer = Object.hasOwn(agentConfig.peers, to) ? agentConfig.peers[to] : undefined;
215
367
  if (!peer)
216
368
  throw new Error(`unknown peer: ${to} — add to peers in agent-config.json`);
217
- const conversationId = String(args.conversationId ?? `dm:${agentConfig.agentId}:${to}`);
369
+ const conversationId = String(args.conversationId ?? defaultPeerConversationId({
370
+ to,
371
+ agentId: agentConfig.agentId,
372
+ codexThreadId: process.env.CODEX_THREAD_ID,
373
+ }));
218
374
  const msgId = randomUUID();
375
+ const routing = resolveRoutingMetadata(args, agentConfig, peer);
219
376
  // Encrypt
220
377
  const encrypted = await encryptPayload(text, peer.encryption.publicKey, agentConfig.keys.encryption.privateKey);
221
378
  // Build envelope
@@ -229,11 +386,13 @@ const handleTool = async (name, args) => {
229
386
  payloadCiphertext: encrypted.ciphertext,
230
387
  payloadNonce: encrypted.nonce,
231
388
  signature: "",
389
+ ...routing,
232
390
  };
233
391
  // Sign
234
392
  envelope.signature = await signEnvelope(stableEnvelopePayload(envelope), agentConfig.keys.signing.privateKey);
235
393
  // Enqueue to outbox — daemon will flush to NATS
236
- await outbox.enqueue(peer.subject, envelope);
394
+ await outbox.enqueue(resolveMessageSubject(peer, routing.channelId), envelope);
395
+ recordCodexTaskPeerBinding(conversationId, to);
237
396
  // Store outbound copy in message store
238
397
  await store.append({
239
398
  conversationId,
@@ -243,20 +402,21 @@ const handleTool = async (name, args) => {
243
402
  text,
244
403
  createdAt: envelope.createdAt,
245
404
  transport: "nats",
405
+ ...routing,
246
406
  });
247
- return { msgId, to, conversationId, status: "queued" };
407
+ return { msgId, to, conversationId, status: "queued", ...routing };
248
408
  }
249
409
  if (name === "murmur_inbox") {
250
410
  if (!agentConfig)
251
411
  throw new Error("agent config not loaded — run agent-config-init.mjs first");
252
412
  const limit = Number(args.limit ?? 20);
253
413
  const effectiveLimit = Number.isFinite(limit) ? limit : 20;
254
- // Search inbound messages for this agent
255
- const messages = await store.searchMessages(agentConfig.agentId, effectiveLimit * 5);
256
- // Filter to only inbound messages
257
- const inbound = messages
258
- .filter((m) => m.direction === "inbound")
259
- .slice(0, effectiveLimit);
414
+ // Select by direction, not by a text search for the agent's own name: this store
415
+ // belongs to one agent, so every inbound row in it is addressed to that agent.
416
+ // The old searchMessages(agentId) form was a LIKE over text/sender/conversationId
417
+ // and silently returned count:0 for any message that did not spell out the agent's
418
+ // name — delivered, acked, present in local_messages, invisible to the inbox (#114).
419
+ const inbound = await store.listInbound(effectiveLimit);
260
420
  return { messages: inbound.map(asMessage), count: inbound.length };
261
421
  }
262
422
  if (name === "murmur_request") {
@@ -268,14 +428,18 @@ const handleTool = async (name, args) => {
268
428
  const text = String(args.text ?? "").trim();
269
429
  if (!text)
270
430
  throw new Error("'text' is required");
271
- const peer = agentConfig.peers[to];
431
+ const peer = Object.hasOwn(agentConfig.peers, to) ? agentConfig.peers[to] : undefined;
272
432
  if (!peer)
273
433
  throw new Error(`unknown peer: ${to} — add to peers in agent-config.json`);
274
- const timeoutMs = Number(args.timeout_ms ?? 300_000);
275
- const pollMs = Number(args.poll_interval_ms ?? 10_000);
276
- const conversationId = String(args.conversationId ?? `dm:${agentConfig.agentId}:${to}`);
434
+ const { requestedTimeoutMs, timeoutMs, pollMs, graceMs } = requestTiming(args);
435
+ const conversationId = String(args.conversationId ?? defaultPeerConversationId({
436
+ to,
437
+ agentId: agentConfig.agentId,
438
+ codexThreadId: process.env.CODEX_THREAD_ID,
439
+ }));
277
440
  const msgId = randomUUID();
278
441
  const sentAt = new Date().toISOString();
442
+ const routing = resolveRoutingMetadata(args, agentConfig, peer);
279
443
  // Encrypt
280
444
  const encrypted = await encryptPayload(text, peer.encryption.publicKey, agentConfig.keys.encryption.privateKey);
281
445
  // Build envelope
@@ -289,60 +453,64 @@ const handleTool = async (name, args) => {
289
453
  payloadCiphertext: encrypted.ciphertext,
290
454
  payloadNonce: encrypted.nonce,
291
455
  signature: "",
456
+ ...routing,
292
457
  };
293
458
  // Sign
294
459
  envelope.signature = await signEnvelope(stableEnvelopePayload(envelope), agentConfig.keys.signing.privateKey);
295
460
  // Enqueue to outbox
296
- await outbox.enqueue(peer.subject, envelope);
461
+ const suppressionMarker = armSynchronousReplySuppression(conversationId, to, timeoutMs);
462
+ try {
463
+ await outbox.enqueue(resolveMessageSubject(peer, routing.channelId), envelope);
464
+ recordCodexTaskPeerBinding(conversationId, to);
465
+ }
466
+ catch (error) {
467
+ clearSynchronousReplySuppression(suppressionMarker);
468
+ throw error;
469
+ }
297
470
  // Store outbound copy
298
- await store.append({
299
- conversationId,
300
- msgId,
301
- direction: "outbound",
302
- sender: agentConfig.agentId,
303
- text,
304
- createdAt: sentAt,
305
- transport: "nats",
306
- });
471
+ try {
472
+ await store.append({
473
+ conversationId,
474
+ msgId,
475
+ direction: "outbound",
476
+ sender: agentConfig.agentId,
477
+ text,
478
+ createdAt: sentAt,
479
+ transport: "nats",
480
+ ...routing,
481
+ });
482
+ }
483
+ catch (error) {
484
+ clearSynchronousReplySuppression(suppressionMarker);
485
+ throw error;
486
+ }
307
487
  // Wait for the reply. Store polling is the durable fallback and always runs;
308
488
  // an optional read-only NATS tap on our own subject accelerates the wait by
309
489
  // re-checking the store as soon as a matching envelope is observed. The tap is
310
490
  // signal-only — the daemon stays the source of truth for decrypt + persistence.
311
- const graceMs = Number(args.grace_ms ?? 250);
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
- };
491
+ const deadline = startedAt + timeoutMs;
492
+ const matchReply = buildReplyMatcher(conversationId, to, routing.addresseeMemberId);
493
+ const snapshot = agentConfig;
494
+ const subjects = [snapshot.subject];
495
+ if (snapshot.subjectScoping?.enabled === true && routing.channelId)
496
+ subjects.push(channelScopedSubject(snapshot.subject, routing.channelId));
497
+ const tap = {};
321
498
  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
- }
499
+ const onSignal = (wake) => {
500
+ tap.current = createReplySignalTap(() => getWakeBroker(snapshot), subjects, env => {
501
+ if (matchReply(env)) {
502
+ wokenBySignal = true;
503
+ wake();
504
+ }
505
+ });
506
+ };
340
507
  let reply = null;
341
508
  try {
342
509
  reply = await waitForReply({
343
510
  checkStore: async () => {
344
- const inbound = await store.getInboundAfter(conversationId, sentAt, 1);
345
- return inbound.length > 0 ? inbound[0] : null;
511
+ const inbound = await store.getInboundAfter(conversationId, sentAt, 100);
512
+ return inbound.find((row) => row.sender === to &&
513
+ (!routing.addresseeMemberId || row.senderMemberId === routing.addresseeMemberId)) ?? null;
346
514
  },
347
515
  pollMs,
348
516
  graceMs,
@@ -350,39 +518,40 @@ const handleTool = async (name, args) => {
350
518
  onSignal,
351
519
  });
352
520
  }
521
+ catch (error) {
522
+ clearSynchronousReplySuppression(suppressionMarker);
523
+ throw error;
524
+ }
353
525
  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
- }
363
- }
526
+ tap.current?.close();
364
527
  }
365
528
  if (reply) {
529
+ shortenSynchronousReplySuppression(suppressionMarker);
366
530
  return {
367
531
  status: "received",
368
532
  msgId,
369
533
  conversationId,
370
534
  sentAt,
535
+ ...routing,
371
536
  reply: asMessage(reply),
372
537
  // Precise telemetry (per CODEX-VOLT review): tapAttached = the read-only NATS
373
538
  // tap was live for this wait; wokenBySignal = a matching envelope actually
374
539
  // short-circuited the poll (true acceleration, not merely "broker available").
375
- tapAttached: tap.sub !== null,
540
+ tapAttached: tap.current?.hasAttached() ?? false,
376
541
  wokenBySignal,
377
542
  };
378
543
  }
544
+ clearSynchronousReplySuppression(suppressionMarker);
379
545
  return {
380
- status: "timeout",
546
+ status: "awaiting_reply",
381
547
  msgId,
382
548
  conversationId,
383
549
  sentAt,
550
+ ...routing,
384
551
  timeout_ms: timeoutMs,
385
- hint: "Use murmur_inbox to check for late responses",
552
+ requested_timeout_ms: requestedTimeoutMs,
553
+ delivery: requestDelivery((await outbox.getOutboxRecord(msgId))?.status),
554
+ hint: "No reply yet. Use murmur_inbox and match conversationId to read a later reply; do not resend this request.",
386
555
  };
387
556
  }
388
557
  if (name === "murmur_peers") {
@@ -391,6 +560,8 @@ const handleTool = async (name, args) => {
391
560
  const peerList = Object.entries(agentConfig.peers).map(([id, p]) => ({
392
561
  agentId: id,
393
562
  subject: p.subject,
563
+ channelId: p.channelId,
564
+ memberId: p.memberId,
394
565
  hasEncryptionKey: !!p.encryption?.publicKey,
395
566
  hasSigningKey: !!p.signing?.publicKey,
396
567
  }));
@@ -499,12 +670,41 @@ const tools = [
499
670
  channelId: { type: "string" },
500
671
  selfAgentId: { type: "string" },
501
672
  senderAgentId: { type: "string" },
673
+ senderMemberId: { type: "string" },
502
674
  addresseeMemberId: { type: "string" },
503
675
  addresseeAgentId: { type: "string" },
504
676
  },
505
677
  required: ["selfAgentId"],
506
678
  },
507
679
  },
680
+ {
681
+ name: "channel_presence",
682
+ description: "List unexpired local chat-session presence for a channel. Advisory only; not peer liveness or lease ownership.",
683
+ inputSchema: {
684
+ type: "object", properties: { channelId: { type: "string" } }, required: ["channelId"],
685
+ },
686
+ },
687
+ {
688
+ name: "channel_presence_heartbeat",
689
+ description: "Report this local chat session in an existing channel. Repeat before TTL expires; does not claim a lease or grant membership.",
690
+ inputSchema: {
691
+ type: "object", additionalProperties: false,
692
+ properties: {
693
+ channelId: { type: "string" },
694
+ memberId: { type: "string", description: "Existing local agent member; defaults to configured memberId" },
695
+ status: { type: "string", enum: ["active", "idle", "busy"] },
696
+ ttlMs: { type: "integer", minimum: 5000, maximum: 300000, default: 30000 },
697
+ }, required: ["channelId"],
698
+ },
699
+ },
700
+ {
701
+ name: "channel_presence_leave",
702
+ description: "Remove this local chat session from the channel presence list without changing roster membership or leases.",
703
+ inputSchema: {
704
+ type: "object", additionalProperties: false,
705
+ properties: { channelId: { type: "string" }, memberId: { type: "string" } }, required: ["channelId"],
706
+ },
707
+ },
508
708
  {
509
709
  name: "murmur_send",
510
710
  description: "Send an encrypted, signed message to another agent via NATS. Message is queued in outbox and delivered by murmur-daemon.",
@@ -513,21 +713,27 @@ const tools = [
513
713
  properties: {
514
714
  to: { type: "string", description: "Recipient agent ID (must be in peers config)" },
515
715
  text: { type: "string", description: "Message text (will be encrypted)" },
516
- conversationId: { type: "string", description: "Optional conversation ID" },
716
+ conversationId: { type: "string", description: "Optional conversation ID. In Codex Desktop, omission automatically binds replies to the current task." },
717
+ channelId: { type: "string", description: "Optional typed-channel ID; may default from peer config" },
718
+ senderMemberId: { type: "string", description: "Optional sender member identity; may default from local config" },
719
+ addresseeMemberId: { type: "string", description: "Optional target member identity; may default from peer config" },
517
720
  },
518
721
  required: ["to", "text"],
519
722
  },
520
723
  },
521
724
  {
522
725
  name: "murmur_request",
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.",
726
+ description: "Send a message and wait up to 45 seconds for the reply, using the durable local store and an optional NATS tap. A slower reply returns a normal awaiting_reply result with delivery status and conversationId. Read later replies with murmur_inbox; do not resend. Delivery is confirmed only by an ACK, and does not prove automatic agent wake.",
524
727
  inputSchema: {
525
728
  type: "object",
526
729
  properties: {
527
730
  to: { type: "string", description: "Recipient agent ID (must be in peers config)" },
528
731
  text: { type: "string", description: "Message text (will be encrypted)" },
529
- conversationId: { type: "string", description: "Optional conversation ID" },
530
- timeout_ms: { type: "number", description: "Max wait time in ms (default: 300000 = 5 min)" },
732
+ conversationId: { type: "string", description: "Optional conversation ID. In Codex Desktop, omission automatically binds replies to the current task." },
733
+ channelId: { type: "string", description: "Optional typed-channel ID; may default from peer config" },
734
+ senderMemberId: { type: "string", description: "Optional sender member identity; may default from local config" },
735
+ addresseeMemberId: { type: "string", description: "Optional target member identity; may default from peer config" },
736
+ timeout_ms: { type: "number", description: "Max wait time in ms (default and cap: 45000); larger values are capped to fit desktop host tool limits" },
531
737
  poll_interval_ms: { type: "number", description: "Store-poll fallback interval in ms (default: 10000 = 10s)" },
532
738
  grace_ms: { type: "number", description: "Delay after a wake signal before re-checking the store, to let the daemon persist (default: 250)" },
533
739
  },
@@ -1,4 +1,28 @@
1
- import type { LocalMessageRecord } from "@murmurv2/core";
1
+ import type { EnvelopeV1, LocalMessageRecord, OutboxStatus } from "@murmurv2/core";
2
+ export declare const MAX_REQUEST_WAIT_MS = 45000;
3
+ export declare function requestTiming(args: Record<string, unknown>): {
4
+ requestedTimeoutMs: number;
5
+ timeoutMs: number;
6
+ pollMs: number;
7
+ graceMs: number;
8
+ };
9
+ export declare function requestDelivery(status: OutboxStatus | undefined): {
10
+ status: string;
11
+ acknowledged: boolean;
12
+ outboxStatus: string;
13
+ };
14
+ interface SignalSubscription {
15
+ unsubscribe(): void | Promise<void>;
16
+ }
17
+ interface SignalBroker {
18
+ subscribeRaw(subject: string, onEnvelope: (envelope: EnvelopeV1) => void): Promise<SignalSubscription>;
19
+ }
20
+ /** Optional acceleration never blocks store polling or completion, even while
21
+ * connecting. A subscription that attaches after close is immediately released. */
22
+ export declare function createReplySignalTap(connect: () => Promise<SignalBroker | null>, subjects: string[], onEnvelope: (envelope: EnvelopeV1) => void): {
23
+ hasAttached: () => boolean;
24
+ close: () => void;
25
+ };
2
26
  /**
3
27
  * Pure wait-loop for the request/reply ("native-request-reply") flow.
4
28
  *
@@ -40,7 +64,9 @@ export declare function waitForReply(deps: ReplyWaiterDeps): Promise<LocalMessag
40
64
  * same conversation AND sent by the peer we are waiting on. Envelope metadata is
41
65
  * plaintext (conversationId / senderAgentId), so this needs no decryption.
42
66
  */
43
- export declare const buildReplyMatcher: (conversationId: string, fromAgentId: string) => (envelope: {
67
+ export declare const buildReplyMatcher: (conversationId: string, fromAgentId: string, fromMemberId?: string) => (envelope: {
44
68
  conversationId: string;
45
69
  senderAgentId: string;
70
+ senderMemberId?: string;
46
71
  }) => boolean;
72
+ export {};
@@ -1,3 +1,54 @@
1
+ // Leave room below desktop hosts' common 60-second tool limit. A larger caller
2
+ // timeout must not turn a healthy but slower peer into a host-level tool error.
3
+ export const MAX_REQUEST_WAIT_MS = 45_000;
4
+ export function requestTiming(args) {
5
+ const number = (key, fallback, minimum) => {
6
+ const value = args[key] ?? fallback;
7
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < minimum) {
8
+ throw new Error(`${key} must be an integer >= ${minimum}`);
9
+ }
10
+ return value;
11
+ };
12
+ const requestedTimeoutMs = number("timeout_ms", MAX_REQUEST_WAIT_MS, 1);
13
+ const timeoutMs = Math.min(requestedTimeoutMs, MAX_REQUEST_WAIT_MS);
14
+ return { requestedTimeoutMs, timeoutMs,
15
+ pollMs: Math.min(number("poll_interval_ms", 10_000, 1), timeoutMs),
16
+ graceMs: Math.min(number("grace_ms", 250, 0), timeoutMs) };
17
+ }
18
+ export function requestDelivery(status) {
19
+ return { status: status === "acked" ? "delivered" : status === "dlq" ? "failed" : status ? "pending" : "unknown",
20
+ acknowledged: status === "acked", outboxStatus: status ?? "unknown" };
21
+ }
22
+ /** Optional acceleration never blocks store polling or completion, even while
23
+ * connecting. A subscription that attaches after close is immediately released. */
24
+ export function createReplySignalTap(connect, subjects, onEnvelope) {
25
+ let closed = false, attached = false;
26
+ const subscriptions = [];
27
+ const release = (sub) => {
28
+ try {
29
+ void Promise.resolve(sub.unsubscribe()).catch(() => { });
30
+ }
31
+ catch { /* optional tap */ }
32
+ };
33
+ void Promise.resolve().then(connect).then(async (broker) => {
34
+ if (!broker || closed)
35
+ return;
36
+ await Promise.all(subjects.map(async (subject) => {
37
+ try {
38
+ const sub = await broker.subscribeRaw(subject, envelope => { if (!closed)
39
+ onEnvelope(envelope); });
40
+ if (closed)
41
+ release(sub);
42
+ else {
43
+ attached = true;
44
+ subscriptions.push(sub);
45
+ }
46
+ }
47
+ catch { /* Store polling remains the durable fallback. */ }
48
+ }));
49
+ }).catch(() => { });
50
+ return { hasAttached: () => attached, close: () => { closed = true; subscriptions.splice(0).forEach(release); } };
51
+ }
1
52
  export async function waitForReply(deps) {
2
53
  const now = deps.now ?? (() => Date.now());
3
54
  const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
@@ -37,4 +88,6 @@ export async function waitForReply(deps) {
37
88
  * same conversation AND sent by the peer we are waiting on. Envelope metadata is
38
89
  * plaintext (conversationId / senderAgentId), so this needs no decryption.
39
90
  */
40
- export const buildReplyMatcher = (conversationId, fromAgentId) => (envelope) => envelope.conversationId === conversationId && envelope.senderAgentId === fromAgentId;
91
+ export const buildReplyMatcher = (conversationId, fromAgentId, fromMemberId) => (envelope) => envelope.conversationId === conversationId &&
92
+ envelope.senderAgentId === fromAgentId &&
93
+ (!fromMemberId || envelope.senderMemberId === fromMemberId);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@murmurv2/mcp-server",
3
- "version": "0.2.0",
3
+ "version": "0.2.3",
4
4
  "type": "module",
5
5
  "main": "dist/src/index.js",
6
6
  "types": "dist/src/index.d.ts",
@@ -9,9 +9,9 @@
9
9
  "prepack": "npm run build"
10
10
  },
11
11
  "dependencies": {
12
- "@murmurv2/broker-nats": "^0.3.0",
13
- "@murmurv2/core": "^0.4.0",
14
- "@murmurv2/security": "^0.1.0"
12
+ "@murmurv2/broker-nats": "^0.3.4",
13
+ "@murmurv2/core": "^0.6.3",
14
+ "@murmurv2/security": "^0.1.1"
15
15
  },
16
16
  "license": "MIT",
17
17
  "repository": {
@@ -27,7 +27,7 @@
27
27
  "LICENSE"
28
28
  ],
29
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",
30
+ "homepage": "https://murmurconnect.com",
31
31
  "bugs": {
32
32
  "url": "https://github.com/alexfrmn/murmur/issues"
33
33
  },