replywizard-whatsapp-mcp 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/README.md CHANGED
@@ -40,10 +40,13 @@ extension** (the hub only sees tool arguments and results).
40
40
 
41
41
  ## Setup
42
42
 
43
- ```bash
44
- cd mcp-host
45
- npm install
46
- ```
43
+ > **Recommended: the multi-agent connector.** Point your client at `rw-mcp-connector` (see
44
+ > [Multiple AI assistants at once](#multiple-ai-assistants-at-once-daemon) below) so several assistants
45
+ > can share one WhatsApp session. The single-client examples in this section still work but bind the
46
+ > port directly — only one client at a time.
47
+
48
+ Published to npm as [`replywizard-whatsapp-mcp`](https://www.npmjs.com/package/replywizard-whatsapp-mcp).
49
+ You don't install anything by hand — your AI client runs it via `npx` (requires Node.js 18+).
47
50
 
48
51
  ### Claude Desktop
49
52
 
@@ -53,8 +56,8 @@ Add to `claude_desktop_config.json`:
53
56
  {
54
57
  "mcpServers": {
55
58
  "replywizard": {
56
- "command": "node",
57
- "args": ["/absolute/path/to/Reply-Wizard-App/mcp-host/src/index.js"],
59
+ "command": "npx",
60
+ "args": ["-y", "replywizard-whatsapp-mcp"],
58
61
  "env": { "RW_MCP_PORT": "7869" }
59
62
  }
60
63
  }
@@ -64,11 +67,66 @@ Add to `claude_desktop_config.json`:
64
67
  ### Claude Code
65
68
 
66
69
  ```bash
67
- claude mcp add replywizard -- node /absolute/path/to/Reply-Wizard-App/mcp-host/src/index.js
70
+ claude mcp add replywizard -- npx -y replywizard-whatsapp-mcp
68
71
  ```
69
72
 
70
73
  `RW_MCP_PORT` is optional (defaults to `7869`); set it on both sides if you change it.
71
74
 
75
+ > **Running from source instead?** Clone the repo, `cd mcp-host && npm install`, and point your
76
+ > client at `node /absolute/path/to/mcp-host/src/index.js` rather than the `npx` command above.
77
+
78
+ ## Multiple AI assistants at once (daemon)
79
+
80
+ The `index.js` hub above binds the WebSocket port directly, so **only one AI client can use it at a
81
+ time** (a second launch hits `EADDRINUSE`). To let several clients (Claude Code + Cursor + Claude
82
+ Desktop, …) share one WhatsApp session, run the **daemon** instead:
83
+
84
+ ```
85
+ client A (HTTP) ─┐
86
+ client B (stdio)→ rw-mcp-connector ─┤→ rw-mcp-daemon ⇄ Reply Wizard extension ⇄ WhatsApp Web
87
+ client C (stdio)→ rw-mcp-connector ─┘ (one daemon; owns ws://127.0.0.1:7869, serves http://127.0.0.1:7870/mcp)
88
+ ```
89
+
90
+ - **`rw-mcp-daemon`** — long-lived; owns the extension WebSocket and serves MCP over Streamable HTTP
91
+ to any number of clients (each gets its own session). Single-instance: a second daemon exits cleanly.
92
+ - **`rw-mcp-connector`** — a stdio shim for clients that only launch a command; it auto-starts the
93
+ daemon if needed and transparently proxies. **Reads the auth token for you** (no token in your config).
94
+
95
+ **Clients that speak HTTP (e.g. Claude Code)** connect to the daemon directly — no connector needed:
96
+
97
+ ```bash
98
+ TOKEN=$(node -e "console.log(require('os').homedir())")/.replywizard-mcp/daemon-token.json # see the token
99
+ claude mcp add rw --transport http http://127.0.0.1:7870/mcp --header "Authorization: Bearer <token>"
100
+ ```
101
+
102
+ **Stdio-only clients** use the connector (auto-token, auto-start):
103
+
104
+ ```json
105
+ {
106
+ "mcpServers": {
107
+ "replywizard": { "command": "npx", "args": ["-y", "-p", "replywizard-whatsapp-mcp", "rw-mcp-connector"] }
108
+ }
109
+ }
110
+ ```
111
+
112
+ > From source: `node /abs/path/mcp-host/src/connector.js` (or `…/daemon.js` to run the daemon directly).
113
+
114
+ ### Environment variables
115
+
116
+ | Var | Default | Meaning |
117
+ |-----|---------|---------|
118
+ | `RW_MCP_PORT` | `7869` | Extension WebSocket port. |
119
+ | `RW_MCP_HTTP_PORT` | `7870` | Daemon HTTP (client) port. |
120
+ | `RW_MCP_IDLE_MS` | `1800000` | Daemon exits after this long with no sessions (`0` disables). |
121
+ | `RW_MCP_STALE_SESSION_MS` | `600000` | Reap sessions silent this long (client crashed without a clean disconnect). |
122
+
123
+ ### Auth token
124
+
125
+ The daemon generates a bearer token on first start at `~/.replywizard-mcp/daemon-token.json` (mode
126
+ `600`). Every `/mcp` request must present it (`Authorization: Bearer <token>`); `/healthz` is open.
127
+ The connector reads it automatically. **To revoke**, delete that file (the daemon mints a new one on
128
+ next start) — existing clients must pick up the new token.
129
+
72
130
  ## First-run pairing
73
131
 
74
132
  1. Open **WhatsApp Web** in the browser with Reply Wizard installed.
package/package.json CHANGED
@@ -1,10 +1,12 @@
1
1
  {
2
2
  "name": "replywizard-whatsapp-mcp",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Local MCP server that exposes WhatsApp Web (read + value tools) to AI clients via the Reply Wizard Chrome extension.",
5
5
  "type": "module",
6
6
  "bin": {
7
- "replywizard-whatsapp-mcp": "src/index.js"
7
+ "replywizard-whatsapp-mcp": "src/index.js",
8
+ "rw-mcp-daemon": "src/daemon.js",
9
+ "rw-mcp-connector": "src/connector.js"
8
10
  },
9
11
  "exports": {
10
12
  "./protocol": "./src/protocol.js"
@@ -0,0 +1,95 @@
1
+ // connector.js — stdio↔daemon proxy for MCP clients that only speak stdio (WS-A2).
2
+ //
3
+ // Clients that support HTTP transport connect to the daemon directly
4
+ // (claude mcp add rw --transport http http://127.0.0.1:7870/mcp). Clients that only
5
+ // launch a stdio command (the classic mcpServers config) launch THIS connector, which:
6
+ // 1. ensures the shared daemon is running (spawns it detached if absent), then
7
+ // 2. transparently pumps JSON-RPC frames between its stdio (facing the client) and
8
+ // a Streamable-HTTP client transport (facing the daemon).
9
+ //
10
+ // It owns no MCP logic — it relays at the transport layer, so every tool/version the
11
+ // daemon supports works without changes here. ALL logging goes to stderr (stdout is
12
+ // reserved for the MCP stdio protocol). Mirrors Kaption's `@kaptionai/mcp-extension` shim.
13
+
14
+ import { spawn } from 'node:child_process';
15
+ import { fileURLToPath } from 'node:url';
16
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
17
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
18
+ import { DEFAULT_HTTP_PORT } from './daemon.js';
19
+ import { readToken } from './daemonAuth.js';
20
+
21
+ const HOST = '127.0.0.1';
22
+ const log = (...args) => console.error('[replywizard-mcp:connector]', ...args);
23
+ const delay = (ms) => new Promise((r) => setTimeout(r, ms));
24
+
25
+ /**
26
+ * Wire two MCP transports so every message on one is forwarded to the other, in both
27
+ * directions, and a close/error on either tears down the pair. Pure plumbing — no
28
+ * protocol knowledge. Returns nothing; assign the transports' lifecycle to the caller.
29
+ */
30
+ export function pumpTransports(clientFacing, daemonFacing) {
31
+ clientFacing.onmessage = (msg) => { daemonFacing.send(msg).catch((e) => log('→daemon send failed:', e && e.message)); };
32
+ daemonFacing.onmessage = (msg) => { clientFacing.send(msg).catch((e) => log('→client send failed:', e && e.message)); };
33
+ clientFacing.onclose = () => { daemonFacing.close().catch(() => {}); };
34
+ daemonFacing.onclose = () => { clientFacing.close().catch(() => {}); };
35
+ clientFacing.onerror = (e) => log('client transport error:', e && e.message);
36
+ daemonFacing.onerror = (e) => log('daemon transport error:', e && e.message);
37
+ }
38
+
39
+ /**
40
+ * Poll the daemon's /healthz until it responds OK or the timeout elapses.
41
+ * @returns {Promise<boolean>} true if the daemon became reachable
42
+ */
43
+ export async function waitForDaemon(healthUrl, { timeout = 10000, interval = 200, fetchImpl = fetch, now = Date.now } = {}) {
44
+ const deadline = now() + timeout;
45
+ for (;;) {
46
+ try { const r = await fetchImpl(healthUrl); if (r && r.ok) return true; } catch { /* not up yet */ }
47
+ if (now() >= deadline) return false;
48
+ await delay(interval);
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Ensure a daemon is reachable: if /healthz already answers, do nothing; otherwise call
54
+ * spawnDaemon() and wait for it to come up.
55
+ * @returns {Promise<'already-running'|'spawned'>}
56
+ */
57
+ export async function ensureDaemon({ healthUrl, spawnDaemon, fetchImpl = fetch, waitOpts } = {}) {
58
+ try { const r = await fetchImpl(healthUrl); if (r && r.ok) return 'already-running'; } catch { /* fall through to spawn */ }
59
+ spawnDaemon();
60
+ const up = await waitForDaemon(healthUrl, { fetchImpl, ...(waitOpts || {}) });
61
+ if (!up) throw new Error('Reply Wizard MCP daemon did not become ready in time.');
62
+ return 'spawned';
63
+ }
64
+
65
+ // Spawn the daemon as a detached, fully background process that outlives this connector.
66
+ function spawnDetachedDaemon() {
67
+ const daemonPath = fileURLToPath(new URL('./daemon.js', import.meta.url));
68
+ const child = spawn(process.execPath, [daemonPath], { detached: true, stdio: 'ignore', env: process.env });
69
+ child.unref();
70
+ log('Started the Reply Wizard MCP daemon.');
71
+ }
72
+
73
+ export async function main() {
74
+ const httpPort = Number(process.env.RW_MCP_HTTP_PORT) || DEFAULT_HTTP_PORT;
75
+ const base = `http://${HOST}:${httpPort}`;
76
+
77
+ await ensureDaemon({ healthUrl: `${base}/healthz`, spawnDaemon: spawnDetachedDaemon });
78
+
79
+ // Read the daemon's auth token AFTER it is up (the daemon writes it at startup).
80
+ const token = readToken();
81
+ const opts = token ? { requestInit: { headers: { Authorization: `Bearer ${token}` } } } : undefined;
82
+
83
+ const clientFacing = new StdioServerTransport();
84
+ const daemonFacing = new StreamableHTTPClientTransport(new URL(`${base}/mcp`), opts);
85
+ pumpTransports(clientFacing, daemonFacing);
86
+
87
+ await daemonFacing.start();
88
+ await clientFacing.start();
89
+ log(`Connector ready. Proxying stdio ↔ ${base}/mcp`);
90
+ }
91
+
92
+ // Run only when invoked directly as the bin entry (not when imported by tests).
93
+ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
94
+ main().catch((err) => { log('Fatal:', (err && err.stack) || err); process.exit(1); });
95
+ }
package/src/daemon.js ADDED
@@ -0,0 +1,234 @@
1
+ // daemon.js — long-lived multi-client MCP daemon (Option A, WS-A1).
2
+ //
3
+ // The original index.js binds ONE stdio client and ONE extension WebSocket per
4
+ // process, so two AI clients fight over the port (the v3.1.5 EADDRINUSE case). This
5
+ // daemon instead:
6
+ // • owns a single ExtensionBridge (the extension dials into ws://127.0.0.1:7869), and
7
+ // • serves MCP over Streamable HTTP at http://127.0.0.1:7870/mcp to ANY number of
8
+ // clients — each client gets its own MCP session (a fresh Server + transport),
9
+ // and they all share the one extension bridge.
10
+ //
11
+ // Clients connect either directly (claude mcp add rw --transport http
12
+ // http://127.0.0.1:7870/mcp) or through the stdio connector shim (WS-A2).
13
+ //
14
+ // Concurrency: each session's tool calls go through bridge.callAction(), which already
15
+ // correlates responses by a per-request id, so interleaved calls from multiple sessions
16
+ // resolve to the right caller. Fairness/queueing refinements are WS-A3.
17
+ //
18
+ // stdout is irrelevant here (HTTP transport); ALL logging goes to stderr.
19
+
20
+ import http from 'node:http';
21
+ import { randomUUID } from 'node:crypto';
22
+ import { fileURLToPath } from 'node:url';
23
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
24
+ import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
25
+ import { ExtensionBridge } from './wsServer.js';
26
+ import { createMcpServer } from './mcpServer.js';
27
+ import { DEFAULT_PORT } from './protocol.js';
28
+ import { loadOrCreateToken, tokenMatches, bearerFrom } from './daemonAuth.js';
29
+
30
+ // Daemon-only (not part of the extension wire contract, so it lives here rather than
31
+ // in protocol.js). Overridable via env for users who run more than one profile.
32
+ export const DEFAULT_HTTP_PORT = 7870;
33
+ const MAX_BODY_BYTES = 4 * 1024 * 1024;
34
+ const HOST = '127.0.0.1';
35
+
36
+ const log = (...args) => console.error('[replywizard-mcp]', ...args);
37
+
38
+ // Read and JSON-parse a request body, bounded. Resolves undefined for an empty body.
39
+ function readJsonBody(req, limit = MAX_BODY_BYTES) {
40
+ return new Promise((resolve, reject) => {
41
+ let size = 0;
42
+ const chunks = [];
43
+ req.on('data', (c) => {
44
+ size += c.length;
45
+ if (size > limit) { reject(new Error('Request body too large')); req.destroy(); return; }
46
+ chunks.push(c);
47
+ });
48
+ req.on('end', () => {
49
+ const raw = Buffer.concat(chunks).toString('utf8');
50
+ if (!raw) { resolve(undefined); return; }
51
+ try { resolve(JSON.parse(raw)); } catch { reject(new Error('Invalid JSON body')); }
52
+ });
53
+ req.on('error', reject);
54
+ });
55
+ }
56
+
57
+ function writeJson(res, status, obj) {
58
+ res.writeHead(status, { 'content-type': 'application/json' });
59
+ res.end(JSON.stringify(obj));
60
+ }
61
+
62
+ function rpcError(res, status, message) {
63
+ writeJson(res, status, { jsonrpc: '2.0', error: { code: -32000, message }, id: null });
64
+ }
65
+
66
+ /**
67
+ * Create the daemon's HTTP server (does not listen until .listen() is called).
68
+ * @param {{ bridge: object, httpPort?: number, host?: string, authToken?: string,
69
+ * idleMs?: number, staleSessionMs?: number, sweepIntervalMs?: number,
70
+ * onIdle?: Function, now?: () => number }} opts
71
+ * @returns {{ httpServer, sessions, listen, close, sweep }}
72
+ */
73
+ export function createDaemon({
74
+ bridge, httpPort = DEFAULT_HTTP_PORT, host = HOST, authToken,
75
+ idleMs = 0, staleSessionMs = 0, sweepIntervalMs = 60_000, onIdle = () => {}, now = Date.now,
76
+ } = {}) {
77
+ const sessions = new Map(); // sessionId → { transport, server, lastSeen }
78
+ // Client-auth token (WS-A4): clients must present `Authorization: Bearer <token>`.
79
+ // Defaults to the persisted local token; tests inject an explicit one.
80
+ const token = authToken || loadOrCreateToken();
81
+ let lastActivityAt = now(); // last /mcp request time, for idle-exit (WS-A5)
82
+ let sweepTimer = null;
83
+
84
+ // Build the DNS-rebinding allowlist from the ACTUAL bound port (supports
85
+ // ephemeral port 0 in tests). The server only binds loopback.
86
+ const allowedHosts = () => {
87
+ const addr = httpServer.address();
88
+ const port = (addr && typeof addr === 'object') ? addr.port : httpPort;
89
+ return [`127.0.0.1:${port}`, `localhost:${port}`];
90
+ };
91
+
92
+ async function newSession(req, res, body) {
93
+ // Capture the session id at init: transport.sessionId may already be cleared by
94
+ // the time onclose fires, so we must not rely on it for cleanup.
95
+ let sid = null;
96
+ const transport = new StreamableHTTPServerTransport({
97
+ sessionIdGenerator: () => randomUUID(),
98
+ enableDnsRebindingProtection: true,
99
+ allowedHosts: allowedHosts(),
100
+ onsessioninitialized: (id) => { sid = id; sessions.set(id, { transport, server, lastSeen: now() }); },
101
+ });
102
+ transport.onclose = () => { if (sid) sessions.delete(sid); };
103
+ const server = createMcpServer(bridge);
104
+ await server.connect(transport);
105
+ await transport.handleRequest(req, res, body);
106
+ }
107
+
108
+ async function handle(req, res) {
109
+ let url;
110
+ try { url = new URL(req.url, `http://${req.headers.host || `${host}:${httpPort}`}`); }
111
+ catch { rpcError(res, 400, 'Bad request URL'); return; }
112
+
113
+ if (url.pathname === '/healthz') {
114
+ const connected = !!(bridge && bridge.socket && bridge.socket.readyState === 1);
115
+ writeJson(res, 200, { ok: true, extensionConnected: connected, paired: !!(bridge && bridge.paired), sessions: sessions.size });
116
+ return;
117
+ }
118
+ if (url.pathname !== '/mcp') { rpcError(res, 404, 'Not found. MCP endpoint is /mcp'); return; }
119
+
120
+ // Auth gate (WS-A4): every /mcp request must carry the bearer token.
121
+ if (!tokenMatches(bearerFrom(req.headers.authorization), token)) {
122
+ rpcError(res, 401, 'Unauthorized: missing or invalid Reply Wizard MCP token.');
123
+ return;
124
+ }
125
+
126
+ lastActivityAt = now(); // any authed /mcp activity defers idle-exit (WS-A5)
127
+ const sessionId = req.headers['mcp-session-id'];
128
+ const existing = (sessionId && sessions.has(sessionId)) ? sessions.get(sessionId) : null;
129
+ if (existing) existing.lastSeen = now(); // defer stale-session cleanup
130
+
131
+ if (req.method === 'POST') {
132
+ let body;
133
+ try { body = await readJsonBody(req); } catch (e) { rpcError(res, 400, (e && e.message) || 'Invalid body'); return; }
134
+ if (existing) { await existing.transport.handleRequest(req, res, body); return; }
135
+ if (!sessionId && isInitializeRequest(body)) { await newSession(req, res, body); return; }
136
+ rpcError(res, 400, 'No valid session. Send an initialize request first (no Mcp-Session-Id).');
137
+ return;
138
+ }
139
+
140
+ if (req.method === 'GET' || req.method === 'DELETE') {
141
+ if (!existing) { rpcError(res, 400, 'Missing or unknown Mcp-Session-Id'); return; }
142
+ await existing.transport.handleRequest(req, res);
143
+ return;
144
+ }
145
+
146
+ res.writeHead(405, { 'content-type': 'application/json', allow: 'GET, POST, DELETE' });
147
+ res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32000, message: 'Method Not Allowed' }, id: null }));
148
+ }
149
+
150
+ const httpServer = http.createServer((req, res) => {
151
+ handle(req, res).catch((err) => {
152
+ log('HTTP handler error:', (err && err.message) || err);
153
+ if (!res.headersSent) { try { rpcError(res, 500, 'Internal error'); } catch { /* noop */ } }
154
+ });
155
+ });
156
+
157
+ // WS-A5: close sessions that have gone silent (client crashed without DELETE), and
158
+ // signal idle-exit when there are no sessions and no recent activity. Safe to call
159
+ // anytime; returns the number of stale sessions it closed.
160
+ function sweep() {
161
+ const t = now();
162
+ let closed = 0;
163
+ if (staleSessionMs > 0) {
164
+ for (const [, s] of sessions) {
165
+ if (t - s.lastSeen > staleSessionMs) { closed++; try { s.transport.close(); } catch { /* onclose removes it */ } }
166
+ }
167
+ }
168
+ if (idleMs > 0 && sessions.size === 0 && (t - lastActivityAt) > idleMs) { onIdle(); }
169
+ return closed;
170
+ }
171
+
172
+ function listen(cb) {
173
+ httpServer.listen(httpPort, host, cb);
174
+ if ((idleMs > 0 || staleSessionMs > 0) && typeof setInterval === 'function') {
175
+ sweepTimer = setInterval(sweep, sweepIntervalMs);
176
+ if (typeof sweepTimer.unref === 'function') sweepTimer.unref();
177
+ }
178
+ return httpServer;
179
+ }
180
+
181
+ async function close() {
182
+ if (sweepTimer) { clearInterval(sweepTimer); sweepTimer = null; }
183
+ for (const { transport } of sessions.values()) { try { await transport.close(); } catch { /* noop */ } }
184
+ sessions.clear();
185
+ await new Promise((resolve) => httpServer.close(() => resolve()));
186
+ }
187
+
188
+ return { httpServer, sessions, listen, close, sweep };
189
+ }
190
+
191
+ export async function main() {
192
+ const wsPort = Number(process.env.RW_MCP_PORT) || DEFAULT_PORT;
193
+ const httpPort = Number(process.env.RW_MCP_HTTP_PORT) || DEFAULT_HTTP_PORT;
194
+ // Lifecycle knobs (WS-A5). RW_MCP_IDLE_MS=0 disables idle-exit. Defaults: exit after
195
+ // 30 min idle; reap sessions silent for 10 min (client crashed without DELETE).
196
+ const idleMs = process.env.RW_MCP_IDLE_MS != null ? Number(process.env.RW_MCP_IDLE_MS) : 30 * 60_000;
197
+ const staleSessionMs = process.env.RW_MCP_STALE_SESSION_MS != null ? Number(process.env.RW_MCP_STALE_SESSION_MS) : 10 * 60_000;
198
+ const sweepIntervalMs = process.env.RW_MCP_SWEEP_MS != null ? Number(process.env.RW_MCP_SWEEP_MS) : 60_000;
199
+
200
+ const bridge = new ExtensionBridge({ port: wsPort });
201
+ await bridge.listen(); // hardened: degrades (does not crash) if the WS port is taken
202
+
203
+ let shutdownFn = () => process.exit(0); // replaced below once daemon exists
204
+ const daemon = createDaemon({
205
+ bridge, httpPort, idleMs, staleSessionMs, sweepIntervalMs,
206
+ onIdle: () => { log(`Idle for ${Math.round(idleMs / 1000)}s with no sessions — shutting down.`); shutdownFn(); },
207
+ });
208
+
209
+ // Single-instance lock: the HTTP port is the daemon's identity. If it is taken,
210
+ // another daemon already owns it — exit cleanly rather than crash-loop.
211
+ daemon.httpServer.on('error', (err) => {
212
+ if (err && err.code === 'EADDRINUSE') {
213
+ log(`HTTP port ${httpPort} is in use — another Reply Wizard daemon is already running. Exiting.`);
214
+ try { bridge.close(); } catch { /* noop */ }
215
+ process.exit(0);
216
+ }
217
+ log('HTTP server error:', (err && err.message) || err);
218
+ });
219
+
220
+ daemon.listen(() => {
221
+ log(`MCP daemon ready. Clients → http://${HOST}:${httpPort}/mcp ; extension → ws://${HOST}:${wsPort}`);
222
+ if (bridge.portConflict) log('NOTE: extension WS bridge is degraded (port in use); action calls will report it.');
223
+ });
224
+
225
+ const shutdown = () => { daemon.close().catch(() => {}); try { bridge.close(); } catch { /* noop */ } process.exit(0); };
226
+ shutdownFn = shutdown; // wire idle-exit to the real shutdown
227
+ process.on('SIGINT', shutdown);
228
+ process.on('SIGTERM', shutdown);
229
+ }
230
+
231
+ // Run only when invoked directly as the bin entry (not when imported by tests).
232
+ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
233
+ main().catch((err) => { log('Fatal:', (err && err.stack) || err); process.exit(1); });
234
+ }
@@ -0,0 +1,73 @@
1
+ // daemonAuth.js — local client-auth token for the MCP daemon (WS-A4).
2
+ //
3
+ // The daemon listens on loopback, but any local process could otherwise reach it and
4
+ // read WhatsApp through a paired extension. This adds a bearer token that clients must
5
+ // present (Authorization: Bearer <token>) on every /mcp request:
6
+ // • the daemon generates + persists it on first start (0600, in ~/.replywizard-mcp/),
7
+ // • the stdio connector reads it automatically,
8
+ // • direct-HTTP clients put it in their MCP client config (surfaced in Options, A5).
9
+ // Rotating the token (revoke) invalidates every existing client until they re-read it.
10
+ //
11
+ // The state dir is overridable via RW_MCP_STATE_DIR (used by tests so they never touch
12
+ // the real ~/.replywizard-mcp).
13
+
14
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
15
+ import { homedir } from 'node:os';
16
+ import { join } from 'node:path';
17
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
18
+
19
+ const log = (...args) => console.error('[replywizard-mcp]', ...args);
20
+
21
+ function stateDir(dir) {
22
+ return dir || process.env.RW_MCP_STATE_DIR || join(homedir(), '.replywizard-mcp');
23
+ }
24
+ function tokenFile(dir) {
25
+ return join(stateDir(dir), 'daemon-token.json');
26
+ }
27
+
28
+ function writeToken(token, dir) {
29
+ try {
30
+ mkdirSync(stateDir(dir), { recursive: true });
31
+ writeFileSync(tokenFile(dir), JSON.stringify({ token }), { mode: 0o600 });
32
+ } catch (e) {
33
+ log('Could not persist daemon auth token:', e && e.message);
34
+ }
35
+ }
36
+
37
+ /** Read the persisted token, or null if none / unreadable. */
38
+ export function readToken(dir) {
39
+ try { return JSON.parse(readFileSync(tokenFile(dir), 'utf8')).token || null; }
40
+ catch { return null; }
41
+ }
42
+
43
+ /** Return the persisted token, creating + persisting a fresh one if absent. */
44
+ export function loadOrCreateToken(dir) {
45
+ const existing = readToken(dir);
46
+ if (existing) return existing;
47
+ const token = randomBytes(32).toString('hex');
48
+ writeToken(token, dir);
49
+ return token;
50
+ }
51
+
52
+ /** Replace the token with a fresh one (revoke). Returns the new token. */
53
+ export function rotateToken(dir) {
54
+ const token = randomBytes(32).toString('hex');
55
+ writeToken(token, dir);
56
+ return token;
57
+ }
58
+
59
+ /** Constant-time-ish comparison of a provided token against the expected one. */
60
+ export function tokenMatches(provided, expected) {
61
+ if (!provided || !expected) return false;
62
+ const a = Buffer.from(String(provided));
63
+ const b = Buffer.from(String(expected));
64
+ if (a.length !== b.length) return false;
65
+ return timingSafeEqual(a, b);
66
+ }
67
+
68
+ /** Extract a bearer token from an Authorization header value. */
69
+ export function bearerFrom(authHeader) {
70
+ if (typeof authHeader !== 'string') return null;
71
+ const m = authHeader.match(/^Bearer\s+(.+)$/i);
72
+ return m ? m[1].trim() : null;
73
+ }
package/src/index.js CHANGED
@@ -26,7 +26,12 @@ async function main() {
26
26
  const server = createMcpServer(bridge);
27
27
  const transport = new StdioServerTransport();
28
28
  await server.connect(transport);
29
- log('MCP stdio server ready. Waiting for the Reply Wizard extension to connect…');
29
+ if (bridge.portConflict) {
30
+ log('MCP stdio server ready, but the bridge is DISABLED (port in use). Tools');
31
+ log('will list, but action calls fail until the duplicate hub is closed.');
32
+ } else {
33
+ log('MCP stdio server ready. Waiting for the Reply Wizard extension to connect…');
34
+ }
30
35
 
31
36
  const shutdown = () => { try { bridge.close(); } catch { /* noop */ } process.exit(0); };
32
37
  process.on('SIGINT', shutdown);
package/src/wsServer.js CHANGED
@@ -25,27 +25,41 @@ import { WebSocketServer } from 'ws';
25
25
  import { randomBytes, randomUUID } from 'node:crypto';
26
26
  import { homedir } from 'node:os';
27
27
  import { join } from 'node:path';
28
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
29
- import { CONTROL, DEFAULT_PORT, PROTOCOL_VERSION } from './protocol.js';
28
+ import { mkdirSync, readFileSync, writeFileSync, rmSync } from 'node:fs';
29
+ import { CONTROL, DEFAULT_PORT, PROTOCOL_VERSION, VALUE_ACTIONS } from './protocol.js';
30
30
 
31
31
  const log = (...args) => console.error('[replywizard-mcp]', ...args);
32
32
 
33
- const STATE_DIR = join(homedir(), '.replywizard-mcp');
34
- const STATE_FILE = join(STATE_DIR, 'session.json');
33
+ // State dir is overridable via RW_MCP_STATE_DIR (consistent with daemonAuth.js); used
34
+ // by tests for isolation. Resolved lazily (at call time) so the env can be set before
35
+ // a bridge is constructed. Defaults to ~/.replywizard-mcp in production.
36
+ function stateDir() { return process.env.RW_MCP_STATE_DIR || join(homedir(), '.replywizard-mcp'); }
37
+ function stateFile() { return join(stateDir(), 'session.json'); }
35
38
 
36
39
  function loadToken() {
37
- try { return JSON.parse(readFileSync(STATE_FILE, 'utf8')).token || null; } catch { return null; }
40
+ try { return JSON.parse(readFileSync(stateFile(), 'utf8')).token || null; } catch { return null; }
38
41
  }
39
42
  function saveToken(token) {
40
- try { mkdirSync(STATE_DIR, { recursive: true }); writeFileSync(STATE_FILE, JSON.stringify({ token }), { mode: 0o600 }); }
43
+ try { mkdirSync(stateDir(), { recursive: true }); writeFileSync(stateFile(), JSON.stringify({ token }), { mode: 0o600 }); }
41
44
  catch (e) { log('Could not persist session token:', e && e.message); }
42
45
  }
46
+
47
+ // When the daemon runs detached (spawned by the connector, stderr → /dev/null), the
48
+ // printed pairing code is invisible. Mirror it to a file so a first-time user can read
49
+ // it (`cat ~/.replywizard-mcp/pairing-code.txt`). Cleared once pairing succeeds.
50
+ function pairingFile() { return join(stateDir(), 'pairing-code.txt'); }
51
+ function writePairingCode(code) {
52
+ try { mkdirSync(stateDir(), { recursive: true }); writeFileSync(pairingFile(), `${code}\n`, { mode: 0o600 }); }
53
+ catch { /* best-effort surfacing */ }
54
+ }
55
+ function clearPairingCode() { try { rmSync(pairingFile(), { force: true }); } catch { /* noop */ } }
43
56
  function sixDigitCode() {
44
57
  return String(parseInt(randomBytes(4).toString('hex'), 16) % 1_000_000).padStart(6, '0');
45
58
  }
46
59
 
47
60
  export class ExtensionBridge {
48
- constructor({ port = DEFAULT_PORT, host = '127.0.0.1' } = {}) {
61
+ constructor(opts = {}) {
62
+ const { port = DEFAULT_PORT, host = '127.0.0.1' } = opts;
49
63
  this.port = port;
50
64
  this.host = host;
51
65
  this.wss = null;
@@ -53,15 +67,56 @@ export class ExtensionBridge {
53
67
  this.paired = false;
54
68
  this.pairingCode = null;
55
69
  this.sessionToken = loadToken();
56
- this.pending = new Map(); // requestId → { resolve, reject, timer }
57
- this.requestTimeoutMs = 25_000;
70
+ this.pending = new Map(); // requestId → { entry, lane }
71
+ this.requestTimeoutMs = opts.requestTimeoutMs ?? 25_000;
72
+ this.listening = false;
73
+ this.portConflict = false; // true if the port was already in use at startup
74
+ // Concurrency scheduler (WS-A3): all client sessions multiplex onto the single
75
+ // extension socket. Reads and value-actions run in INDEPENDENT lanes so a slow
76
+ // value-action (transcribe/summarize/suggest → LLM/STT) never head-of-line-blocks
77
+ // quick reads; value-actions are serialized (limit 1) to protect the provider/tab.
78
+ // The per-action timeout covers queue wait + round-trip, bounding total latency.
79
+ this.lanes = {
80
+ read: { name: 'read', limit: opts.maxRead ?? 4, inFlight: 0, queue: [] },
81
+ value: { name: 'value', limit: opts.maxValue ?? 1, inFlight: 0, queue: [] },
82
+ };
83
+ this.maxQueuePerLane = opts.maxQueue ?? 100;
58
84
  }
59
85
 
60
86
  listen() {
61
87
  return new Promise((resolve, reject) => {
62
88
  this.wss = new WebSocketServer({ host: this.host, port: this.port });
63
- this.wss.on('listening', () => { log(`WebSocket server listening on ws://${this.host}:${this.port}`); resolve(); });
64
- this.wss.on('error', reject);
89
+
90
+ const onEarlyError = (err) => {
91
+ this.wss.removeListener('listening', onListening);
92
+ if (err && err.code === 'EADDRINUSE') {
93
+ // Another Reply Wizard hub already owns the port. Degrade gracefully:
94
+ // resolve so the MCP stdio server still connects (the client's
95
+ // `initialize` succeeds instead of getting EOF), but mark the bridge
96
+ // unavailable so action calls return a clear, actionable message.
97
+ this.portConflict = true;
98
+ log(`Port ${this.port} is already in use — another Reply Wizard hub is`);
99
+ log('probably already running. Starting without the WebSocket bridge;');
100
+ log('action calls will report the conflict. Close the other hub, or set');
101
+ log('RW_MCP_PORT to a free port if you intend to run more than one.');
102
+ try { this.wss.close(); } catch { /* noop */ }
103
+ this.wss = null;
104
+ resolve();
105
+ return;
106
+ }
107
+ reject(err);
108
+ };
109
+ const onListening = () => {
110
+ this.wss.removeListener('error', onEarlyError);
111
+ // Keep a persistent handler so a late error never throws unhandled.
112
+ this.wss.on('error', (e) => log('WebSocket server error:', e && e.message));
113
+ this.listening = true;
114
+ log(`WebSocket server listening on ws://${this.host}:${this.port}`);
115
+ resolve();
116
+ };
117
+
118
+ this.wss.once('error', onEarlyError);
119
+ this.wss.once('listening', onListening);
65
120
  this.wss.on('connection', (ws) => this._onConnection(ws));
66
121
  });
67
122
  }
@@ -80,7 +135,7 @@ export class ExtensionBridge {
80
135
  ws.on('message', (raw) => this._onMessage(raw));
81
136
  ws.on('close', () => {
82
137
  log('Extension disconnected.');
83
- this._failAllPending(new Error('Extension disconnected.'));
138
+ this._failAll(new Error('Extension disconnected.'));
84
139
  if (this.socket === ws) { this.socket = null; this.paired = false; }
85
140
  });
86
141
  ws.on('error', (e) => log('Socket error:', e && e.message));
@@ -98,11 +153,13 @@ export class ExtensionBridge {
98
153
  log('Reconnected with a valid session token (no pairing needed).');
99
154
  } else {
100
155
  this.pairingCode = sixDigitCode();
156
+ writePairingCode(this.pairingCode);
101
157
  log('');
102
158
  log(' ┌──────────────────────────────────────────────┐');
103
159
  log(` │ Reply Wizard pairing code: ${this.pairingCode} │`);
104
160
  log(' └──────────────────────────────────────────────┘');
105
161
  log(' Enter it in Reply Wizard → popup → AI client access.');
162
+ log(` (Running in the background? Read it from ${pairingFile()})`);
106
163
  this._send({ method: CONTROL.PAIRING_REQUEST, params: { hub_name: 'Reply Wizard MCP', protocol: PROTOCOL_VERSION } });
107
164
  }
108
165
  return;
@@ -114,6 +171,7 @@ export class ExtensionBridge {
114
171
  this.paired = true;
115
172
  this.sessionToken = randomUUID();
116
173
  saveToken(this.sessionToken);
174
+ clearPairingCode();
117
175
  this._send({ method: CONTROL.PAIRING_COMPLETE, params: { session_id: randomUUID(), session_token: this.sessionToken } });
118
176
  this._send({ method: CONTROL.AUTH_SUCCESS, params: {} });
119
177
  log('Pairing approved.');
@@ -125,43 +183,120 @@ export class ExtensionBridge {
125
183
 
126
184
  if (msg.method === CONTROL.PONG) return;
127
185
 
128
- // Action result correlation.
186
+ // Action result correlation: settle the caller, free its lane slot, pump the lane.
129
187
  if (msg.id && this.pending.has(msg.id)) {
130
- const { resolve, reject, timer } = this.pending.get(msg.id);
131
- clearTimeout(timer);
132
- this.pending.delete(msg.id);
133
- if (msg.error) reject(new Error(msg.error.message || 'Action failed'));
134
- else resolve(msg.result);
188
+ this._finishInFlight(msg.id, (entry) => {
189
+ if (msg.error) entry.reject(new Error(msg.error.message || 'Action failed'));
190
+ else entry.resolve(msg.result);
191
+ });
135
192
  }
136
193
  }
137
194
 
138
- /** Forward an action to the extension and await the result. */
195
+ /**
196
+ * Forward an action to the extension and await the result. Scheduled in a lane
197
+ * (read vs value) with bounded concurrency + per-lane backpressure; the per-action
198
+ * timeout covers queue wait + round-trip.
199
+ */
139
200
  callAction(action, params = {}) {
201
+ if (this.portConflict) {
202
+ return Promise.reject(new Error(`Another Reply Wizard hub is already using port ${this.port}. Close the duplicate MCP host (or set RW_MCP_PORT to a free port) and reconnect.`));
203
+ }
140
204
  if (!this.socket || this.socket.readyState !== this.socket.OPEN) {
141
205
  return Promise.reject(new Error('Reply Wizard extension is not connected. Open WhatsApp Web and enable AI client access in the extension.'));
142
206
  }
143
207
  if (!this.paired) {
144
208
  return Promise.reject(new Error('Not paired yet. Enter the pairing code shown above in the extension popup.'));
145
209
  }
146
- const id = randomUUID();
210
+ const lane = this._laneFor(action);
211
+ if (lane.queue.length >= this.maxQueuePerLane) {
212
+ return Promise.reject(new Error(`Reply Wizard is busy (${lane.name} queue full). Try again shortly.`));
213
+ }
147
214
  return new Promise((resolve, reject) => {
148
- const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`Action "${action}" timed out.`)); }, this.requestTimeoutMs);
149
- this.pending.set(id, { resolve, reject, timer });
150
- this._send({ id, method: 'action', action, params });
215
+ const entry = { action, params, resolve, reject, settled: false, id: null, timer: null };
216
+ entry.timer = setTimeout(() => this._timeout(entry, lane), this.requestTimeoutMs);
217
+ lane.queue.push(entry);
218
+ this._drainLane(lane);
151
219
  });
152
220
  }
153
221
 
222
+ _laneFor(action) {
223
+ return VALUE_ACTIONS.includes(action) ? this.lanes.value : this.lanes.read;
224
+ }
225
+
226
+ // Dispatch as many queued entries as the lane's concurrency limit allows.
227
+ _drainLane(lane) {
228
+ while (lane.inFlight < lane.limit && lane.queue.length > 0) {
229
+ const entry = lane.queue.shift();
230
+ if (entry.settled) continue; // timed out while queued
231
+ lane.inFlight++;
232
+ this._dispatch(entry, lane);
233
+ }
234
+ }
235
+
236
+ _dispatch(entry, lane) {
237
+ if (!this.socket || this.socket.readyState !== this.socket.OPEN) {
238
+ // Connection dropped between enqueue and dispatch.
239
+ lane.inFlight--;
240
+ if (!entry.settled) {
241
+ entry.settled = true;
242
+ clearTimeout(entry.timer);
243
+ entry.reject(new Error('Reply Wizard extension disconnected.'));
244
+ }
245
+ this._drainLane(lane);
246
+ return;
247
+ }
248
+ const id = randomUUID();
249
+ entry.id = id;
250
+ this.pending.set(id, { entry, lane });
251
+ this._send({ id, method: 'action', action: entry.action, params: entry.params });
252
+ }
253
+
254
+ // Settle an in-flight action, free its lane slot, and pump the lane.
255
+ _finishInFlight(id, settle) {
256
+ const rec = this.pending.get(id);
257
+ if (!rec) return;
258
+ this.pending.delete(id);
259
+ const { entry, lane } = rec;
260
+ clearTimeout(entry.timer);
261
+ lane.inFlight--;
262
+ if (!entry.settled) { entry.settled = true; settle(entry); }
263
+ this._drainLane(lane);
264
+ }
265
+
266
+ _timeout(entry, lane) {
267
+ if (entry.settled) return;
268
+ entry.settled = true;
269
+ const qi = lane.queue.indexOf(entry);
270
+ if (qi >= 0) lane.queue.splice(qi, 1); // timed out while still queued
271
+ if (entry.id && this.pending.has(entry.id)) { // timed out while in flight
272
+ this.pending.delete(entry.id);
273
+ lane.inFlight--;
274
+ this._drainLane(lane);
275
+ }
276
+ entry.reject(new Error(`Action "${entry.action}" timed out.`));
277
+ }
278
+
154
279
  _send(obj) {
155
280
  if (this.socket && this.socket.readyState === this.socket.OPEN) this.socket.send(JSON.stringify(obj));
156
281
  }
157
282
 
158
- _failAllPending(err) {
159
- for (const { reject, timer } of this.pending.values()) { clearTimeout(timer); reject(err); }
283
+ // Reject every queued and in-flight action (e.g. on disconnect / shutdown).
284
+ _failAll(err) {
285
+ for (const lane of Object.values(this.lanes)) {
286
+ const queued = lane.queue.splice(0);
287
+ for (const entry of queued) {
288
+ if (!entry.settled) { entry.settled = true; clearTimeout(entry.timer); entry.reject(err); }
289
+ }
290
+ lane.inFlight = 0;
291
+ }
292
+ for (const { entry } of this.pending.values()) {
293
+ if (!entry.settled) { entry.settled = true; clearTimeout(entry.timer); entry.reject(err); }
294
+ }
160
295
  this.pending.clear();
161
296
  }
162
297
 
163
298
  close() {
164
- this._failAllPending(new Error('Hub shutting down.'));
299
+ this._failAll(new Error('Hub shutting down.'));
165
300
  if (this.wss) this.wss.close();
166
301
  }
167
302
  }