replywizard-whatsapp-mcp 0.2.7 → 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 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 extension**.
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
- v1 is **read + value only** and **local-only**: there is no path that can send or modify WhatsApp
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
@@ -78,6 +79,55 @@ hand the editor exactly the config above, plus a copy button for the Claude Code
78
79
  JSON stays on screen next to them: an install deeplink is opaque by nature, so reading it first is
79
80
  always an option.
80
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
+
81
131
  `RW_MCP_PORT` is optional (defaults to `7869`); set it on both sides if you change it.
82
132
 
83
133
  > **Pairing-code toast.** The code is also shown as a desktop notification (`osascript` on
@@ -95,7 +145,12 @@ always an option.
95
145
  ## Multiple AI assistants at once (daemon)
96
146
 
97
147
  This happens automatically with the `npx` config above: `replywizard-whatsapp-mcp` runs the connector,
98
- which starts one shared daemon. (The legacy `index.js` hub, run directly via `node .../src/index.js`, binds
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
99
154
  the WebSocket port itself, so **only one AI client can use it at a time**; a second launch hits
100
155
  `EADDRINUSE`.) The daemon architecture:
101
156
 
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "replywizard-whatsapp-mcp",
3
- "version": "0.2.7",
4
- "description": "Local MCP server that exposes WhatsApp Web (read + value tools) to AI clients via the Reply Wizard Chrome extension.",
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
@@ -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
- function spawnDetachedDaemon() {
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
@@ -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.
@@ -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, { ok: true, extensionConnected: connected, paired: !!(bridge && bridge.paired), sessions: sessions.size });
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; }