replywizard-whatsapp-mcp 0.1.0 → 0.2.1
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 +65 -7
- package/package.json +4 -2
- package/src/connector.js +95 -0
- package/src/daemon.js +234 -0
- package/src/daemonAuth.js +73 -0
- package/src/index.js +6 -1
- package/src/protocol.js +1 -0
- package/src/wsServer.js +210 -27
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
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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": "
|
|
57
|
-
"args": ["
|
|
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 --
|
|
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
|
|
3
|
+
"version": "0.2.1",
|
|
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"
|
package/src/connector.js
ADDED
|
@@ -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
|
-
|
|
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/protocol.js
CHANGED
|
@@ -43,6 +43,7 @@ export const CONTROL = Object.freeze({
|
|
|
43
43
|
PAIRING_REQUEST: 'pairing_request',
|
|
44
44
|
PAIRING_RESPONSE: 'pairing_response',
|
|
45
45
|
PAIRING_COMPLETE: 'pairing_complete',
|
|
46
|
+
PAIRING_FAILED: 'pairing_failed',
|
|
46
47
|
AUTH_SUCCESS: 'auth_success',
|
|
47
48
|
PING: 'ping',
|
|
48
49
|
PONG: 'pong',
|
package/src/wsServer.js
CHANGED
|
@@ -23,29 +23,83 @@
|
|
|
23
23
|
|
|
24
24
|
import { WebSocketServer } from 'ws';
|
|
25
25
|
import { randomBytes, randomUUID } from 'node:crypto';
|
|
26
|
-
import { homedir } from 'node:os';
|
|
26
|
+
import { homedir, platform } from 'node:os';
|
|
27
27
|
import { join } from 'node:path';
|
|
28
|
-
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
29
|
-
import {
|
|
28
|
+
import { mkdirSync, readFileSync, writeFileSync, rmSync } from 'node:fs';
|
|
29
|
+
import { spawn } from 'node:child_process';
|
|
30
|
+
import { CONTROL, DEFAULT_PORT, PROTOCOL_VERSION, VALUE_ACTIONS } from './protocol.js';
|
|
30
31
|
|
|
31
32
|
const log = (...args) => console.error('[replywizard-mcp]', ...args);
|
|
32
33
|
|
|
33
|
-
|
|
34
|
-
|
|
34
|
+
// State dir is overridable via RW_MCP_STATE_DIR (consistent with daemonAuth.js); used
|
|
35
|
+
// by tests for isolation. Resolved lazily (at call time) so the env can be set before
|
|
36
|
+
// a bridge is constructed. Defaults to ~/.replywizard-mcp in production.
|
|
37
|
+
function stateDir() { return process.env.RW_MCP_STATE_DIR || join(homedir(), '.replywizard-mcp'); }
|
|
38
|
+
function stateFile() { return join(stateDir(), 'session.json'); }
|
|
35
39
|
|
|
36
40
|
function loadToken() {
|
|
37
|
-
try { return JSON.parse(readFileSync(
|
|
41
|
+
try { return JSON.parse(readFileSync(stateFile(), 'utf8')).token || null; } catch { return null; }
|
|
38
42
|
}
|
|
39
43
|
function saveToken(token) {
|
|
40
|
-
try { mkdirSync(
|
|
44
|
+
try { mkdirSync(stateDir(), { recursive: true }); writeFileSync(stateFile(), JSON.stringify({ token }), { mode: 0o600 }); }
|
|
41
45
|
catch (e) { log('Could not persist session token:', e && e.message); }
|
|
42
46
|
}
|
|
47
|
+
|
|
48
|
+
// When the daemon runs detached (spawned by the connector, stderr → /dev/null), the
|
|
49
|
+
// printed pairing code is invisible. Mirror it to a file so a first-time user can read
|
|
50
|
+
// it (`cat ~/.replywizard-mcp/pairing-code.txt`). Cleared once pairing succeeds.
|
|
51
|
+
function pairingFile() { return join(stateDir(), 'pairing-code.txt'); }
|
|
52
|
+
function writePairingCode(code) {
|
|
53
|
+
try { mkdirSync(stateDir(), { recursive: true }); writeFileSync(pairingFile(), `${code}\n`, { mode: 0o600 }); }
|
|
54
|
+
catch { /* best-effort surfacing */ }
|
|
55
|
+
}
|
|
56
|
+
function clearPairingCode() { try { rmSync(pairingFile(), { force: true }); } catch { /* noop */ } }
|
|
43
57
|
function sixDigitCode() {
|
|
44
58
|
return String(parseInt(randomBytes(4).toString('hex'), 16) % 1_000_000).padStart(6, '0');
|
|
45
59
|
}
|
|
46
60
|
|
|
61
|
+
// Surface the pairing code as an OS desktop notification so a non-technical user
|
|
62
|
+
// sees it WITHOUT a terminal (the connector launches us in the background, where
|
|
63
|
+
// stderr is invisible). This is a valid out-of-band channel: only someone at the
|
|
64
|
+
// physical machine sees the toast, so it does not weaken pairing the way echoing
|
|
65
|
+
// the code over the (untrusted) extension socket would. Best-effort: never throws,
|
|
66
|
+
// never blocks (detached + unref + stdio ignore), silent if the tool is missing —
|
|
67
|
+
// the 0600 file and stderr remain as backstops. `code` is digits-only (no shell/
|
|
68
|
+
// AppleScript injection risk). Exported for tests.
|
|
69
|
+
export function notifyPairingCode(code) {
|
|
70
|
+
const title = 'Reply Wizard pairing code';
|
|
71
|
+
const body = `Enter ${code} in Reply Wizard (AI Assistants > MCP) to connect.`;
|
|
72
|
+
try {
|
|
73
|
+
let cmd, args;
|
|
74
|
+
const os = platform();
|
|
75
|
+
if (os === 'darwin') {
|
|
76
|
+
cmd = 'osascript';
|
|
77
|
+
args = ['-e', `display notification "${body}" with title "${title}"`];
|
|
78
|
+
} else if (os === 'win32') {
|
|
79
|
+
// PowerShell balloon via WinForms — no external module required.
|
|
80
|
+
const ps =
|
|
81
|
+
'Add-Type -AssemblyName System.Windows.Forms;' +
|
|
82
|
+
'$n=New-Object System.Windows.Forms.NotifyIcon;' +
|
|
83
|
+
'$n.Icon=[System.Drawing.SystemIcons]::Information;' +
|
|
84
|
+
`$n.BalloonTipTitle=${JSON.stringify(title)};` +
|
|
85
|
+
`$n.BalloonTipText=${JSON.stringify(body)};` +
|
|
86
|
+
'$n.Visible=$true;$n.ShowBalloonTip(20000);Start-Sleep -Seconds 8;$n.Dispose()';
|
|
87
|
+
cmd = 'powershell';
|
|
88
|
+
args = ['-NoProfile', '-WindowStyle', 'Hidden', '-Command', ps];
|
|
89
|
+
} else {
|
|
90
|
+
// Linux / *nix: libnotify.
|
|
91
|
+
cmd = 'notify-send';
|
|
92
|
+
args = ['-u', 'normal', '-t', '30000', title, body];
|
|
93
|
+
}
|
|
94
|
+
const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
|
|
95
|
+
child.on('error', () => {}); // tool absent (e.g. no notify-send) — stay silent
|
|
96
|
+
child.unref();
|
|
97
|
+
} catch { /* notifications are best-effort */ }
|
|
98
|
+
}
|
|
99
|
+
|
|
47
100
|
export class ExtensionBridge {
|
|
48
|
-
constructor(
|
|
101
|
+
constructor(opts = {}) {
|
|
102
|
+
const { port = DEFAULT_PORT, host = '127.0.0.1' } = opts;
|
|
49
103
|
this.port = port;
|
|
50
104
|
this.host = host;
|
|
51
105
|
this.wss = null;
|
|
@@ -53,15 +107,58 @@ export class ExtensionBridge {
|
|
|
53
107
|
this.paired = false;
|
|
54
108
|
this.pairingCode = null;
|
|
55
109
|
this.sessionToken = loadToken();
|
|
56
|
-
this.pending = new Map(); // requestId → {
|
|
57
|
-
this.requestTimeoutMs = 25_000;
|
|
110
|
+
this.pending = new Map(); // requestId → { entry, lane }
|
|
111
|
+
this.requestTimeoutMs = opts.requestTimeoutMs ?? 25_000;
|
|
112
|
+
this.listening = false;
|
|
113
|
+
this.portConflict = false; // true if the port was already in use at startup
|
|
114
|
+
// Desktop-notification fn for the pairing code (injectable for tests).
|
|
115
|
+
this._notify = opts.notify ?? notifyPairingCode;
|
|
116
|
+
// Concurrency scheduler (WS-A3): all client sessions multiplex onto the single
|
|
117
|
+
// extension socket. Reads and value-actions run in INDEPENDENT lanes so a slow
|
|
118
|
+
// value-action (transcribe/summarize/suggest → LLM/STT) never head-of-line-blocks
|
|
119
|
+
// quick reads; value-actions are serialized (limit 1) to protect the provider/tab.
|
|
120
|
+
// The per-action timeout covers queue wait + round-trip, bounding total latency.
|
|
121
|
+
this.lanes = {
|
|
122
|
+
read: { name: 'read', limit: opts.maxRead ?? 4, inFlight: 0, queue: [] },
|
|
123
|
+
value: { name: 'value', limit: opts.maxValue ?? 1, inFlight: 0, queue: [] },
|
|
124
|
+
};
|
|
125
|
+
this.maxQueuePerLane = opts.maxQueue ?? 100;
|
|
58
126
|
}
|
|
59
127
|
|
|
60
128
|
listen() {
|
|
61
129
|
return new Promise((resolve, reject) => {
|
|
62
130
|
this.wss = new WebSocketServer({ host: this.host, port: this.port });
|
|
63
|
-
|
|
64
|
-
|
|
131
|
+
|
|
132
|
+
const onEarlyError = (err) => {
|
|
133
|
+
this.wss.removeListener('listening', onListening);
|
|
134
|
+
if (err && err.code === 'EADDRINUSE') {
|
|
135
|
+
// Another Reply Wizard hub already owns the port. Degrade gracefully:
|
|
136
|
+
// resolve so the MCP stdio server still connects (the client's
|
|
137
|
+
// `initialize` succeeds instead of getting EOF), but mark the bridge
|
|
138
|
+
// unavailable so action calls return a clear, actionable message.
|
|
139
|
+
this.portConflict = true;
|
|
140
|
+
log(`Port ${this.port} is already in use — another Reply Wizard hub is`);
|
|
141
|
+
log('probably already running. Starting without the WebSocket bridge;');
|
|
142
|
+
log('action calls will report the conflict. Close the other hub, or set');
|
|
143
|
+
log('RW_MCP_PORT to a free port if you intend to run more than one.');
|
|
144
|
+
try { this.wss.close(); } catch { /* noop */ }
|
|
145
|
+
this.wss = null;
|
|
146
|
+
resolve();
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
reject(err);
|
|
150
|
+
};
|
|
151
|
+
const onListening = () => {
|
|
152
|
+
this.wss.removeListener('error', onEarlyError);
|
|
153
|
+
// Keep a persistent handler so a late error never throws unhandled.
|
|
154
|
+
this.wss.on('error', (e) => log('WebSocket server error:', e && e.message));
|
|
155
|
+
this.listening = true;
|
|
156
|
+
log(`WebSocket server listening on ws://${this.host}:${this.port}`);
|
|
157
|
+
resolve();
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
this.wss.once('error', onEarlyError);
|
|
161
|
+
this.wss.once('listening', onListening);
|
|
65
162
|
this.wss.on('connection', (ws) => this._onConnection(ws));
|
|
66
163
|
});
|
|
67
164
|
}
|
|
@@ -80,7 +177,7 @@ export class ExtensionBridge {
|
|
|
80
177
|
ws.on('message', (raw) => this._onMessage(raw));
|
|
81
178
|
ws.on('close', () => {
|
|
82
179
|
log('Extension disconnected.');
|
|
83
|
-
this.
|
|
180
|
+
this._failAll(new Error('Extension disconnected.'));
|
|
84
181
|
if (this.socket === ws) { this.socket = null; this.paired = false; }
|
|
85
182
|
});
|
|
86
183
|
ws.on('error', (e) => log('Socket error:', e && e.message));
|
|
@@ -98,11 +195,15 @@ export class ExtensionBridge {
|
|
|
98
195
|
log('Reconnected with a valid session token (no pairing needed).');
|
|
99
196
|
} else {
|
|
100
197
|
this.pairingCode = sixDigitCode();
|
|
198
|
+
writePairingCode(this.pairingCode);
|
|
199
|
+
try { this._notify(this.pairingCode); } catch { /* notifier is best-effort */ }
|
|
101
200
|
log('');
|
|
102
201
|
log(' ┌──────────────────────────────────────────────┐');
|
|
103
202
|
log(` │ Reply Wizard pairing code: ${this.pairingCode} │`);
|
|
104
203
|
log(' └──────────────────────────────────────────────┘');
|
|
105
204
|
log(' Enter it in Reply Wizard → popup → AI client access.');
|
|
205
|
+
log(' (A desktop notification with the code should also appear.)');
|
|
206
|
+
log(` (Running in the background? Read it from ${pairingFile()})`);
|
|
106
207
|
this._send({ method: CONTROL.PAIRING_REQUEST, params: { hub_name: 'Reply Wizard MCP', protocol: PROTOCOL_VERSION } });
|
|
107
208
|
}
|
|
108
209
|
return;
|
|
@@ -114,10 +215,15 @@ export class ExtensionBridge {
|
|
|
114
215
|
this.paired = true;
|
|
115
216
|
this.sessionToken = randomUUID();
|
|
116
217
|
saveToken(this.sessionToken);
|
|
218
|
+
clearPairingCode();
|
|
117
219
|
this._send({ method: CONTROL.PAIRING_COMPLETE, params: { session_id: randomUUID(), session_token: this.sessionToken } });
|
|
118
220
|
this._send({ method: CONTROL.AUTH_SUCCESS, params: {} });
|
|
119
221
|
log('Pairing approved.');
|
|
120
222
|
} else {
|
|
223
|
+
// Tell the extension so it can show "incorrect code" instead of just
|
|
224
|
+
// silently staying on "Pairing needed". A rejected code keeps the same
|
|
225
|
+
// pairing code active so the user can retry without a new handshake.
|
|
226
|
+
this._send({ method: CONTROL.PAIRING_FAILED, params: { reason: 'invalid_code' } });
|
|
121
227
|
log('Pairing rejected or wrong code.');
|
|
122
228
|
}
|
|
123
229
|
return;
|
|
@@ -125,43 +231,120 @@ export class ExtensionBridge {
|
|
|
125
231
|
|
|
126
232
|
if (msg.method === CONTROL.PONG) return;
|
|
127
233
|
|
|
128
|
-
// Action result correlation.
|
|
234
|
+
// Action result correlation: settle the caller, free its lane slot, pump the lane.
|
|
129
235
|
if (msg.id && this.pending.has(msg.id)) {
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
else resolve(msg.result);
|
|
236
|
+
this._finishInFlight(msg.id, (entry) => {
|
|
237
|
+
if (msg.error) entry.reject(new Error(msg.error.message || 'Action failed'));
|
|
238
|
+
else entry.resolve(msg.result);
|
|
239
|
+
});
|
|
135
240
|
}
|
|
136
241
|
}
|
|
137
242
|
|
|
138
|
-
/**
|
|
243
|
+
/**
|
|
244
|
+
* Forward an action to the extension and await the result. Scheduled in a lane
|
|
245
|
+
* (read vs value) with bounded concurrency + per-lane backpressure; the per-action
|
|
246
|
+
* timeout covers queue wait + round-trip.
|
|
247
|
+
*/
|
|
139
248
|
callAction(action, params = {}) {
|
|
249
|
+
if (this.portConflict) {
|
|
250
|
+
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.`));
|
|
251
|
+
}
|
|
140
252
|
if (!this.socket || this.socket.readyState !== this.socket.OPEN) {
|
|
141
253
|
return Promise.reject(new Error('Reply Wizard extension is not connected. Open WhatsApp Web and enable AI client access in the extension.'));
|
|
142
254
|
}
|
|
143
255
|
if (!this.paired) {
|
|
144
256
|
return Promise.reject(new Error('Not paired yet. Enter the pairing code shown above in the extension popup.'));
|
|
145
257
|
}
|
|
146
|
-
const
|
|
258
|
+
const lane = this._laneFor(action);
|
|
259
|
+
if (lane.queue.length >= this.maxQueuePerLane) {
|
|
260
|
+
return Promise.reject(new Error(`Reply Wizard is busy (${lane.name} queue full). Try again shortly.`));
|
|
261
|
+
}
|
|
147
262
|
return new Promise((resolve, reject) => {
|
|
148
|
-
const
|
|
149
|
-
|
|
150
|
-
|
|
263
|
+
const entry = { action, params, resolve, reject, settled: false, id: null, timer: null };
|
|
264
|
+
entry.timer = setTimeout(() => this._timeout(entry, lane), this.requestTimeoutMs);
|
|
265
|
+
lane.queue.push(entry);
|
|
266
|
+
this._drainLane(lane);
|
|
151
267
|
});
|
|
152
268
|
}
|
|
153
269
|
|
|
270
|
+
_laneFor(action) {
|
|
271
|
+
return VALUE_ACTIONS.includes(action) ? this.lanes.value : this.lanes.read;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// Dispatch as many queued entries as the lane's concurrency limit allows.
|
|
275
|
+
_drainLane(lane) {
|
|
276
|
+
while (lane.inFlight < lane.limit && lane.queue.length > 0) {
|
|
277
|
+
const entry = lane.queue.shift();
|
|
278
|
+
if (entry.settled) continue; // timed out while queued
|
|
279
|
+
lane.inFlight++;
|
|
280
|
+
this._dispatch(entry, lane);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
_dispatch(entry, lane) {
|
|
285
|
+
if (!this.socket || this.socket.readyState !== this.socket.OPEN) {
|
|
286
|
+
// Connection dropped between enqueue and dispatch.
|
|
287
|
+
lane.inFlight--;
|
|
288
|
+
if (!entry.settled) {
|
|
289
|
+
entry.settled = true;
|
|
290
|
+
clearTimeout(entry.timer);
|
|
291
|
+
entry.reject(new Error('Reply Wizard extension disconnected.'));
|
|
292
|
+
}
|
|
293
|
+
this._drainLane(lane);
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
const id = randomUUID();
|
|
297
|
+
entry.id = id;
|
|
298
|
+
this.pending.set(id, { entry, lane });
|
|
299
|
+
this._send({ id, method: 'action', action: entry.action, params: entry.params });
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// Settle an in-flight action, free its lane slot, and pump the lane.
|
|
303
|
+
_finishInFlight(id, settle) {
|
|
304
|
+
const rec = this.pending.get(id);
|
|
305
|
+
if (!rec) return;
|
|
306
|
+
this.pending.delete(id);
|
|
307
|
+
const { entry, lane } = rec;
|
|
308
|
+
clearTimeout(entry.timer);
|
|
309
|
+
lane.inFlight--;
|
|
310
|
+
if (!entry.settled) { entry.settled = true; settle(entry); }
|
|
311
|
+
this._drainLane(lane);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
_timeout(entry, lane) {
|
|
315
|
+
if (entry.settled) return;
|
|
316
|
+
entry.settled = true;
|
|
317
|
+
const qi = lane.queue.indexOf(entry);
|
|
318
|
+
if (qi >= 0) lane.queue.splice(qi, 1); // timed out while still queued
|
|
319
|
+
if (entry.id && this.pending.has(entry.id)) { // timed out while in flight
|
|
320
|
+
this.pending.delete(entry.id);
|
|
321
|
+
lane.inFlight--;
|
|
322
|
+
this._drainLane(lane);
|
|
323
|
+
}
|
|
324
|
+
entry.reject(new Error(`Action "${entry.action}" timed out.`));
|
|
325
|
+
}
|
|
326
|
+
|
|
154
327
|
_send(obj) {
|
|
155
328
|
if (this.socket && this.socket.readyState === this.socket.OPEN) this.socket.send(JSON.stringify(obj));
|
|
156
329
|
}
|
|
157
330
|
|
|
158
|
-
|
|
159
|
-
|
|
331
|
+
// Reject every queued and in-flight action (e.g. on disconnect / shutdown).
|
|
332
|
+
_failAll(err) {
|
|
333
|
+
for (const lane of Object.values(this.lanes)) {
|
|
334
|
+
const queued = lane.queue.splice(0);
|
|
335
|
+
for (const entry of queued) {
|
|
336
|
+
if (!entry.settled) { entry.settled = true; clearTimeout(entry.timer); entry.reject(err); }
|
|
337
|
+
}
|
|
338
|
+
lane.inFlight = 0;
|
|
339
|
+
}
|
|
340
|
+
for (const { entry } of this.pending.values()) {
|
|
341
|
+
if (!entry.settled) { entry.settled = true; clearTimeout(entry.timer); entry.reject(err); }
|
|
342
|
+
}
|
|
160
343
|
this.pending.clear();
|
|
161
344
|
}
|
|
162
345
|
|
|
163
346
|
close() {
|
|
164
|
-
this.
|
|
347
|
+
this._failAll(new Error('Hub shutting down.'));
|
|
165
348
|
if (this.wss) this.wss.close();
|
|
166
349
|
}
|
|
167
350
|
}
|