replywizard-whatsapp-mcp 0.2.6 → 0.3.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 +108 -19
- package/package.json +7 -4
- package/src/cli.js +444 -0
- package/src/connector.js +6 -4
- package/src/daemon.js +41 -9
- package/src/daemonAuth.js +9 -1
- package/src/index.js +1 -1
- package/src/mcpServer.js +1 -1
- package/src/protocol.js +1 -1
- package/src/tools.js +17 -6
- package/src/wsServer.js +200 -44
package/README.md
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
# replywizard-whatsapp-mcp
|
|
2
2
|
|
|
3
3
|
Local **Model Context Protocol** server that exposes your WhatsApp Web session to AI clients
|
|
4
|
-
(Claude Desktop, Claude Code, Cursor, …) **through the Reply Wizard Chrome
|
|
4
|
+
(Claude Desktop, Claude Code, Cursor, Antigravity, …) **through the Reply Wizard Chrome
|
|
5
|
+
extension**, plus a `replywizard` command line onto the same bridge.
|
|
5
6
|
|
|
6
|
-
|
|
7
|
+
**Read + value only** and **local-only**: there is no path that can send or modify WhatsApp
|
|
7
8
|
messages, and nothing leaves your machine.
|
|
8
9
|
|
|
9
10
|
## How it works
|
|
@@ -32,7 +33,7 @@ lifted into its own repository without touching the extension.
|
|
|
32
33
|
| `get_contact` | read | Look up one contact by id. |
|
|
33
34
|
| `list_contacts` | read | Your saved (address-book) contacts. |
|
|
34
35
|
| `summarize_chat` | value | Bulleted summary of a chat's recent messages (uses your configured AI provider). |
|
|
35
|
-
| `suggest_reply` | value | Drafts a reply as you
|
|
36
|
+
| `suggest_reply` | value | Drafts a reply as you, returns text only, **never sends**. |
|
|
36
37
|
| `transcribe_voice_note` | value | Transcribes a voice note via your configured **cloud** speech-to-text provider. |
|
|
37
38
|
|
|
38
39
|
Value tools reuse the extension's existing AI/STT configuration; **your API keys never leave the
|
|
@@ -41,13 +42,13 @@ extension** (the hub only sees tool arguments and results).
|
|
|
41
42
|
## Setup
|
|
42
43
|
|
|
43
44
|
> **Multi-agent by default.** The `npx -y replywizard-whatsapp-mcp` config below runs the **connector**
|
|
44
|
-
> (the package's default bin), which auto-starts a shared local **daemon
|
|
45
|
+
> (the package's default bin), which auto-starts a shared local **daemon**, so several assistants
|
|
45
46
|
> (Claude Code + Cursor + Claude Desktop, …) can share one WhatsApp session at once, with no extra setup.
|
|
46
47
|
> See [Multiple AI assistants at once](#multiple-ai-assistants-at-once-daemon) for the architecture. Use
|
|
47
48
|
> the single-arg form above (not the older `-p <pkg> <bin>` form, which some clients fail to launch).
|
|
48
49
|
|
|
49
50
|
Published to npm as [`replywizard-whatsapp-mcp`](https://www.npmjs.com/package/replywizard-whatsapp-mcp).
|
|
50
|
-
You don't install anything by hand
|
|
51
|
+
You don't install anything by hand, your AI client runs it via `npx` (requires Node.js 18+).
|
|
51
52
|
|
|
52
53
|
### Claude Desktop
|
|
53
54
|
|
|
@@ -71,17 +72,86 @@ Add to `claude_desktop_config.json`:
|
|
|
71
72
|
claude mcp add replywizard -- npx -y replywizard-whatsapp-mcp
|
|
72
73
|
```
|
|
73
74
|
|
|
75
|
+
### Cursor and VS Code: one click
|
|
76
|
+
|
|
77
|
+
The extension's **WhatsApp MCP** tab has **Add to Cursor** and **Add to VS Code** buttons that
|
|
78
|
+
hand the editor exactly the config above, plus a copy button for the Claude Code command. The raw
|
|
79
|
+
JSON stays on screen next to them: an install deeplink is opaque by nature, so reading it first is
|
|
80
|
+
always an option.
|
|
81
|
+
|
|
82
|
+
### Antigravity
|
|
83
|
+
|
|
84
|
+
Antigravity is a VS Code fork and inherits both `--add-mcp` and the `mcp/install` URL handler,
|
|
85
|
+
but **it keeps two MCP lists** and they are not the same one:
|
|
86
|
+
|
|
87
|
+
| List | Path | Key | Written by |
|
|
88
|
+
|---|---|---|---|
|
|
89
|
+
| The editor's | `~/.config/Antigravity IDE/User/mcp.json` | `servers` | `antigravity-ide --add-mcp` |
|
|
90
|
+
| The agent's | `~/.gemini/config/mcp_config.json` | `mcpServers` | by hand, and it is the config above |
|
|
91
|
+
|
|
92
|
+
The **Copy Antigravity command** button hands you the `--add-mcp` line. If the agent panel does
|
|
93
|
+
not list Reply Wizard afterwards, put the JSON above into `~/.gemini/config/mcp_config.json`
|
|
94
|
+
instead. There is deliberately no deeplink button: the handler ships in the build, but nothing
|
|
95
|
+
registers the `antigravity-ide:` scheme on Linux, so the click would do nothing and say nothing.
|
|
96
|
+
|
|
97
|
+
## The command line
|
|
98
|
+
|
|
99
|
+
The same package installs a `replywizard` command. It is a THIRD front end onto the same local
|
|
100
|
+
daemon, beside the MCP HTTP endpoint and the stdio connector, so it works while every editor you
|
|
101
|
+
have connected is still attached, and it can do exactly what an AI client can do and nothing more.
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
npx -y -p replywizard-whatsapp-mcp replywizard --help
|
|
105
|
+
|
|
106
|
+
replywizard status # is the bridge up, is the browser paired
|
|
107
|
+
replywizard pair # where to find the 6-digit code
|
|
108
|
+
replywizard chats --limit 10
|
|
109
|
+
replywizard messages 919110412164 --limit 20
|
|
110
|
+
replywizard contacts
|
|
111
|
+
replywizard summarize 919110412164 # uses your configured AI provider
|
|
112
|
+
replywizard suggest 919110412164 "politely decline"
|
|
113
|
+
replywizard transcribe <messageId>
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
`--json` prints the raw answer for scripting, and a failed call exits non-zero, so a pipeline can
|
|
117
|
+
branch on it:
|
|
118
|
+
|
|
119
|
+
```bash
|
|
120
|
+
replywizard chats --limit 5 --json | jq -r '.chats[] | "\(.unreadCount)\t\(.name)"'
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
**It never sends.** There is no `send` command because there is no send path in the extension,
|
|
124
|
+
which is the answer to "will this get my WhatsApp account banned". The commands are generated from
|
|
125
|
+
the same tool definitions the MCP surface uses, so the two can never document different arguments.
|
|
126
|
+
|
|
127
|
+
The first command starts the shared daemon if it is not already running, exactly as an editor's
|
|
128
|
+
launch does. It identifies itself as `replywizard-cli`, so it appears beside your editors under
|
|
129
|
+
**Connected assistants** on the extension's WhatsApp MCP tab.
|
|
130
|
+
|
|
74
131
|
`RW_MCP_PORT` is optional (defaults to `7869`); set it on both sides if you change it.
|
|
75
132
|
|
|
133
|
+
> **Pairing-code toast.** The code is also shown as a desktop notification (`osascript` on
|
|
134
|
+
> macOS, a PowerShell balloon on Windows, `notify-send` on Linux), because the connector is
|
|
135
|
+
> usually launched in the background where stderr is invisible. It is best-effort and never
|
|
136
|
+
> fails the daemon; `~/.replywizard-mcp/pairing-code.txt` (0600) is the backstop. All three
|
|
137
|
+
> branches run in CI on their own platform, `npm test` in this package covers them, and the
|
|
138
|
+
> real-notifier test is skipped locally unless `CI=1` or `RW_TEST_NOTIFY=1` so running the
|
|
139
|
+
> suite does not interrupt you with a toast.
|
|
140
|
+
|
|
76
141
|
> **Running from source instead?** Clone the repo, `cd mcp-host && npm install`, and point your
|
|
77
|
-
> client at `node /absolute/path/to/mcp-host/src/connector.js` (multi-agent)
|
|
142
|
+
> client at `node /absolute/path/to/mcp-host/src/connector.js` (multi-agent), or
|
|
78
143
|
> `node .../src/index.js` for the legacy single-client, no-daemon hub.
|
|
79
144
|
|
|
80
145
|
## Multiple AI assistants at once (daemon)
|
|
81
146
|
|
|
82
147
|
This happens automatically with the `npx` config above: `replywizard-whatsapp-mcp` runs the connector,
|
|
83
|
-
which starts one shared daemon.
|
|
84
|
-
|
|
148
|
+
which starts one shared daemon. **There is no limit on the number of clients.** Measured
|
|
149
|
+
2026-09-10 against a running daemon: four concurrent MCP sessions, all four listing the same
|
|
150
|
+
eight tools, and three concurrent tool calls through the one browser socket answering in 24, 24
|
|
151
|
+
and 25ms. VS Code, Claude Code, Cursor, Antigravity, the `replywizard` command line and a second
|
|
152
|
+
window of any of them can all be attached at once. The one limit is on the other side: **one
|
|
153
|
+
WhatsApp Web browser at a time**, because a second extension socket is refused. (The legacy `index.js` hub, run directly via `node .../src/index.js`, binds
|
|
154
|
+
the WebSocket port itself, so **only one AI client can use it at a time**; a second launch hits
|
|
85
155
|
`EADDRINUSE`.) The daemon architecture:
|
|
86
156
|
|
|
87
157
|
```
|
|
@@ -90,12 +160,12 @@ client B (stdio)→ rw-mcp-connector ─┤→ rw-mcp-daemon ⇄ Reply Wizard
|
|
|
90
160
|
client C (stdio)→ rw-mcp-connector ─┘ (one daemon; owns ws://127.0.0.1:7869, serves http://127.0.0.1:7870/mcp)
|
|
91
161
|
```
|
|
92
162
|
|
|
93
|
-
- **`rw-mcp-daemon
|
|
163
|
+
- **`rw-mcp-daemon`**: long-lived; owns the extension WebSocket and serves MCP over Streamable HTTP
|
|
94
164
|
to any number of clients (each gets its own session). Single-instance: a second daemon exits cleanly.
|
|
95
|
-
- **`rw-mcp-connector
|
|
165
|
+
- **`rw-mcp-connector`**: a stdio shim for clients that only launch a command; it auto-starts the
|
|
96
166
|
daemon if needed and transparently proxies. **Reads the auth token for you** (no token in your config).
|
|
97
167
|
|
|
98
|
-
**Clients that speak HTTP (e.g. Claude Code)** connect to the daemon directly
|
|
168
|
+
**Clients that speak HTTP (e.g. Claude Code)** connect to the daemon directly, no connector needed:
|
|
99
169
|
|
|
100
170
|
```bash
|
|
101
171
|
TOKEN=$(node -e "console.log(require('os').homedir())")/.replywizard-mcp/daemon-token.json # see the token
|
|
@@ -128,24 +198,43 @@ claude mcp add rw --transport http http://127.0.0.1:7870/mcp --header "Authoriza
|
|
|
128
198
|
The daemon generates a bearer token on first start at `~/.replywizard-mcp/daemon-token.json` (mode
|
|
129
199
|
`600`). Every `/mcp` request must present it (`Authorization: Bearer <token>`); `/healthz` is open.
|
|
130
200
|
The connector reads it automatically. **To revoke**, delete that file (the daemon mints a new one on
|
|
131
|
-
next start)
|
|
201
|
+
next start): existing clients must pick up the new token.
|
|
132
202
|
|
|
133
203
|
## First-run pairing
|
|
134
204
|
|
|
135
205
|
1. Open **WhatsApp Web** in the browser with Reply Wizard installed.
|
|
136
|
-
2.
|
|
206
|
+
2. Open Reply Wizard **Settings** → **WhatsApp MCP** and turn on **Enable AI access**. The
|
|
207
|
+
toolbar popup reports the same state under **AI client access** and has a **Manage in
|
|
208
|
+
Settings** button that jumps straight there, but every control lives on the tab.
|
|
137
209
|
3. Start your AI client (it launches this hub). The hub prints a **6-digit pairing code** to its
|
|
138
210
|
stderr / the client's MCP log.
|
|
139
|
-
4. Enter that code in
|
|
140
|
-
reconnects automatically on subsequent runs (no code needed again).
|
|
211
|
+
4. Enter that code in **Settings → WhatsApp MCP**. Once paired, the extension stores a session
|
|
212
|
+
token and reconnects automatically on subsequent runs (no code needed again).
|
|
213
|
+
|
|
214
|
+
Use **Revoke pairing** on the same tab to drop the token and disable the bridge.
|
|
215
|
+
|
|
216
|
+
**A code survives a reconnect.** The extension's MV3 service worker reconnects on its own
|
|
217
|
+
schedule, and until 2026-09-03 each reconnect threw the pairing code away and minted a new one,
|
|
218
|
+
so the digits you were reading off the toast went stale while you typed them and another toast
|
|
219
|
+
appeared. A code that is still within its five minutes is now reused instead: one code, one
|
|
220
|
+
notification, and it stays valid for as long as it was ever going to.
|
|
221
|
+
|
|
222
|
+
Two things do **not** change on reuse, and each is tested:
|
|
223
|
+
|
|
224
|
+
- **The deadline is not extended.** The five minutes run from when the code was first issued,
|
|
225
|
+
so a client that reconnects every four minutes cannot keep one code alive indefinitely.
|
|
226
|
+
- **The wrong-attempt counter is not reset.** This is the load-bearing half. Without it,
|
|
227
|
+
closing and reopening the socket would hand an attacker another five guesses against the
|
|
228
|
+
same code, over and over; the old behaviour was safe only because the code changed each
|
|
229
|
+
time, so preserving one property without the other would have been a regression.
|
|
141
230
|
|
|
142
|
-
|
|
231
|
+
A code is still destroyed immediately on a successful pairing, on lockout, and on expiry.
|
|
143
232
|
|
|
144
233
|
## Security
|
|
145
234
|
|
|
146
235
|
- Binds to `127.0.0.1` only.
|
|
147
236
|
- No tool runs until the pairing code is confirmed in the extension.
|
|
148
|
-
- **Read + value tools only
|
|
237
|
+
- **Read + value tools only**: v1 has no send/modify capability.
|
|
149
238
|
- The session token is stored at `~/.replywizard-mcp/session.json` (mode 600).
|
|
150
239
|
|
|
151
240
|
## Troubleshooting
|
|
@@ -158,5 +247,5 @@ Use **Revoke access** in the popup to drop the token and disable the bridge.
|
|
|
158
247
|
| Transcription error about a cloud provider | `transcribe_voice_note` needs a **cloud** STT key in Options → Speech-to-Text (on-device STT is not used over MCP). |
|
|
159
248
|
| Port in use | The default is `7869`. Changing it is advanced (set `RW_MCP_PORT` on the hub **and** the `rw_mcp_port` value in the extension's storage to match). |
|
|
160
249
|
|
|
161
|
-
See [`../
|
|
162
|
-
[`../
|
|
250
|
+
See [`../ARCHITECTURE.md`](../ARCHITECTURE.md) (MCP Integration) for the design, and
|
|
251
|
+
[`../ROADMAP.md`](../ROADMAP.md) §3.4 for the open MCP items.
|
package/package.json
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "replywizard-whatsapp-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Local MCP server that
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Local MCP server and command line that expose WhatsApp Web (read + value tools) to AI clients via the Reply Wizard Chrome extension.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"replywizard-whatsapp-mcp": "src/connector.js",
|
|
8
8
|
"rw-mcp-daemon": "src/daemon.js",
|
|
9
|
-
"rw-mcp-connector": "src/connector.js"
|
|
9
|
+
"rw-mcp-connector": "src/connector.js",
|
|
10
|
+
"replywizard": "src/cli.js"
|
|
10
11
|
},
|
|
11
12
|
"exports": {
|
|
12
13
|
"./protocol": "./src/protocol.js"
|
|
@@ -28,7 +29,9 @@
|
|
|
28
29
|
"whatsapp",
|
|
29
30
|
"reply-wizard",
|
|
30
31
|
"claude",
|
|
31
|
-
"ai"
|
|
32
|
+
"ai",
|
|
33
|
+
"cli",
|
|
34
|
+
"command-line"
|
|
32
35
|
],
|
|
33
36
|
"repository": {
|
|
34
37
|
"type": "git",
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// cli.js: Reply Wizard from a terminal.
|
|
3
|
+
//
|
|
4
|
+
// WHAT THIS IS, AND WHAT IT DELIBERATELY IS NOT
|
|
5
|
+
// A THIRD front end onto the same local daemon, alongside the MCP HTTP endpoint and the
|
|
6
|
+
// stdio connector. It speaks the same protocol to the same process, so everything it can do
|
|
7
|
+
// is something an AI client can already do, and nothing here reaches WhatsApp except through
|
|
8
|
+
// the extension's own read-and-value actions.
|
|
9
|
+
//
|
|
10
|
+
// It does NOT open a WebSocket to the extension. That socket is the one singleton in this
|
|
11
|
+
// system (`wsServer.js` refuses a second extension connection), and a CLI that grabbed it
|
|
12
|
+
// would take WhatsApp away from every editor the user has open. Connecting as an ordinary
|
|
13
|
+
// client instead is what makes `replywizard chats` work while VS Code, Claude Code and
|
|
14
|
+
// Antigravity are all attached: measured 2026-09-10, four concurrent sessions on one bridge,
|
|
15
|
+
// three concurrent tool calls answering in 24-25ms each.
|
|
16
|
+
//
|
|
17
|
+
// It sends nothing. There is no send path in this extension and that is the answer to "will
|
|
18
|
+
// this get my WhatsApp account banned". A command line feels like automation in a way an
|
|
19
|
+
// editor plugin does not, so `--help` says so in as many words rather than leaving it to be
|
|
20
|
+
// inferred from the absence of a `send` command.
|
|
21
|
+
//
|
|
22
|
+
// WHY IT IS A BIN IN THIS PACKAGE RATHER THAN ITS OWN
|
|
23
|
+
// One install, one version, and no second copy of `ensureDaemon`, the token reader or the
|
|
24
|
+
// tool schemas. The commands below are GENERATED from `TOOLS`, so a tool added to the MCP
|
|
25
|
+
// surface is a CLI command with no edit here, and a tool whose arguments change cannot end
|
|
26
|
+
// up documented two different ways.
|
|
27
|
+
//
|
|
28
|
+
// WHY THE BIN IS `replywizard` AND NOT `rw`
|
|
29
|
+
// npm bin collisions are silent and the last install wins, which is the trap
|
|
30
|
+
// `npx-stale-global-shadows` already records for this package. A two-letter name on a
|
|
31
|
+
// developer's PATH is asking for it.
|
|
32
|
+
|
|
33
|
+
import { realpathSync } from 'node:fs';
|
|
34
|
+
import { fileURLToPath } from 'node:url';
|
|
35
|
+
import { TOOLS } from './tools.js';
|
|
36
|
+
import { ACTIONS, VALUE_ACTIONS } from './protocol.js';
|
|
37
|
+
import { DEFAULT_HTTP_PORT } from './daemon.js';
|
|
38
|
+
import { ensureDaemon, spawnDetachedDaemon } from './connector.js';
|
|
39
|
+
import { readToken } from './daemonAuth.js';
|
|
40
|
+
|
|
41
|
+
const HOST = '127.0.0.1';
|
|
42
|
+
const CLIENT_NAME = 'replywizard-cli';
|
|
43
|
+
|
|
44
|
+
/** Written to stderr so `replywizard chats --json | jq` stays clean. */
|
|
45
|
+
const note = (...args) => console.error(...args);
|
|
46
|
+
|
|
47
|
+
/* ── the command table, derived from the MCP tools ─────────────────────────────────── */
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* How each tool is spelled on a command line.
|
|
51
|
+
*
|
|
52
|
+
* `positional` names the arguments that may be given without a flag, in order, so
|
|
53
|
+
* `replywizard messages 9199... --limit 5` works. Everything else is `--flag value`.
|
|
54
|
+
* Only the shape lives here; the descriptions and the argument names come from `TOOLS`.
|
|
55
|
+
*/
|
|
56
|
+
const POSITIONAL = {
|
|
57
|
+
[ACTIONS.PING]: ['echo'],
|
|
58
|
+
[ACTIONS.GET_MESSAGES]: ['chatId'],
|
|
59
|
+
[ACTIONS.GET_CONTACT]: ['contactId'],
|
|
60
|
+
[ACTIONS.SUMMARIZE_CHAT]: ['chatId'],
|
|
61
|
+
[ACTIONS.SUGGEST_REPLY]: ['chatId', 'guidance'],
|
|
62
|
+
[ACTIONS.TRANSCRIBE_VOICE_NOTE]: ['messageId'],
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/** Shorter names for the two longest tools. The tool name always works as well. */
|
|
66
|
+
const ALIASES = {
|
|
67
|
+
chats: ACTIONS.LIST_CHATS,
|
|
68
|
+
messages: ACTIONS.GET_MESSAGES,
|
|
69
|
+
contacts: ACTIONS.LIST_CONTACTS,
|
|
70
|
+
contact: ACTIONS.GET_CONTACT,
|
|
71
|
+
summarize: ACTIONS.SUMMARIZE_CHAT,
|
|
72
|
+
suggest: ACTIONS.SUGGEST_REPLY,
|
|
73
|
+
transcribe: ACTIONS.TRANSCRIBE_VOICE_NOTE,
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
const toolByName = new Map(TOOLS.map((t) => [t.name, t]));
|
|
77
|
+
|
|
78
|
+
/** Resolve a typed command to a tool, via the aliases or the tool's own name. */
|
|
79
|
+
export function resolveCommand(word) {
|
|
80
|
+
const name = ALIASES[word] || word;
|
|
81
|
+
return toolByName.get(name) || null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/* ── argument parsing ──────────────────────────────────────────────────────────────── */
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Turn argv into `{ args, flags }` for one tool.
|
|
88
|
+
*
|
|
89
|
+
* Types come from the tool's own `inputSchema`, so an integer argument is sent as a number
|
|
90
|
+
* and a boolean flag needs no value. Getting this from the schema rather than a second table
|
|
91
|
+
* is the point: a provider that rejects `"limit": "5"` would otherwise be a CLI-only bug.
|
|
92
|
+
*
|
|
93
|
+
* @param {object} tool one entry from TOOLS
|
|
94
|
+
* @param {string[]} argv the words after the command
|
|
95
|
+
* @returns {{args: object, json: boolean, unknown: string[]}}
|
|
96
|
+
*/
|
|
97
|
+
export function parseArgs(tool, argv) {
|
|
98
|
+
const props = (tool.inputSchema && tool.inputSchema.properties) || {};
|
|
99
|
+
const positional = POSITIONAL[tool.name] || [];
|
|
100
|
+
const args = {};
|
|
101
|
+
const unknown = [];
|
|
102
|
+
let json = false;
|
|
103
|
+
let next = 0;
|
|
104
|
+
|
|
105
|
+
const coerce = (key, raw) => {
|
|
106
|
+
const type = props[key] && props[key].type;
|
|
107
|
+
if (type === 'integer' || type === 'number') {
|
|
108
|
+
const n = Number(raw);
|
|
109
|
+
return Number.isFinite(n) ? n : raw;
|
|
110
|
+
}
|
|
111
|
+
if (type === 'boolean') return raw !== 'false';
|
|
112
|
+
return raw;
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
116
|
+
const word = argv[i];
|
|
117
|
+
if (word === '--json') { json = true; continue; }
|
|
118
|
+
if (word.startsWith('--')) {
|
|
119
|
+
const eq = word.indexOf('=');
|
|
120
|
+
const key = eq === -1 ? word.slice(2) : word.slice(2, eq);
|
|
121
|
+
if (!Object.prototype.hasOwnProperty.call(props, key)) {
|
|
122
|
+
// Swallow the value a misspelled flag was given, so the complaint names the flag and
|
|
123
|
+
// not also the number beside it. `--lmit 5` should read as one mistake, not two, and
|
|
124
|
+
// without this the 5 would arrive as a stray positional or a second unknown.
|
|
125
|
+
if (eq === -1 && argv[i + 1] !== undefined && !String(argv[i + 1]).startsWith('--')) i += 1;
|
|
126
|
+
unknown.push(`--${key}`);
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
/*
|
|
130
|
+
* A boolean flag is set by PRESENCE and takes no following word. `--flag=false` is the
|
|
131
|
+
* explicit form. Consuming the next word instead would make `replywizard contacts
|
|
132
|
+
* --includeNonContacts 9199` eat the chat id, and the failure would be a command that
|
|
133
|
+
* silently did something else.
|
|
134
|
+
*/
|
|
135
|
+
if (props[key].type === 'boolean' && eq === -1) { args[key] = true; continue; }
|
|
136
|
+
const raw = eq === -1 ? argv[i += 1] : word.slice(eq + 1);
|
|
137
|
+
if (raw === undefined) { unknown.push(`--${key} (no value)`); continue; }
|
|
138
|
+
args[key] = coerce(key, raw);
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
// A bare word fills the next positional slot this tool has left.
|
|
142
|
+
if (next < positional.length) { args[positional[next]] = coerce(positional[next], word); next += 1; continue; }
|
|
143
|
+
unknown.push(word);
|
|
144
|
+
}
|
|
145
|
+
return { args, json, unknown };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Required-but-missing arguments, from the tool's own schema. */
|
|
149
|
+
export function missingRequired(tool, args) {
|
|
150
|
+
const required = (tool.inputSchema && tool.inputSchema.required) || [];
|
|
151
|
+
return required.filter((k) => args[k] === undefined || args[k] === '');
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/* ── talking to the daemon ─────────────────────────────────────────────────────────── */
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* One MCP session, one tool call, then hang up.
|
|
158
|
+
*
|
|
159
|
+
* A session per invocation rather than a long-lived one, because a CLI process IS the
|
|
160
|
+
* session's lifetime. The DELETE at the end matters: without it the daemon holds the session
|
|
161
|
+
* until its stale sweep runs, and `replywizard status` would report sessions nobody has.
|
|
162
|
+
*
|
|
163
|
+
* @param {object} deps injectable for tests: fetchImpl, token, base
|
|
164
|
+
*/
|
|
165
|
+
export async function callTool(name, args, deps = {}) {
|
|
166
|
+
const base = deps.base || `http://${HOST}:${Number(process.env.RW_MCP_HTTP_PORT) || DEFAULT_HTTP_PORT}`;
|
|
167
|
+
const fetchImpl = deps.fetchImpl || fetch;
|
|
168
|
+
const token = deps.token !== undefined ? deps.token : readToken();
|
|
169
|
+
const headers = {
|
|
170
|
+
'content-type': 'application/json',
|
|
171
|
+
// Both, because the Streamable HTTP transport may answer either way and a missing
|
|
172
|
+
// `text/event-stream` is a 406 rather than anything that reads like a cause.
|
|
173
|
+
accept: 'application/json, text/event-stream',
|
|
174
|
+
...(token ? { authorization: `Bearer ${token}` } : {}),
|
|
175
|
+
};
|
|
176
|
+
const post = (body, sessionId) => fetchImpl(`${base}/mcp`, {
|
|
177
|
+
method: 'POST',
|
|
178
|
+
headers: sessionId ? { ...headers, 'mcp-session-id': sessionId } : headers,
|
|
179
|
+
body: JSON.stringify(body),
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
const opened = await post({
|
|
183
|
+
jsonrpc: '2.0',
|
|
184
|
+
id: 1,
|
|
185
|
+
method: 'initialize',
|
|
186
|
+
params: {
|
|
187
|
+
protocolVersion: '2024-11-05',
|
|
188
|
+
capabilities: {},
|
|
189
|
+
// The daemon relays this name to the extension, and the Options page shows it under
|
|
190
|
+
// "Connected assistants": the CLI should be identifiable there like any other client.
|
|
191
|
+
clientInfo: { name: CLIENT_NAME, version: deps.version || 'dev' },
|
|
192
|
+
},
|
|
193
|
+
});
|
|
194
|
+
if (opened.status === 401) throw new Error(UNAUTHORIZED);
|
|
195
|
+
if (!opened.ok) throw new Error(`The Reply Wizard daemon refused the connection (HTTP ${opened.status}).`);
|
|
196
|
+
const sessionId = opened.headers.get('mcp-session-id');
|
|
197
|
+
await opened.text();
|
|
198
|
+
if (!sessionId) throw new Error('The Reply Wizard daemon opened no session.');
|
|
199
|
+
|
|
200
|
+
try {
|
|
201
|
+
await post({ jsonrpc: '2.0', method: 'notifications/initialized' }, sessionId);
|
|
202
|
+
const res = await post({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name, arguments: args } }, sessionId);
|
|
203
|
+
const raw = await res.text();
|
|
204
|
+
return unwrap(raw);
|
|
205
|
+
} finally {
|
|
206
|
+
// Best effort: a failed hang-up must not turn a successful call into an error.
|
|
207
|
+
try {
|
|
208
|
+
await fetchImpl(`${base}/mcp`, { method: 'DELETE', headers: { ...headers, 'mcp-session-id': sessionId } });
|
|
209
|
+
} catch { /* the daemon's stale sweep will collect it */ }
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const UNAUTHORIZED = 'The Reply Wizard daemon rejected this token. It is in '
|
|
214
|
+
+ '~/.replywizard-mcp/daemon-token.json; if you revoked it from the extension\'s Options '
|
|
215
|
+
+ 'page, restart the daemon so a fresh one is written.';
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Pull the tool's payload out of a JSON-RPC answer, which may arrive as an SSE frame.
|
|
219
|
+
*
|
|
220
|
+
* The Streamable HTTP transport is allowed to answer either `application/json` or
|
|
221
|
+
* `text/event-stream` for the same request, so both are handled here rather than a content
|
|
222
|
+
* type being assumed. An `isError` result is raised as an error, because a CLI that printed
|
|
223
|
+
* a failure to stdout and exited 0 would be wrong in a pipeline.
|
|
224
|
+
*/
|
|
225
|
+
export function unwrap(raw) {
|
|
226
|
+
const text = String(raw == null ? '' : raw);
|
|
227
|
+
const line = text.split('\n').map((l) => l.trim())
|
|
228
|
+
.filter((l) => l.startsWith('{') || l.startsWith('data: {'))
|
|
229
|
+
.map((l) => (l.startsWith('data: ') ? l.slice(6) : l))
|
|
230
|
+
.pop();
|
|
231
|
+
if (!line) throw new Error('The Reply Wizard daemon sent no answer.');
|
|
232
|
+
let msg;
|
|
233
|
+
try { msg = JSON.parse(line); } catch { throw new Error('The Reply Wizard daemon sent an answer that is not JSON.'); }
|
|
234
|
+
if (msg.error) throw new Error(msg.error.message || 'The call failed.');
|
|
235
|
+
const result = msg.result || {};
|
|
236
|
+
const body = (result.content || []).map((c) => c.text).filter(Boolean).join('\n');
|
|
237
|
+
if (result.isError) throw new Error(body || 'The call failed.');
|
|
238
|
+
try { return JSON.parse(body); } catch { return body; }
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/* ── output ────────────────────────────────────────────────────────────────────────── */
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Print a result for a human, or verbatim JSON for a pipeline.
|
|
245
|
+
*
|
|
246
|
+
* The human form is deliberately shallow: a table for a list of objects, key/value lines for
|
|
247
|
+
* one object, and the raw text for anything else. Anyone who wants structure has `--json`,
|
|
248
|
+
* and inventing a pretty renderer per tool is how the two drift apart.
|
|
249
|
+
*/
|
|
250
|
+
export function format(value, { json = false } = {}) {
|
|
251
|
+
if (json) return JSON.stringify(value, null, 2);
|
|
252
|
+
if (value == null) return '';
|
|
253
|
+
if (typeof value === 'string') return value;
|
|
254
|
+
|
|
255
|
+
const rows = Array.isArray(value) ? value : pickList(value);
|
|
256
|
+
if (rows && rows.length && rows.every((r) => r && typeof r === 'object' && !Array.isArray(r))) {
|
|
257
|
+
return table(rows);
|
|
258
|
+
}
|
|
259
|
+
if (Array.isArray(value)) return value.map((v) => (typeof v === 'string' ? v : JSON.stringify(v))).join('\n');
|
|
260
|
+
return Object.entries(value)
|
|
261
|
+
.map(([k, v]) => `${k}: ${typeof v === 'object' ? JSON.stringify(v) : v}`)
|
|
262
|
+
.join('\n');
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** The one array inside a single-key wrapper like `{ chats: [...] }`. */
|
|
266
|
+
function pickList(obj) {
|
|
267
|
+
const values = Object.values(obj);
|
|
268
|
+
const arrays = values.filter(Array.isArray);
|
|
269
|
+
return arrays.length === 1 && values.length <= 2 ? arrays[0] : null;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** A plain aligned table. No box drawing, so it stays readable when a cell is long. */
|
|
273
|
+
export function table(rows) {
|
|
274
|
+
const cols = [];
|
|
275
|
+
for (const row of rows) for (const k of Object.keys(row)) if (!cols.includes(k)) cols.push(k);
|
|
276
|
+
const cell = (row, k) => {
|
|
277
|
+
const v = row[k];
|
|
278
|
+
if (v == null) return '';
|
|
279
|
+
return typeof v === 'object' ? JSON.stringify(v) : String(v);
|
|
280
|
+
};
|
|
281
|
+
const width = (k) => Math.max(k.length, ...rows.map((r) => cell(r, k).length));
|
|
282
|
+
const widths = cols.map(width);
|
|
283
|
+
const line = (values) => values.map((v, i) => v.padEnd(widths[i])).join(' ').trimEnd();
|
|
284
|
+
return [line(cols), line(widths.map((w) => '-'.repeat(w))), ...rows.map((r) => line(cols.map((k) => cell(r, k))))]
|
|
285
|
+
.join('\n');
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/* ── help ──────────────────────────────────────────────────────────────────────────── */
|
|
289
|
+
|
|
290
|
+
export function helpText() {
|
|
291
|
+
const aliasFor = new Map(Object.entries(ALIASES).map(([a, n]) => [n, a]));
|
|
292
|
+
const lines = TOOLS.map((t) => {
|
|
293
|
+
const name = aliasFor.get(t.name) || t.name;
|
|
294
|
+
const positional = (POSITIONAL[t.name] || []).map((p) => {
|
|
295
|
+
const req = ((t.inputSchema && t.inputSchema.required) || []).includes(p);
|
|
296
|
+
return req ? `<${p}>` : `[${p}]`;
|
|
297
|
+
}).join(' ');
|
|
298
|
+
const value = VALUE_ACTIONS.includes(t.name) ? ' (uses your AI provider)' : '';
|
|
299
|
+
return ` replywizard ${[name, positional].filter(Boolean).join(' ')}${value}`;
|
|
300
|
+
});
|
|
301
|
+
return [
|
|
302
|
+
'replywizard: read your WhatsApp from a terminal, through the Reply Wizard extension.',
|
|
303
|
+
'',
|
|
304
|
+
'It never sends or changes a message. There is no send command because there is no send',
|
|
305
|
+
'path in the extension, which is what keeps your WhatsApp account out of it.',
|
|
306
|
+
'',
|
|
307
|
+
'Commands',
|
|
308
|
+
' replywizard status is the bridge up, is the browser paired',
|
|
309
|
+
' replywizard pair how to finish pairing',
|
|
310
|
+
...lines,
|
|
311
|
+
'',
|
|
312
|
+
'Options',
|
|
313
|
+
' --json print the raw answer, for scripting',
|
|
314
|
+
' --limit <n> how many rows (where the command takes one)',
|
|
315
|
+
' --help this text',
|
|
316
|
+
'',
|
|
317
|
+
'It shares one local daemon with every AI client you have connected, so it works while',
|
|
318
|
+
'VS Code, Claude Code, Cursor or Antigravity are attached at the same time.',
|
|
319
|
+
].join('\n');
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/* ── the two commands that are not tools ───────────────────────────────────────────── */
|
|
323
|
+
|
|
324
|
+
export async function status(deps = {}) {
|
|
325
|
+
const base = deps.base || `http://${HOST}:${Number(process.env.RW_MCP_HTTP_PORT) || DEFAULT_HTTP_PORT}`;
|
|
326
|
+
const fetchImpl = deps.fetchImpl || fetch;
|
|
327
|
+
try {
|
|
328
|
+
const res = await fetchImpl(`${base}/healthz`);
|
|
329
|
+
if (!res.ok) return { running: false, reason: `the daemon answered HTTP ${res.status}` };
|
|
330
|
+
const body = await res.json();
|
|
331
|
+
return {
|
|
332
|
+
running: true,
|
|
333
|
+
version: body.version || null,
|
|
334
|
+
entry: body.entry || null,
|
|
335
|
+
extensionConnected: !!body.extensionConnected,
|
|
336
|
+
paired: !!body.paired,
|
|
337
|
+
sessions: body.sessions || 0,
|
|
338
|
+
tokenPresent: !!(deps.token !== undefined ? deps.token : readToken()),
|
|
339
|
+
};
|
|
340
|
+
} catch {
|
|
341
|
+
return { running: false, reason: 'nothing is listening; start any AI client, or run a command and it will start itself' };
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
export function statusLines(s) {
|
|
346
|
+
if (!s.running) {
|
|
347
|
+
return [`bridge: not running (${s.reason})`];
|
|
348
|
+
}
|
|
349
|
+
return [
|
|
350
|
+
'bridge: running',
|
|
351
|
+
/*
|
|
352
|
+
* The version AND the path, because they answer different halves of the same recurring
|
|
353
|
+
* support shape. A global install of this package shadows `npx`, so a published fix is
|
|
354
|
+
* inert until `npm uninstall -g`; and an absolute path in a client config breaks outright
|
|
355
|
+
* the next time nvm moves Node. Both present as "the extension is broken", and neither
|
|
356
|
+
* is visible from anywhere else. Printing the entry file makes an npx cache path, a
|
|
357
|
+
* global lib path and somebody's working tree tell themselves apart at a glance.
|
|
358
|
+
*/
|
|
359
|
+
`host: ${s.version || 'unknown'}${s.entry ? ` (${s.entry})` : ''}`,
|
|
360
|
+
`browser: ${s.extensionConnected ? 'connected' : 'not connected (open web.whatsapp.com with the extension enabled)'}`,
|
|
361
|
+
`paired: ${s.paired ? 'yes' : 'no (enter the 6-digit code in the extension, see `replywizard pair`)'}`,
|
|
362
|
+
`sessions: ${s.sessions}`,
|
|
363
|
+
`token: ${s.tokenPresent ? 'present' : 'missing (~/.replywizard-mcp/daemon-token.json)'}`,
|
|
364
|
+
];
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
export const PAIR_TEXT = [
|
|
368
|
+
'Pairing happens once per browser, and the code is printed by the daemon rather than by',
|
|
369
|
+
'this command, because the daemon is what the browser connects to.',
|
|
370
|
+
'',
|
|
371
|
+
'Where to find the 6-digit code:',
|
|
372
|
+
' 1. ~/.replywizard-mcp/pairing-code.txt (written every time a code is minted)',
|
|
373
|
+
' 2. your AI client\'s MCP log (the daemon prints it to stderr)',
|
|
374
|
+
' 3. a desktop notification',
|
|
375
|
+
'',
|
|
376
|
+
'Then: open web.whatsapp.com, click the Reply Wizard icon, and enter the code. Once',
|
|
377
|
+
'paired it reconnects on its own and never asks again.',
|
|
378
|
+
].join('\n');
|
|
379
|
+
|
|
380
|
+
/* ── entry ─────────────────────────────────────────────────────────────────────────── */
|
|
381
|
+
|
|
382
|
+
export async function main(argv = process.argv.slice(2), deps = {}) {
|
|
383
|
+
const out = deps.out || ((s) => console.log(s));
|
|
384
|
+
const word = argv[0];
|
|
385
|
+
|
|
386
|
+
if (!word || word === '--help' || word === '-h' || word === 'help') { out(helpText()); return 0; }
|
|
387
|
+
if (word === '--version' || word === '-v') { out(deps.version || 'dev'); return 0; }
|
|
388
|
+
|
|
389
|
+
if (word === 'status') {
|
|
390
|
+
const s = await status(deps);
|
|
391
|
+
const rest = parseArgs({ name: 'status', inputSchema: { properties: {} } }, argv.slice(1));
|
|
392
|
+
out(rest.json ? JSON.stringify(s, null, 2) : statusLines(s).join('\n'));
|
|
393
|
+
return s.running ? 0 : 1;
|
|
394
|
+
}
|
|
395
|
+
if (word === 'pair') { out(PAIR_TEXT); return 0; }
|
|
396
|
+
|
|
397
|
+
const tool = resolveCommand(word);
|
|
398
|
+
if (!tool) {
|
|
399
|
+
note(`replywizard: unknown command "${word}". Try \`replywizard --help\`.`);
|
|
400
|
+
return 2;
|
|
401
|
+
}
|
|
402
|
+
const { args, json, unknown } = parseArgs(tool, argv.slice(1));
|
|
403
|
+
if (unknown.length) {
|
|
404
|
+
note(`replywizard: ${tool.name} does not take ${unknown.join(', ')}. Try \`replywizard --help\`.`);
|
|
405
|
+
return 2;
|
|
406
|
+
}
|
|
407
|
+
const missing = missingRequired(tool, args);
|
|
408
|
+
if (missing.length) {
|
|
409
|
+
note(`replywizard: ${tool.name} needs ${missing.map((m) => `<${m}>`).join(' and ')}.`);
|
|
410
|
+
return 2;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// Start the daemon if it is not up, exactly as the stdio connector does, so the first
|
|
414
|
+
// command on a fresh machine works rather than explaining how to start a server.
|
|
415
|
+
const healthUrl = `${deps.base || `http://${HOST}:${Number(process.env.RW_MCP_HTTP_PORT) || DEFAULT_HTTP_PORT}`}/healthz`;
|
|
416
|
+
await ensureDaemon({
|
|
417
|
+
healthUrl,
|
|
418
|
+
spawnDaemon: deps.spawnDaemon || spawnDetachedDaemon,
|
|
419
|
+
fetchImpl: deps.fetchImpl || fetch,
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
const value = await callTool(tool.name, args, deps);
|
|
423
|
+
out(format(value, { json }));
|
|
424
|
+
return 0;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// Run only when invoked directly as the bin entry. argv[1] may be a bin SYMLINK while
|
|
428
|
+
// import.meta.url is the real file, so both sides are resolved before comparing: a raw ===
|
|
429
|
+
// never matches under npx or a global install and main() would silently no-op.
|
|
430
|
+
export function invokedAsEntry() {
|
|
431
|
+
if (!process.argv[1]) return false;
|
|
432
|
+
try {
|
|
433
|
+
return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
|
|
434
|
+
} catch {
|
|
435
|
+
return false;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
if (invokedAsEntry()) {
|
|
440
|
+
main().then((code) => process.exit(code)).catch((err) => {
|
|
441
|
+
note(`replywizard: ${(err && err.message) || err}`);
|
|
442
|
+
process.exit(1);
|
|
443
|
+
});
|
|
444
|
+
}
|
package/src/connector.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// connector.js
|
|
2
|
+
// connector.js: stdio↔daemon proxy for MCP clients that only speak stdio (WS-A2).
|
|
3
3
|
//
|
|
4
4
|
// Clients that support HTTP transport connect to the daemon directly
|
|
5
5
|
// (claude mcp add rw --transport http http://127.0.0.1:7870/mcp). Clients that only
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// 2. transparently pumps JSON-RPC frames between its stdio (facing the client) and
|
|
9
9
|
// a Streamable-HTTP client transport (facing the daemon).
|
|
10
10
|
//
|
|
11
|
-
// It owns no MCP logic
|
|
11
|
+
// It owns no MCP logic: it relays at the transport layer, so every tool/version the
|
|
12
12
|
// daemon supports works without changes here. ALL logging goes to stderr (stdout is
|
|
13
13
|
// reserved for the MCP stdio protocol). Mirrors Kaption's `@kaptionai/mcp-extension` shim.
|
|
14
14
|
|
|
@@ -26,7 +26,7 @@ const delay = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
|
26
26
|
|
|
27
27
|
/**
|
|
28
28
|
* Wire two MCP transports so every message on one is forwarded to the other, in both
|
|
29
|
-
* directions, and a close/error on either tears down the pair. Pure plumbing
|
|
29
|
+
* directions, and a close/error on either tears down the pair. Pure plumbing: no
|
|
30
30
|
* protocol knowledge. Returns nothing; assign the transports' lifecycle to the caller.
|
|
31
31
|
*/
|
|
32
32
|
export function pumpTransports(clientFacing, daemonFacing) {
|
|
@@ -65,7 +65,9 @@ export async function ensureDaemon({ healthUrl, spawnDaemon, fetchImpl = fetch,
|
|
|
65
65
|
}
|
|
66
66
|
|
|
67
67
|
// Spawn the daemon as a detached, fully background process that outlives this connector.
|
|
68
|
-
|
|
68
|
+
// Exported because `cli.js` needs exactly the same behaviour: the first command on a fresh
|
|
69
|
+
// machine must start the daemon rather than explain how to.
|
|
70
|
+
export function spawnDetachedDaemon() {
|
|
69
71
|
const daemonPath = fileURLToPath(new URL('./daemon.js', import.meta.url));
|
|
70
72
|
const child = spawn(process.execPath, [daemonPath], { detached: true, stdio: 'ignore', env: process.env });
|
|
71
73
|
child.unref();
|
package/src/daemon.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// daemon.js
|
|
2
|
+
// daemon.js: long-lived multi-client MCP daemon (Option A, WS-A1).
|
|
3
3
|
//
|
|
4
4
|
// The original index.js binds ONE stdio client and ONE extension WebSocket per
|
|
5
5
|
// process, so two AI clients fight over the port (the v3.1.5 EADDRINUSE case). This
|
|
6
6
|
// daemon instead:
|
|
7
7
|
// • owns a single ExtensionBridge (the extension dials into ws://127.0.0.1:7869), and
|
|
8
8
|
// • serves MCP over Streamable HTTP at http://127.0.0.1:7870/mcp to ANY number of
|
|
9
|
-
// clients
|
|
9
|
+
// clients: each client gets its own MCP session (a fresh Server + transport),
|
|
10
10
|
// and they all share the one extension bridge.
|
|
11
11
|
//
|
|
12
12
|
// Clients connect either directly (claude mcp add rw --transport http
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
|
|
21
21
|
import http from 'node:http';
|
|
22
22
|
import { randomUUID } from 'node:crypto';
|
|
23
|
-
import { realpathSync } from 'node:fs';
|
|
23
|
+
import { readFileSync, realpathSync } from 'node:fs';
|
|
24
24
|
import { fileURLToPath } from 'node:url';
|
|
25
25
|
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
26
26
|
import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
|
|
@@ -35,6 +35,28 @@ export const DEFAULT_HTTP_PORT = 7870;
|
|
|
35
35
|
const MAX_BODY_BYTES = 4 * 1024 * 1024;
|
|
36
36
|
const HOST = '127.0.0.1';
|
|
37
37
|
|
|
38
|
+
/**
|
|
39
|
+
* Which copy of this package is actually running, reported by /healthz.
|
|
40
|
+
*
|
|
41
|
+
* It exists because of one recurring support shape: a GLOBAL install of
|
|
42
|
+
* `replywizard-whatsapp-mcp` shadows `npx`, so a published fix is inert until the user runs
|
|
43
|
+
* `npm uninstall -g`, and an absolute path in a client config (`node /…/vX/lib/node_modules/…`)
|
|
44
|
+
* breaks outright the next time nvm moves Node. Both look exactly like "the extension is
|
|
45
|
+
* broken" and neither is visible from anywhere. `replywizard status` prints this, so the
|
|
46
|
+
* first question in a support thread has an answer the user can read off their own machine.
|
|
47
|
+
*
|
|
48
|
+
* Read once, and a failure is `null` rather than a throw: a missing package.json must not
|
|
49
|
+
* take the health endpoint down with it.
|
|
50
|
+
*/
|
|
51
|
+
export const HOST_VERSION = (() => {
|
|
52
|
+
try {
|
|
53
|
+
const here = fileURLToPath(new URL('../package.json', import.meta.url));
|
|
54
|
+
return JSON.parse(readFileSync(here, 'utf8')).version || null;
|
|
55
|
+
} catch {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
})();
|
|
59
|
+
|
|
38
60
|
const log = (...args) => console.error('[replywizard-mcp]', ...args);
|
|
39
61
|
|
|
40
62
|
// Read and JSON-parse a request body, bounded. Resolves undefined for an empty body.
|
|
@@ -94,7 +116,7 @@ export function createDaemon({
|
|
|
94
116
|
// Relay the distinct names of currently-connected MCP clients to the extension,
|
|
95
117
|
// so the options page can show which AI assistants are attached. Names come from
|
|
96
118
|
// each client's `initialize` clientInfo (the stdio connector pumps frames raw, so
|
|
97
|
-
// the real client's name
|
|
119
|
+
// the real client's name ("Antigravity", "Cursor", …) reaches us verbatim).
|
|
98
120
|
function publishClients() {
|
|
99
121
|
if (!bridge || typeof bridge.setConnectedClients !== 'function') return;
|
|
100
122
|
const seen = new Set();
|
|
@@ -145,7 +167,17 @@ export function createDaemon({
|
|
|
145
167
|
|
|
146
168
|
if (url.pathname === '/healthz') {
|
|
147
169
|
const connected = !!(bridge && bridge.socket && bridge.socket.readyState === 1);
|
|
148
|
-
writeJson(res, 200, {
|
|
170
|
+
writeJson(res, 200, {
|
|
171
|
+
ok: true,
|
|
172
|
+
version: HOST_VERSION,
|
|
173
|
+
// Where this daemon was actually loaded from, which is the other half of the same
|
|
174
|
+
// question: an npx cache path, a global lib path and a working tree all behave
|
|
175
|
+
// differently after an upgrade, and they are indistinguishable from a version alone.
|
|
176
|
+
entry: (() => { try { return fileURLToPath(import.meta.url); } catch { return null; } })(),
|
|
177
|
+
extensionConnected: connected,
|
|
178
|
+
paired: !!(bridge && bridge.paired),
|
|
179
|
+
sessions: sessions.size,
|
|
180
|
+
});
|
|
149
181
|
return;
|
|
150
182
|
}
|
|
151
183
|
if (url.pathname !== '/mcp') { rpcError(res, 404, 'Not found. MCP endpoint is /mcp'); return; }
|
|
@@ -236,14 +268,14 @@ export async function main() {
|
|
|
236
268
|
let shutdownFn = () => process.exit(0); // replaced below once daemon exists
|
|
237
269
|
const daemon = createDaemon({
|
|
238
270
|
bridge, httpPort, idleMs, staleSessionMs, sweepIntervalMs,
|
|
239
|
-
onIdle: () => { log(`Idle for ${Math.round(idleMs / 1000)}s with no sessions
|
|
271
|
+
onIdle: () => { log(`Idle for ${Math.round(idleMs / 1000)}s with no sessions, shutting down.`); shutdownFn(); },
|
|
240
272
|
});
|
|
241
273
|
|
|
242
274
|
// Single-instance lock: the HTTP port is the daemon's identity. If it is taken,
|
|
243
|
-
// another daemon already owns it
|
|
275
|
+
// another daemon already owns it: exit cleanly rather than crash-loop.
|
|
244
276
|
daemon.httpServer.on('error', (err) => {
|
|
245
277
|
if (err && err.code === 'EADDRINUSE') {
|
|
246
|
-
log(`HTTP port ${httpPort} is in use
|
|
278
|
+
log(`HTTP port ${httpPort} is in use, another Reply Wizard daemon is already running. Exiting.`);
|
|
247
279
|
try { bridge.close(); } catch { /* noop */ }
|
|
248
280
|
process.exit(0);
|
|
249
281
|
}
|
|
@@ -263,7 +295,7 @@ export async function main() {
|
|
|
263
295
|
|
|
264
296
|
// Run only when invoked directly as the bin entry (not when imported by tests).
|
|
265
297
|
// argv[1] may be a bin SYMLINK (npx / global / `rw-mcp-daemon`) while import.meta.url is the
|
|
266
|
-
// real file
|
|
298
|
+
// real file: resolve symlinks on both sides before comparing, else main() silently no-ops.
|
|
267
299
|
export function invokedAsEntry() {
|
|
268
300
|
if (!process.argv[1]) return false;
|
|
269
301
|
try {
|
package/src/daemonAuth.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// daemonAuth.js
|
|
1
|
+
// daemonAuth.js: local client-auth token for the MCP daemon (WS-A4).
|
|
2
2
|
//
|
|
3
3
|
// The daemon listens on loopback, but any local process could otherwise reach it and
|
|
4
4
|
// read WhatsApp through a paired extension. This adds a bearer token that clients must
|
|
@@ -25,6 +25,14 @@ function tokenFile(dir) {
|
|
|
25
25
|
return join(stateDir(dir), 'daemon-token.json');
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
+
// 0o600 is honoured on Linux and macOS: owner read/write, nobody else. It is NOT
|
|
29
|
+
// honoured on Windows, where Node's `mode` option controls only the read-only flag and
|
|
30
|
+
// stat reports 0666 regardless. There the file's protection is the ACL on the user
|
|
31
|
+
// profile directory, which keeps other *users* out but not another process running as
|
|
32
|
+
// this user, nor an administrator. That is a weaker guarantee, and it is stated here
|
|
33
|
+
// rather than implied by the constant. The token is local-only and rotatable
|
|
34
|
+
// (`rotateToken`), which is what keeps the difference tolerable rather than a hole.
|
|
35
|
+
// Surfaced by the cross-platform CI matrix, 2026-08-20.
|
|
28
36
|
function writeToken(token, dir) {
|
|
29
37
|
try {
|
|
30
38
|
mkdirSync(stateDir(dir), { recursive: true });
|
package/src/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// index.js
|
|
2
|
+
// index.js: replywizard-mcp entry point.
|
|
3
3
|
//
|
|
4
4
|
// Starts the local WebSocket server (which the extension dials into) and the MCP
|
|
5
5
|
// stdio server (which the AI client connects to), and bridges the two.
|
package/src/mcpServer.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// mcpServer.js
|
|
1
|
+
// mcpServer.js: the MCP server presented to the AI client over stdio.
|
|
2
2
|
//
|
|
3
3
|
// Translates MCP tools/list and tools/call into extension actions via the
|
|
4
4
|
// ExtensionBridge WebSocket. Returns tool results as JSON text content.
|
package/src/protocol.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// protocol.js
|
|
1
|
+
// protocol.js: wire contract shared with the Reply Wizard extension.
|
|
2
2
|
//
|
|
3
3
|
// This is a self-contained copy so the hub can be spun off into its own repo.
|
|
4
4
|
// While co-located in the extension repo, `tests/mcpProtocol.test.js` asserts the
|
package/src/tools.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// tools.js
|
|
1
|
+
// tools.js: MCP tool definitions exposed to the AI client.
|
|
2
2
|
//
|
|
3
3
|
// Each tool maps 1:1 to an extension action (see protocol.js ACTIONS). The hub's
|
|
4
4
|
// CallTool handler forwards `arguments` to the extension over the WebSocket and
|
|
@@ -40,7 +40,12 @@ export const TOOLS = [
|
|
|
40
40
|
inputSchema: {
|
|
41
41
|
type: 'object',
|
|
42
42
|
properties: {
|
|
43
|
-
chatId: {
|
|
43
|
+
chatId: {
|
|
44
|
+
type: 'string',
|
|
45
|
+
description: 'Chat id from list_chats, e.g. "84726351928374@lid" (one-to-one) or ' +
|
|
46
|
+
'"12345-1600000000@g.us" (group). A plain phone number in digits also resolves ' +
|
|
47
|
+
'to a one-to-one chat, e.g. "919110412164".',
|
|
48
|
+
},
|
|
44
49
|
limit: { type: 'integer', minimum: 1, maximum: 100, description: 'Max messages (default 30).' },
|
|
45
50
|
},
|
|
46
51
|
required: ['chatId'],
|
|
@@ -53,7 +58,13 @@ export const TOOLS = [
|
|
|
53
58
|
inputSchema: {
|
|
54
59
|
type: 'object',
|
|
55
60
|
properties: {
|
|
56
|
-
contactId: {
|
|
61
|
+
contactId: {
|
|
62
|
+
type: 'string',
|
|
63
|
+
description:
|
|
64
|
+
'Contact id from list_contacts, e.g. "84726351928374@lid" or the legacy ' +
|
|
65
|
+
'"919110412164@c.us". A plain phone number in digits also resolves, e.g. ' +
|
|
66
|
+
'"919110412164".',
|
|
67
|
+
},
|
|
57
68
|
},
|
|
58
69
|
required: ['contactId'],
|
|
59
70
|
additionalProperties: false,
|
|
@@ -80,7 +91,7 @@ export const TOOLS = [
|
|
|
80
91
|
inputSchema: {
|
|
81
92
|
type: 'object',
|
|
82
93
|
properties: {
|
|
83
|
-
chatId: { type: 'string', description: 'Chat id from list_chats.' },
|
|
94
|
+
chatId: { type: 'string', description: 'Chat id from list_chats, or a phone number in digits.' },
|
|
84
95
|
limit: { type: 'integer', minimum: 1, maximum: 100, description: 'Messages to summarize (default 40).' },
|
|
85
96
|
},
|
|
86
97
|
required: ['chatId'],
|
|
@@ -91,11 +102,11 @@ export const TOOLS = [
|
|
|
91
102
|
name: ACTIONS.SUGGEST_REPLY,
|
|
92
103
|
description:
|
|
93
104
|
'Draft a suggested reply (as the user) to a chat, based on its recent messages. ' +
|
|
94
|
-
'Returns the suggestion text only
|
|
105
|
+
'Returns the suggestion text only: it does NOT send anything.',
|
|
95
106
|
inputSchema: {
|
|
96
107
|
type: 'object',
|
|
97
108
|
properties: {
|
|
98
|
-
chatId: { type: 'string', description: 'Chat id from list_chats.' },
|
|
109
|
+
chatId: { type: 'string', description: 'Chat id from list_chats, or a phone number in digits.' },
|
|
99
110
|
limit: { type: 'integer', minimum: 1, maximum: 100, description: 'Context messages (default 20).' },
|
|
100
111
|
guidance: { type: 'string', description: 'Optional steer, e.g. "politely decline" or "ask for a call".' },
|
|
101
112
|
},
|
package/src/wsServer.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// wsServer.js
|
|
1
|
+
// wsServer.js: local WebSocket server the extension dials into.
|
|
2
2
|
//
|
|
3
3
|
// The Reply Wizard extension (background SW) is the WebSocket *client*; this hub is
|
|
4
4
|
// the server, bound to 127.0.0.1 only.
|
|
@@ -58,43 +58,101 @@ function sixDigitCode() {
|
|
|
58
58
|
return String(parseInt(randomBytes(4).toString('hex'), 16) % 1_000_000).padStart(6, '0');
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
+
// Number of wrong pairing codes tolerated before the active code is invalidated
|
|
62
|
+
// (a fresh handshake is then required to mint a new one). Bounds online guessing
|
|
63
|
+
// of the 6-digit (1e6) space to a handful of tries per code.
|
|
64
|
+
const MAX_PAIRING_ATTEMPTS = 5;
|
|
65
|
+
// A pairing code auto-expires this long after it is issued, so a code left on
|
|
66
|
+
// screen can't be brute-forced indefinitely.
|
|
67
|
+
const PAIRING_CODE_TTL_MS = 5 * 60_000;
|
|
68
|
+
|
|
69
|
+
// Decide whether a WebSocket handshake's Origin is allowed. WebSocket is NOT
|
|
70
|
+
// subject to same-origin policy, so any http(s) page a user has open could
|
|
71
|
+
// otherwise dial ws://127.0.0.1:<port> and race for the single connection slot
|
|
72
|
+
// to brute-force pairing. The legitimate client is the extension's MV3 service
|
|
73
|
+
// worker (Origin `chrome-extension://<id>`); a Node/CLI client sends no Origin.
|
|
74
|
+
// We allow those two and reject page origins (http/https/file/etc). Exported for
|
|
75
|
+
// tests. Default-allow only for a genuinely absent Origin, never for a page.
|
|
76
|
+
export function isAllowedOrigin(origin) {
|
|
77
|
+
if (!origin) return true; // Node/CLI client: no Origin header
|
|
78
|
+
if (origin.startsWith('chrome-extension://')) return true;
|
|
79
|
+
if (origin.startsWith('moz-extension://')) return true; // future Firefox/Edge port
|
|
80
|
+
return false; // http(s):// page or anything else
|
|
81
|
+
}
|
|
82
|
+
|
|
61
83
|
// Surface the pairing code as an OS desktop notification so a non-technical user
|
|
62
84
|
// sees it WITHOUT a terminal (the connector launches us in the background, where
|
|
63
85
|
// stderr is invisible). This is a valid out-of-band channel: only someone at the
|
|
64
86
|
// physical machine sees the toast, so it does not weaken pairing the way echoing
|
|
65
87
|
// 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
|
|
88
|
+
// never blocks (detached + unref + stdio ignore), silent if the tool is missing;
|
|
67
89
|
// the 0600 file and stderr remain as backstops. `code` is digits-only (no shell/
|
|
68
90
|
// AppleScript injection risk). Exported for tests.
|
|
69
|
-
export
|
|
70
|
-
|
|
71
|
-
|
|
91
|
+
export const PAIRING_NOTIFY_TITLE = 'Reply Wizard pairing code';
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The command that shows the toast on one platform. Split out from the spawn so the
|
|
95
|
+
* three branches can be asserted, and actually RUN, on all three platforms in CI: until
|
|
96
|
+
* 2026-08-20 the macOS and Windows branches had never once executed anywhere but a
|
|
97
|
+
* developer's own machine, and a toast that silently does nothing is invisible by
|
|
98
|
+
* construction (this whole function is best-effort by design).
|
|
99
|
+
*
|
|
100
|
+
* @param {string} code the 6-digit pairing code
|
|
101
|
+
* @param {string} [os] platform() by default; passed explicitly by tests
|
|
102
|
+
* @returns {{cmd: string, args: string[]}}
|
|
103
|
+
*/
|
|
104
|
+
export function pairingNotifyCommand(code, os = platform()) {
|
|
105
|
+
const title = PAIRING_NOTIFY_TITLE;
|
|
106
|
+
const body = `Enter ${code} in Reply Wizard (Settings > WhatsApp MCP) to connect.`;
|
|
107
|
+
if (os === 'darwin') {
|
|
108
|
+
// AppleScript has no parameter binding, so the text is escaped rather than trusted.
|
|
109
|
+
// `code` is digits-only today; this is what keeps that from being load-bearing.
|
|
110
|
+
const esc = (s) => s.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
|
|
111
|
+
return { cmd: 'osascript', args: ['-e', `display notification "${esc(body)}" with title "${esc(title)}"`] };
|
|
112
|
+
}
|
|
113
|
+
if (os === 'win32') {
|
|
114
|
+
// PowerShell balloon via WinForms: no external module required. System.Drawing is
|
|
115
|
+
// loaded explicitly because SystemIcons lives there; relying on WinForms to drag it
|
|
116
|
+
// in works on some hosts and throws on others, which is exactly the failure this
|
|
117
|
+
// branch could never see before it ran in CI.
|
|
118
|
+
const ps =
|
|
119
|
+
'Add-Type -AssemblyName System.Windows.Forms;' +
|
|
120
|
+
'Add-Type -AssemblyName System.Drawing;' +
|
|
121
|
+
'$n=New-Object System.Windows.Forms.NotifyIcon;' +
|
|
122
|
+
'$n.Icon=[System.Drawing.SystemIcons]::Information;' +
|
|
123
|
+
`$n.BalloonTipTitle=${JSON.stringify(title)};` +
|
|
124
|
+
`$n.BalloonTipText=${JSON.stringify(body)};` +
|
|
125
|
+
'$n.Visible=$true;$n.ShowBalloonTip(20000);Start-Sleep -Seconds 8;$n.Dispose()';
|
|
126
|
+
return { cmd: 'powershell', args: ['-NoProfile', '-WindowStyle', 'Hidden', '-Command', ps] };
|
|
127
|
+
}
|
|
128
|
+
// Linux / *nix: libnotify.
|
|
129
|
+
return { cmd: 'notify-send', args: ['-u', 'normal', '-t', '30000', title, body] };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Show the toast. Best-effort: never throws, never blocks, silent if the tool is missing.
|
|
134
|
+
*
|
|
135
|
+
* @param {string} code the six-digit pairing code
|
|
136
|
+
* @param {Function} [spawnFn] injected by tests, so proving "a missing notifier is not an
|
|
137
|
+
* outage" does not require actually spawning a notifier. It used to, and the cost was
|
|
138
|
+
* three real desktop toasts on the developer's screen every time the suite ran, two of
|
|
139
|
+
* them reading "Enter undefined" and "Enter " because those were the arguments under
|
|
140
|
+
* test. A test that has to be watched to be believed is a test nobody watches.
|
|
141
|
+
* @returns {boolean} whether a notification was attempted
|
|
142
|
+
*/
|
|
143
|
+
export function notifyPairingCode(code, spawnFn = spawn) {
|
|
144
|
+
// A toast reading "Enter undefined in Reply Wizard" is worse than no toast: it tells
|
|
145
|
+
// somebody to type a word. Nothing in the daemon can produce one today, because the
|
|
146
|
+
// code is minted immediately before this call, and that is exactly the kind of thing
|
|
147
|
+
// that stops being true later.
|
|
148
|
+
if (typeof code !== 'string' || !/^\d{4,10}$/.test(code)) return false;
|
|
72
149
|
try {
|
|
73
|
-
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
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 */ }
|
|
150
|
+
const { cmd, args } = pairingNotifyCommand(code);
|
|
151
|
+
const child = spawnFn(cmd, args, { stdio: 'ignore', detached: true });
|
|
152
|
+
child?.on?.('error', () => {}); // tool absent (e.g. no notify-send): stay silent
|
|
153
|
+
child?.unref?.();
|
|
154
|
+
return true;
|
|
155
|
+
} catch { /* notifications are best-effort */ return false; }
|
|
98
156
|
}
|
|
99
157
|
|
|
100
158
|
export class ExtensionBridge {
|
|
@@ -106,6 +164,11 @@ export class ExtensionBridge {
|
|
|
106
164
|
this.socket = null; // the single connected extension socket
|
|
107
165
|
this.paired = false;
|
|
108
166
|
this.pairingCode = null;
|
|
167
|
+
this.pairingAttempts = 0; // wrong-code counter for the current code
|
|
168
|
+
this.pairingCodeExpiresAt = 0; // absolute deadline; a reconnect reuses, never extends
|
|
169
|
+
this._pairingTimer = null; // TTL timer that expires the current code
|
|
170
|
+
this.maxPairingAttempts = opts.maxPairingAttempts ?? MAX_PAIRING_ATTEMPTS;
|
|
171
|
+
this.pairingCodeTtlMs = opts.pairingCodeTtlMs ?? PAIRING_CODE_TTL_MS;
|
|
109
172
|
this.sessionToken = loadToken();
|
|
110
173
|
this.pending = new Map(); // requestId → { entry, lane }
|
|
111
174
|
this.requestTimeoutMs = opts.requestTimeoutMs ?? 25_000;
|
|
@@ -130,7 +193,12 @@ export class ExtensionBridge {
|
|
|
130
193
|
|
|
131
194
|
listen() {
|
|
132
195
|
return new Promise((resolve, reject) => {
|
|
133
|
-
this.wss = new WebSocketServer({
|
|
196
|
+
this.wss = new WebSocketServer({
|
|
197
|
+
host: this.host,
|
|
198
|
+
port: this.port,
|
|
199
|
+
// Reject browser-page origins at the handshake (see isAllowedOrigin).
|
|
200
|
+
verifyClient: (info) => isAllowedOrigin(info.origin),
|
|
201
|
+
});
|
|
134
202
|
|
|
135
203
|
const onEarlyError = (err) => {
|
|
136
204
|
this.wss.removeListener('listening', onListening);
|
|
@@ -140,7 +208,7 @@ export class ExtensionBridge {
|
|
|
140
208
|
// `initialize` succeeds instead of getting EOF), but mark the bridge
|
|
141
209
|
// unavailable so action calls return a clear, actionable message.
|
|
142
210
|
this.portConflict = true;
|
|
143
|
-
log(`Port ${this.port} is already in use
|
|
211
|
+
log(`Port ${this.port} is already in use, another Reply Wizard hub is`);
|
|
144
212
|
log('probably already running. Starting without the WebSocket bridge;');
|
|
145
213
|
log('action calls will report the conflict. Close the other hub, or set');
|
|
146
214
|
log('RW_MCP_PORT to a free port if you intend to run more than one.');
|
|
@@ -166,6 +234,43 @@ export class ExtensionBridge {
|
|
|
166
234
|
});
|
|
167
235
|
}
|
|
168
236
|
|
|
237
|
+
// Issue a fresh pairing code: reset the wrong-attempt counter and arm a TTL
|
|
238
|
+
// timer that invalidates it if it isn't used in time.
|
|
239
|
+
//
|
|
240
|
+
// The expiry is recorded as an ABSOLUTE timestamp as well as a timer, because a
|
|
241
|
+
// reconnect now reuses a live code (see `_onConnection`) and the reuse must not push
|
|
242
|
+
// the deadline out. A rolling TTL would mean a client that reconnects every four
|
|
243
|
+
// minutes keeps one code alive forever, which is the opposite of what a TTL is for.
|
|
244
|
+
_setPairingCode(code) {
|
|
245
|
+
this.pairingCode = code;
|
|
246
|
+
this.pairingAttempts = 0;
|
|
247
|
+
this.pairingCodeExpiresAt = Date.now() + this.pairingCodeTtlMs;
|
|
248
|
+
clearTimeout(this._pairingTimer);
|
|
249
|
+
this._pairingTimer = setTimeout(() => {
|
|
250
|
+
this.pairingCode = null;
|
|
251
|
+
this.pairingCodeExpiresAt = 0;
|
|
252
|
+
clearPairingCode();
|
|
253
|
+
log('Pairing code expired; a new handshake is required to get a new one.');
|
|
254
|
+
}, this.pairingCodeTtlMs);
|
|
255
|
+
// Don't let the TTL timer keep the process (or tests) alive.
|
|
256
|
+
this._pairingTimer?.unref?.();
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** Is there a code a user could still usefully be typing? */
|
|
260
|
+
_pairingCodeIsLive() {
|
|
261
|
+
return Boolean(this.pairingCode) && Date.now() < this.pairingCodeExpiresAt;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// Invalidate the current pairing code and its TTL timer (on success, lockout,
|
|
265
|
+
// an expired-code reconnect, or shutdown).
|
|
266
|
+
_resetPairing() {
|
|
267
|
+
this.pairingCode = null;
|
|
268
|
+
this.pairingAttempts = 0;
|
|
269
|
+
this.pairingCodeExpiresAt = 0;
|
|
270
|
+
clearTimeout(this._pairingTimer);
|
|
271
|
+
this._pairingTimer = null;
|
|
272
|
+
}
|
|
273
|
+
|
|
169
274
|
_onConnection(ws) {
|
|
170
275
|
if (this.socket && this.socket.readyState === this.socket.OPEN) {
|
|
171
276
|
log('Rejecting extra connection; one extension is already connected.');
|
|
@@ -174,14 +279,34 @@ export class ExtensionBridge {
|
|
|
174
279
|
}
|
|
175
280
|
this.socket = ws;
|
|
176
281
|
this.paired = false;
|
|
177
|
-
|
|
282
|
+
// A LIVE pairing code survives the reconnect, deliberately.
|
|
283
|
+
//
|
|
284
|
+
// It used to be thrown away here and a new one minted on the next handshake, which
|
|
285
|
+
// meant the six digits the user was reading off a desktop toast went stale while they
|
|
286
|
+
// were typing them, and every reconnect fired another toast. The extension's service
|
|
287
|
+
// worker reconnects on its own schedule, so an unpaired user could watch three codes
|
|
288
|
+
// go by before entering one.
|
|
289
|
+
//
|
|
290
|
+
// Two properties make this safe rather than merely convenient, and both are tested:
|
|
291
|
+
// the deadline is NOT extended (see `_setPairingCode`), and the wrong-attempt counter
|
|
292
|
+
// is NOT reset. Carrying the counter is the load-bearing half: without it, closing and
|
|
293
|
+
// reopening the socket would hand an attacker another `maxPairingAttempts` guesses
|
|
294
|
+
// against the SAME code, over and over. Today's behaviour is safe only because the
|
|
295
|
+
// code changes each time, so preserving one without the other would be a regression.
|
|
296
|
+
if (!this._pairingCodeIsLive()) this._resetPairing();
|
|
178
297
|
log('Extension connected. Waiting for handshake…');
|
|
179
298
|
|
|
180
299
|
ws.on('message', (raw) => this._onMessage(raw));
|
|
181
300
|
ws.on('close', () => {
|
|
182
301
|
log('Extension disconnected.');
|
|
183
302
|
this._failAll(new Error('Extension disconnected.'));
|
|
184
|
-
if (this.socket === ws) {
|
|
303
|
+
if (this.socket === ws) {
|
|
304
|
+
this.socket = null;
|
|
305
|
+
this.paired = false;
|
|
306
|
+
// Same rule as `_onConnection`: a code the user may still be typing outlives the
|
|
307
|
+
// socket it was minted for. An expired one is cleared here so nothing lingers.
|
|
308
|
+
if (!this._pairingCodeIsLive()) this._resetPairing();
|
|
309
|
+
}
|
|
185
310
|
});
|
|
186
311
|
ws.on('error', (e) => log('Socket error:', e && e.message));
|
|
187
312
|
}
|
|
@@ -197,15 +322,24 @@ export class ExtensionBridge {
|
|
|
197
322
|
this._send({ method: CONTROL.AUTH_SUCCESS, params: { protocol: PROTOCOL_VERSION } });
|
|
198
323
|
this._sendClients(); // sync current assistants to a freshly reconnected extension
|
|
199
324
|
log('Reconnected with a valid session token (no pairing needed).');
|
|
325
|
+
} else if (this._pairingCodeIsLive()) {
|
|
326
|
+
// The code from before the reconnect is still good. Say so in the log and do NOT
|
|
327
|
+
// toast again: one code, one notification. The file is rewritten because it is a
|
|
328
|
+
// mirror rather than the source of truth, so this heals a deleted one.
|
|
329
|
+
writePairingCode(this.pairingCode);
|
|
330
|
+
const secondsLeft = Math.max(1, Math.round((this.pairingCodeExpiresAt - Date.now()) / 1000));
|
|
331
|
+
log(`Reconnected while unpaired; the existing code is still valid for ~${secondsLeft}s `
|
|
332
|
+
+ `(${this.pairingAttempts}/${this.maxPairingAttempts} wrong attempts used).`);
|
|
333
|
+
this._send({ method: CONTROL.PAIRING_REQUEST, params: { hub_name: 'Reply Wizard MCP', protocol: PROTOCOL_VERSION } });
|
|
200
334
|
} else {
|
|
201
|
-
this.
|
|
335
|
+
this._setPairingCode(sixDigitCode());
|
|
202
336
|
writePairingCode(this.pairingCode);
|
|
203
337
|
try { this._notify(this.pairingCode); } catch { /* notifier is best-effort */ }
|
|
204
338
|
log('');
|
|
205
339
|
log(' ┌──────────────────────────────────────────────┐');
|
|
206
340
|
log(` │ Reply Wizard pairing code: ${this.pairingCode} │`);
|
|
207
341
|
log(' └──────────────────────────────────────────────┘');
|
|
208
|
-
log(' Enter it in Reply Wizard →
|
|
342
|
+
log(' Enter it in Reply Wizard → Settings → WhatsApp MCP.');
|
|
209
343
|
log(' (A desktop notification with the code should also appear.)');
|
|
210
344
|
log(` (Running in the background? Read it from ${pairingFile()})`);
|
|
211
345
|
this._send({ method: CONTROL.PAIRING_REQUEST, params: { hub_name: 'Reply Wizard MCP', protocol: PROTOCOL_VERSION } });
|
|
@@ -214,27 +348,48 @@ export class ExtensionBridge {
|
|
|
214
348
|
}
|
|
215
349
|
|
|
216
350
|
if (msg.method === CONTROL.PAIRING_RESPONSE) {
|
|
217
|
-
|
|
351
|
+
// No active code (never issued, or already expired) → nothing to match.
|
|
352
|
+
if (!this.pairingCode) {
|
|
353
|
+
this._send({ method: CONTROL.PAIRING_FAILED, params: { reason: 'expired' } });
|
|
354
|
+
log('Pairing response ignored: no active code (expired or not requested).');
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
const ok = msg.params && msg.params.approved && msg.params.code === this.pairingCode;
|
|
218
358
|
if (ok) {
|
|
219
359
|
this.paired = true;
|
|
220
|
-
|
|
360
|
+
// 256-bit token (hex): matches the daemon's HTTP token strength, rather
|
|
361
|
+
// than randomUUID's ~122 bits of entropy (L1).
|
|
362
|
+
this.sessionToken = randomBytes(32).toString('hex');
|
|
221
363
|
saveToken(this.sessionToken);
|
|
222
364
|
clearPairingCode();
|
|
365
|
+
this._resetPairing();
|
|
223
366
|
this._send({ method: CONTROL.PAIRING_COMPLETE, params: { session_id: randomUUID(), session_token: this.sessionToken } });
|
|
224
367
|
this._send({ method: CONTROL.AUTH_SUCCESS, params: {} });
|
|
225
368
|
this._sendClients(); // sync current assistants right after pairing
|
|
226
369
|
log('Pairing approved.');
|
|
227
370
|
} else {
|
|
228
|
-
//
|
|
229
|
-
//
|
|
230
|
-
//
|
|
231
|
-
|
|
232
|
-
|
|
371
|
+
// Wrong code. Cap attempts to bound online brute-forcing: after the limit,
|
|
372
|
+
// invalidate the code entirely so a fresh handshake (and new code) is
|
|
373
|
+
// required. Below the limit, keep the same code active so a user who
|
|
374
|
+
// mistyped can retry without a new handshake.
|
|
375
|
+
this.pairingAttempts++;
|
|
376
|
+
if (this.pairingAttempts >= this.maxPairingAttempts) {
|
|
377
|
+
this._resetPairing();
|
|
378
|
+
clearPairingCode();
|
|
379
|
+
this._send({ method: CONTROL.PAIRING_FAILED, params: { reason: 'too_many_attempts' } });
|
|
380
|
+
log(`Pairing locked out after ${this.maxPairingAttempts} wrong attempts; code invalidated.`);
|
|
381
|
+
} else {
|
|
382
|
+
this._send({ method: CONTROL.PAIRING_FAILED, params: { reason: 'invalid_code' } });
|
|
383
|
+
log(`Pairing rejected or wrong code (${this.pairingAttempts}/${this.maxPairingAttempts}).`);
|
|
384
|
+
}
|
|
233
385
|
}
|
|
234
386
|
return;
|
|
235
387
|
}
|
|
236
388
|
|
|
237
389
|
if (msg.method === CONTROL.PONG) return;
|
|
390
|
+
// Extension heartbeat (keeps its MV3 service worker alive). Echo a PONG so the
|
|
391
|
+
// round-trip also counts as inbound activity on the extension's socket.
|
|
392
|
+
if (msg.method === CONTROL.PING) { this._send({ method: CONTROL.PONG }); return; }
|
|
238
393
|
|
|
239
394
|
// Action result correlation: settle the caller, free its lane slot, pump the lane.
|
|
240
395
|
if (msg.id && this.pending.has(msg.id)) {
|
|
@@ -332,7 +487,7 @@ export class ExtensionBridge {
|
|
|
332
487
|
_send(obj) {
|
|
333
488
|
// Never throw out of a send: if the socket is closing mid-write, socket.send can
|
|
334
489
|
// throw and would otherwise unwind _dispatch, leaking a lane slot until timeout.
|
|
335
|
-
// Swallowing here is safe
|
|
490
|
+
// Swallowing here is safe: the per-action timeout and _failAll(on-disconnect)
|
|
336
491
|
// both recover the in-flight entry.
|
|
337
492
|
try {
|
|
338
493
|
if (this.socket && this.socket.readyState === this.socket.OPEN) this.socket.send(JSON.stringify(obj));
|
|
@@ -367,6 +522,7 @@ export class ExtensionBridge {
|
|
|
367
522
|
}
|
|
368
523
|
|
|
369
524
|
close() {
|
|
525
|
+
this._resetPairing();
|
|
370
526
|
this._failAll(new Error('Hub shutting down.'));
|
|
371
527
|
if (this.wss) this.wss.close();
|
|
372
528
|
}
|