replywizard-whatsapp-mcp 0.3.3 → 0.5.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
@@ -35,6 +35,14 @@ lifted into its own repository without touching the extension.
35
35
  | `summarize_chat` | value | Bulleted summary of a chat's recent messages (uses your configured AI provider). |
36
36
  | `suggest_reply` | value | Drafts a reply as you, returns text only, **never sends**. |
37
37
  | `transcribe_voice_note` | value | Transcribes a voice note via your configured **cloud** speech-to-text provider. |
38
+ | `draft_message` | write | Puts text in one chat's message box under a "Drafted by" bar. Refuses a box that already holds text. **Never sends**: you read it and press Send. |
39
+ | `create_reminder` | write | Saves a Reply Wizard reminder for a chat (`dueAt` in ISO 8601 with a time zone, optional repeat). Chrome notifies you at that time; nothing is sent. |
40
+ | `save_template` | write | Saves a message template to Reply Wizard's Templates. |
41
+
42
+ **Write tools (0.5.0) are off until you allow them.** They need Reply Wizard 3.5.9 or later and the
43
+ switch "Let AI assistants save and draft" on the extension's WhatsApp MCP tab. Until then every call
44
+ answers with a sentence saying so and changes nothing. Every attempt, allowed or refused, is listed on
45
+ that tab, and none of the three can send a message.
38
46
 
39
47
  Value tools reuse the extension's existing AI/STT configuration; **your API keys never leave the
40
48
  extension** (the hub only sees tool arguments and results).
@@ -151,6 +159,30 @@ launch does. It identifies itself as `replywizard-cli`, so it appears beside you
151
159
 
152
160
  `RW_MCP_PORT` is optional (defaults to `7869`); set it on both sides if you change it.
153
161
 
162
+ ### From any other computer: `--remote` (0.4.0)
163
+
164
+ The local mode needs to run on the computer where Chrome is open. Remote mode runs anywhere, a
165
+ second laptop, a server or a cloud coding agent, and reaches the same browser through Reply
166
+ Wizard's relay at `https://mcp.replywizard.app`, the server claude.ai and ChatGPT use. It needs a
167
+ paid Reply Wizard plan and the **Use from claude.ai and ChatGPT** switch on in the extension's
168
+ WhatsApp MCP tab.
169
+
170
+ ```bash
171
+ replywizard login # once: opens your browser to sign in and approve
172
+ replywizard chats --remote --limit 10
173
+ REPLYWIZARD_REMOTE=1 replywizard summarize 919110412164 # the same, for an agent's shell
174
+ replywizard status --remote # signed in, and is your browser reachable
175
+ replywizard logout
176
+ ```
177
+
178
+ Sign-in is OAuth 2.1 with PKCE over a loopback redirect on `127.0.0.1`, the flow Claude Code uses.
179
+ With no browser on the machine, open the printed link on any device, approve, and paste the
180
+ address the browser lands on back into the terminal. The sign-in lives in
181
+ `~/.replywizard-mcp/remote.json` (0600): a one-hour access token and a 30-day refresh token that
182
+ rotates on every use. Disconnect it from My account at <https://replywizard.app/account>, or with
183
+ `replywizard logout`. What a command reads passes through the relay on its way to you and is not
184
+ stored there.
185
+
154
186
  > **Pairing-code toast.** The code is also shown as a desktop notification (`osascript` on
155
187
  > macOS, a PowerShell balloon on Windows, `notify-send` on Linux), because the connector is
156
188
  > usually launched in the background where stderr is invisible. It is best-effort and never
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "replywizard-whatsapp-mcp",
3
- "version": "0.3.3",
3
+ "version": "0.5.0",
4
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": {
package/src/cli.js CHANGED
@@ -33,10 +33,11 @@
33
33
  import { realpathSync } from 'node:fs';
34
34
  import { fileURLToPath } from 'node:url';
35
35
  import { TOOLS } from './tools.js';
36
- import { ACTIONS, VALUE_ACTIONS } from './protocol.js';
36
+ import { ACTIONS, VALUE_ACTIONS, WRITE_ACTIONS } from './protocol.js';
37
37
  import { DEFAULT_HTTP_PORT } from './daemon.js';
38
38
  import { ensureDaemon, spawnDetachedDaemon } from './connector.js';
39
39
  import { readToken } from './daemonAuth.js';
40
+ import { wantsRemote, login, logout, callRemote, remoteStatus, remoteStatusLines } from './remote.js';
40
41
 
41
42
  const HOST = '127.0.0.1';
42
43
  const CLIENT_NAME = 'replywizard-cli';
@@ -60,6 +61,9 @@ const POSITIONAL = {
60
61
  [ACTIONS.SUMMARIZE_CHAT]: ['chatId'],
61
62
  [ACTIONS.SUGGEST_REPLY]: ['chatId', 'guidance'],
62
63
  [ACTIONS.TRANSCRIBE_VOICE_NOTE]: ['messageId'],
64
+ [ACTIONS.DRAFT_MESSAGE]: ['chatId', 'text'],
65
+ [ACTIONS.CREATE_REMINDER]: ['chatId', 'text', 'dueAt'],
66
+ [ACTIONS.SAVE_TEMPLATE]: ['body'],
63
67
  };
64
68
 
65
69
  /** Shorter names for the two longest tools. The tool name always works as well. */
@@ -71,6 +75,9 @@ const ALIASES = {
71
75
  summarize: ACTIONS.SUMMARIZE_CHAT,
72
76
  suggest: ACTIONS.SUGGEST_REPLY,
73
77
  transcribe: ACTIONS.TRANSCRIBE_VOICE_NOTE,
78
+ draft: ACTIONS.DRAFT_MESSAGE,
79
+ remind: ACTIONS.CREATE_REMINDER,
80
+ template: ACTIONS.SAVE_TEMPLATE,
74
81
  };
75
82
 
76
83
  const toolByName = new Map(TOOLS.map((t) => [t.name, t]));
@@ -295,7 +302,8 @@ export function helpText() {
295
302
  const req = ((t.inputSchema && t.inputSchema.required) || []).includes(p);
296
303
  return req ? `<${p}>` : `[${p}]`;
297
304
  }).join(' ');
298
- const value = VALUE_ACTIONS.includes(t.name) ? ' (uses your AI provider)' : '';
305
+ const value = VALUE_ACTIONS.includes(t.name) ? ' (uses your AI provider)'
306
+ : WRITE_ACTIONS.includes(t.name) ? ' (off until you allow it; never sends)' : '';
299
307
  return ` replywizard ${[name, positional].filter(Boolean).join(' ')}${value}`;
300
308
  });
301
309
  return [
@@ -309,6 +317,13 @@ export function helpText() {
309
317
  ' replywizard pair how to finish pairing',
310
318
  ...lines,
311
319
  '',
320
+ 'From any other computer (needs a Reply Wizard plan)',
321
+ ' replywizard login sign in once; opens your browser',
322
+ ' replywizard <command> --remote run any command above through mcp.replywizard.app',
323
+ ' replywizard status --remote signed in, and is your browser reachable',
324
+ ' replywizard logout sign out and forget the sign-in on this computer',
325
+ ' REPLYWIZARD_REMOTE=1 the same as --remote on every command, for an agent',
326
+ '',
312
327
  'Options',
313
328
  ' --json print the raw answer, for scripting',
314
329
  ' --limit <n> how many rows (where the command takes one)',
@@ -398,11 +413,29 @@ export const PAIR_TEXT = [
398
413
 
399
414
  export async function main(argv = process.argv.slice(2), deps = {}) {
400
415
  const out = deps.out || ((s) => console.log(s));
416
+ // Remote mode (ROADMAP row 20): the same commands through the relay instead of the local daemon.
417
+ const remote = wantsRemote(argv, deps.env || process.env);
418
+ argv = argv.filter((a) => a !== '--remote');
401
419
  const word = argv[0];
402
420
 
421
+ if (word === 'login') {
422
+ await login({ ...deps, note: deps.note || note });
423
+ out('Signed in. Try: replywizard chats --remote');
424
+ return 0;
425
+ }
426
+ if (word === 'logout') {
427
+ out((await logout(deps)) ? 'Signed out. This computer no longer holds a Reply Wizard sign-in.' : 'Not signed in.');
428
+ return 0;
429
+ }
430
+
403
431
  if (!word || word === '--help' || word === '-h' || word === 'help') { out(helpText()); return 0; }
404
432
  if (word === '--version' || word === '-v') { out(deps.version || 'dev'); return 0; }
405
433
 
434
+ if (word === 'status' && remote) {
435
+ const s = await remoteStatus(deps);
436
+ out(argv.includes('--json') ? JSON.stringify(s, null, 2) : remoteStatusLines(s).join('\n'));
437
+ return s.signedIn && s.browser === 'connected' ? 0 : 1;
438
+ }
406
439
  if (word === 'status') {
407
440
  const s = await status(deps);
408
441
  const rest = parseArgs({ name: 'status', inputSchema: { properties: {} } }, argv.slice(1));
@@ -427,6 +460,11 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
427
460
  return 2;
428
461
  }
429
462
 
463
+ if (remote) {
464
+ out(format(await callRemote(tool.name, args, deps), { json }));
465
+ return 0;
466
+ }
467
+
430
468
  // Start the daemon if it is not up, exactly as the stdio connector does, so the first
431
469
  // command on a fresh machine works rather than explaining how to start a server.
432
470
  const healthUrl = `${deps.base || `http://${HOST}:${Number(process.env.RW_MCP_HTTP_PORT) || DEFAULT_HTTP_PORT}`}/healthz`;
package/src/mcpServer.js CHANGED
@@ -30,8 +30,13 @@ export function createMcpServer(bridge) {
30
30
  };
31
31
  }
32
32
  try {
33
- const result = await bridge.callAction(action, args || {});
34
- return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
33
+ // The client's own name from its `initialize`, so a draft can say who wrote it
34
+ // ("Drafted by Claude"). Display text only; the extension bounds and cleans it.
35
+ const client = (server.getClientVersion && server.getClientVersion() && server.getClientVersion().name) || null;
36
+ const result = await bridge.callAction(action, args || {}, { client });
37
+ // Compact, not pretty-printed (2026-10-02): every result is read by a model, and the
38
+ // indentation was paid for in tokens on every call. The remote relay answers the same way.
39
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
35
40
  } catch (err) {
36
41
  return {
37
42
  isError: true,
package/src/protocol.js CHANGED
@@ -22,6 +22,10 @@ export const ACTIONS = Object.freeze({
22
22
  TRANSCRIBE_VOICE_NOTE: 'transcribe_voice_note',
23
23
  SUMMARIZE_CHAT: 'summarize_chat',
24
24
  SUGGEST_REPLY: 'suggest_reply',
25
+ // write, off until the person allows it (W0: our own storage; W1: a draft, never a send)
26
+ CREATE_REMINDER: 'create_reminder',
27
+ SAVE_TEMPLATE: 'save_template',
28
+ DRAFT_MESSAGE: 'draft_message',
25
29
  });
26
30
 
27
31
  export const READ_ACTIONS = Object.freeze([
@@ -30,6 +34,9 @@ export const READ_ACTIONS = Object.freeze([
30
34
  export const VALUE_ACTIONS = Object.freeze([
31
35
  ACTIONS.TRANSCRIBE_VOICE_NOTE, ACTIONS.SUMMARIZE_CHAT, ACTIONS.SUGGEST_REPLY,
32
36
  ]);
37
+ export const WRITE_ACTIONS = Object.freeze([
38
+ ACTIONS.CREATE_REMINDER, ACTIONS.SAVE_TEMPLATE, ACTIONS.DRAFT_MESSAGE,
39
+ ]);
33
40
 
34
41
  export const STATUS = Object.freeze({
35
42
  DISCONNECTED: 'disconnected',
package/src/remote.js ADDED
@@ -0,0 +1,239 @@
1
+ // remote.js: the `replywizard` command line through the REMOTE relay (ROADMAP row 20).
2
+ //
3
+ // The local mode talks to a daemon on 127.0.0.1, so it works only on the computer where Chrome
4
+ // is open. Remote mode talks to https://mcp.replywizard.app/mcp, the same server claude.ai and
5
+ // ChatGPT use, so it works from any machine: a second laptop, a server, a cloud coding agent.
6
+ // The answers still come from the person's own browser; the relay only carries them.
7
+ //
8
+ // SIGN-IN is OAuth 2.1 with PKCE over a loopback redirect, the flow Claude Code uses (RFC 8252):
9
+ // `replywizard login` registers itself (DCR), opens the consent page, and listens on
10
+ // 127.0.0.1:<random port>/callback for the code. On a machine with no browser the person opens
11
+ // the link anywhere, approves, and pastes the address the browser landed on back into the
12
+ // terminal; the code in it is useless without the verifier this process holds.
13
+ //
14
+ // THE CREDENTIALS FILE is `~/.replywizard-mcp/remote.json`, mode 0600. It holds a one-hour
15
+ // access token and a 30-day refresh token that rotates on every use; a reused refresh token
16
+ // revokes the whole sign-in at the server, so the file is rewritten after every refresh.
17
+
18
+ import { createServer } from 'node:http';
19
+ import { createHash, randomBytes } from 'node:crypto';
20
+ import { join } from 'node:path';
21
+ import { writeFileSync, rmSync, mkdirSync, chmodSync } from 'node:fs';
22
+ import { spawn } from 'node:child_process';
23
+ import { createInterface } from 'node:readline';
24
+ import { stateDir, readJson } from './stateStore.js';
25
+
26
+ export const RELAY = 'https://mcp.replywizard.app';
27
+ export const RESOURCE = `${RELAY}/mcp`;
28
+ export const CLIENT_NAME = 'Reply Wizard command line';
29
+ const REFRESH_EARLY_MS = 5 * 60 * 1000;
30
+ const LOGIN_TIMEOUT_MS = 10 * 60 * 1000;
31
+
32
+ const b64u = (buf) => Buffer.from(buf).toString('base64url');
33
+ export const credentialsFile = () => join(stateDir(), 'remote.json');
34
+
35
+ export function readCredentials() {
36
+ const c = readJson(credentialsFile());
37
+ return c && typeof c.refresh_token === 'string' && typeof c.client_id === 'string' ? c : null;
38
+ }
39
+
40
+ export function writeCredentials(c) {
41
+ const dir = stateDir();
42
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
43
+ const file = credentialsFile();
44
+ writeFileSync(file, JSON.stringify(c, null, 2), { mode: 0o600 });
45
+ try { chmodSync(file, 0o600); } catch { /* Windows */ }
46
+ }
47
+
48
+ /** Is remote mode asked for? `--remote` anywhere, or REPLYWIZARD_REMOTE=1 for an agent's shell. */
49
+ export function wantsRemote(argv, env = process.env) {
50
+ return argv.includes('--remote') || env.REPLYWIZARD_REMOTE === '1';
51
+ }
52
+
53
+ async function postForm(fetchImpl, url, form) {
54
+ const res = await fetchImpl(url, {
55
+ method: 'POST',
56
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
57
+ body: new URLSearchParams(form).toString(),
58
+ });
59
+ const body = await res.json().catch(() => ({}));
60
+ return { status: res.status, body };
61
+ }
62
+
63
+ /** Open a URL in the default browser, best effort. Returns false where there is none. */
64
+ export function openBrowser(url, spawnImpl = spawn, platform = process.platform) {
65
+ const cmd = platform === 'darwin' ? ['open', [url]] : platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : ['xdg-open', [url]];
66
+ try {
67
+ const child = spawnImpl(cmd[0], cmd[1], { stdio: 'ignore', detached: true });
68
+ child.on?.('error', () => {});
69
+ child.unref?.();
70
+ return true;
71
+ } catch { return false; }
72
+ }
73
+
74
+ /** Pull `code` and `state` out of a callback URL, whether it arrived at the listener or was pasted. */
75
+ export function parseCallback(text) {
76
+ try {
77
+ const u = new URL(String(text).trim());
78
+ return { code: u.searchParams.get('code'), state: u.searchParams.get('state'), error: u.searchParams.get('error') };
79
+ } catch { return null; }
80
+ }
81
+
82
+ /**
83
+ * Sign in. Resolves with the stored credentials.
84
+ * @param {object} deps fetchImpl, open, note, input (a readable stream for the paste fallback), now
85
+ */
86
+ export async function login(deps = {}) {
87
+ const fetchImpl = deps.fetchImpl || fetch;
88
+ const note = deps.note || ((s) => console.error(s));
89
+ const open = deps.open || openBrowser;
90
+
91
+ // A loopback listener on a port the OS picks. Registered redirect is port-agnostic.
92
+ let resolveCode;
93
+ const got = new Promise((r) => { resolveCode = r; });
94
+ const server = createServer((req, res) => {
95
+ const cb = parseCallback(`http://127.0.0.1${req.url}`);
96
+ if (!cb || (!cb.code && !cb.error) || !req.url.startsWith('/callback')) { res.writeHead(404); res.end(); return; }
97
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
98
+ res.end(cb.error
99
+ ? '<p style="font:16px system-ui">Reply Wizard was not connected. You can close this tab.</p>'
100
+ : '<p style="font:16px system-ui">Signed in. You can close this tab and go back to the terminal.</p>');
101
+ resolveCode(cb);
102
+ });
103
+ await new Promise((r) => server.listen(0, '127.0.0.1', r));
104
+ const port = server.address().port;
105
+ const redirectUri = `http://127.0.0.1:${port}/callback`;
106
+
107
+ try {
108
+ const saved = readCredentials();
109
+ let clientId = saved && saved.client_id;
110
+ if (!clientId) {
111
+ const reg = await fetchImpl(`${RELAY}/register`, {
112
+ method: 'POST',
113
+ headers: { 'content-type': 'application/json' },
114
+ body: JSON.stringify({ client_name: CLIENT_NAME, redirect_uris: ['http://127.0.0.1/callback'], token_endpoint_auth_method: 'none' }),
115
+ });
116
+ const body = await reg.json().catch(() => ({}));
117
+ if (!reg.ok || !body.client_id) throw new Error('Reply Wizard did not accept the sign-in request. Try again in a minute.');
118
+ clientId = body.client_id;
119
+ }
120
+
121
+ const verifier = b64u(randomBytes(48));
122
+ const state = b64u(randomBytes(16));
123
+ const challenge = b64u(createHash('sha256').update(verifier).digest());
124
+ const url = `${RELAY}/authorize?${new URLSearchParams({
125
+ response_type: 'code', client_id: clientId, redirect_uri: redirectUri, state,
126
+ code_challenge: challenge, code_challenge_method: 'S256', scope: 'wa:read offline_access', resource: RESOURCE,
127
+ })}`;
128
+
129
+ note('Sign in to Reply Wizard in your browser. If it does not open, open this link:');
130
+ note('');
131
+ note(` ${url}`);
132
+ note('');
133
+ note('No browser on this machine? Open the link on any device, approve, then paste the');
134
+ note('address the browser lands on (it starts with http://127.0.0.1) here and press Enter.');
135
+ open(url);
136
+
137
+ // The paste fallback, raced against the listener.
138
+ let rl = null;
139
+ const pasted = new Promise((resolvePaste) => {
140
+ const input = deps.input || (process.stdin.isTTY ? process.stdin : null);
141
+ if (!input) return;
142
+ rl = createInterface({ input });
143
+ rl.on('line', (line) => { const cb = parseCallback(line); if (cb && (cb.code || cb.error)) resolvePaste(cb); });
144
+ });
145
+ let timer;
146
+ const timeout = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Sign-in timed out. Run replywizard login again.')), deps.timeoutMs || LOGIN_TIMEOUT_MS); });
147
+ const cb = await Promise.race([got, pasted, timeout]).finally(() => { clearTimeout(timer); rl?.close(); });
148
+
149
+ if (cb.error) throw new Error(cb.error === 'access_denied' ? 'Sign-in was declined.' : `Sign-in failed (${cb.error}).`);
150
+ if (cb.state !== state) throw new Error('That sign-in answer is for a different attempt. Run replywizard login again.');
151
+
152
+ const tok = await postForm(fetchImpl, `${RELAY}/token`, {
153
+ grant_type: 'authorization_code', code: cb.code, redirect_uri: redirectUri, client_id: clientId,
154
+ code_verifier: verifier, resource: RESOURCE,
155
+ });
156
+ if (tok.status !== 200 || !tok.body.access_token) throw new Error('Reply Wizard did not complete the sign-in. Run replywizard login again.');
157
+ const now = (deps.now || Date.now)();
158
+ const creds = {
159
+ client_id: clientId,
160
+ access_token: tok.body.access_token,
161
+ refresh_token: tok.body.refresh_token,
162
+ expires_at: now + (tok.body.expires_in || 3600) * 1000,
163
+ };
164
+ writeCredentials(creds);
165
+ return creds;
166
+ } finally {
167
+ server.close();
168
+ }
169
+ }
170
+
171
+ /** A live access token, refreshing (and rewriting the file) when it is near expiry. */
172
+ export async function accessToken(deps = {}, { force = false } = {}) {
173
+ const fetchImpl = deps.fetchImpl || fetch;
174
+ const now = (deps.now || Date.now)();
175
+ const c = readCredentials();
176
+ if (!c) throw new Error('Not signed in. Run replywizard login first.');
177
+ if (!force && c.access_token && c.expires_at - now > REFRESH_EARLY_MS) return c.access_token;
178
+ const r = await postForm(fetchImpl, `${RELAY}/token`, { grant_type: 'refresh_token', refresh_token: c.refresh_token, client_id: c.client_id });
179
+ if (r.status !== 200 || !r.body.access_token) {
180
+ if (r.body && r.body.error === 'invalid_grant') {
181
+ rmSync(credentialsFile(), { force: true });
182
+ throw new Error('Your Reply Wizard sign-in has ended (it was disconnected, or the plan stopped). Run replywizard login again.');
183
+ }
184
+ throw new Error('Could not reach Reply Wizard to renew the sign-in. Check your connection.');
185
+ }
186
+ writeCredentials({ ...c, access_token: r.body.access_token, refresh_token: r.body.refresh_token, expires_at: now + (r.body.expires_in || 3600) * 1000 });
187
+ return r.body.access_token;
188
+ }
189
+
190
+ /** One tool call through the relay. Returns the parsed payload, or throws its sentence. */
191
+ export async function callRemote(name, args, deps = {}) {
192
+ const fetchImpl = deps.fetchImpl || fetch;
193
+ const post = (token) => fetchImpl(RESOURCE, {
194
+ method: 'POST',
195
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
196
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }),
197
+ });
198
+ let res = await post(await accessToken(deps));
199
+ if (res.status === 401) res = await post(await accessToken(deps, { force: true }));
200
+ if (res.status === 401) throw new Error('Reply Wizard did not accept the sign-in. Run replywizard login again.');
201
+ if (!res.ok) throw new Error(`The Reply Wizard relay answered HTTP ${res.status}. Try again in a moment.`);
202
+ const msg = await res.json();
203
+ if (msg.error) throw new Error(msg.error.message || 'The call failed.');
204
+ const body = ((msg.result && msg.result.content) || []).map((c) => c.text).filter(Boolean).join('\n');
205
+ if (msg.result && msg.result.isError) throw new Error(body || 'The call failed.');
206
+ try { return JSON.parse(body); } catch { return body; }
207
+ }
208
+
209
+ /** Sign out: revoke at the server (which ends the whole grant) and delete the file. */
210
+ export async function logout(deps = {}) {
211
+ const fetchImpl = deps.fetchImpl || fetch;
212
+ const c = readCredentials();
213
+ if (c) {
214
+ try { await postForm(fetchImpl, `${RELAY}/revoke`, { token: c.refresh_token, client_id: c.client_id }); } catch { /* deleted locally either way */ }
215
+ }
216
+ rmSync(credentialsFile(), { force: true });
217
+ return !!c;
218
+ }
219
+
220
+ /** `replywizard status --remote`: signed in, and can the relay reach this account's browser? */
221
+ export async function remoteStatus(deps = {}) {
222
+ const c = readCredentials();
223
+ if (!c) return { signedIn: false };
224
+ try {
225
+ const pong = await callRemote('ping', {}, deps);
226
+ return { signedIn: true, browser: pong && pong.pong === true ? 'connected' : 'not_reachable', message: pong && pong.message };
227
+ } catch (e) {
228
+ return { signedIn: !!readCredentials(), browser: 'unknown', message: e.message };
229
+ }
230
+ }
231
+
232
+ export function remoteStatusLines(s) {
233
+ if (!s.signedIn) return ['remote: not signed in (run replywizard login)'];
234
+ return [
235
+ 'remote: signed in (https://mcp.replywizard.app)',
236
+ `browser: ${s.browser === 'connected' ? 'connected' : s.browser === 'not_reachable' ? 'not reachable' : 'unknown'}`,
237
+ ...(s.message && s.browser !== 'connected' ? [` ${s.message}`] : []),
238
+ ];
239
+ }
package/src/tools.js CHANGED
@@ -6,9 +6,32 @@
6
6
 
7
7
  import { ACTIONS } from './protocol.js';
8
8
 
9
+ /*
10
+ * MCP tool annotations (2026-10-02, docs/REMOTE_MCP_RELAY_PLAN.md §3). ChatGPT treats any tool
11
+ * WITHOUT `readOnlyHint: true` as a write and asks the person to confirm every call, so all eight
12
+ * of these would have prompted on every read. None of them changes anything in WhatsApp.
13
+ *
14
+ * `openWorldHint` is true for the three value tools and false for the rest, because those three
15
+ * send chat text or audio to the person's own AI provider from their browser; the read tools
16
+ * answer from the WhatsApp Web page alone. Shared by the local host and the remote relay, which
17
+ * imports this file, so the two can never describe a tool differently.
18
+ */
19
+ const READ = Object.freeze({ readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false });
20
+ const VALUE = Object.freeze({ readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true });
21
+ /*
22
+ * The write tools (row 20 Phase 4, tiers W0 and W1). `readOnlyHint: false` on purpose, so ChatGPT
23
+ * and Claude ask the person before each call. None of them sends: two save to Reply Wizard's own
24
+ * storage and the third puts text in a message box for the person to send. They are refused by the
25
+ * extension until the person turns on "Let AI assistants save and draft" in Reply Wizard.
26
+ */
27
+ const WRITE = Object.freeze({ readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false });
28
+ const OFF_UNTIL_ALLOWED = ' Refused until the user turns on "Let AI assistants save and draft" in Reply Wizard\'s WhatsApp MCP settings.';
29
+
9
30
  export const TOOLS = [
10
31
  {
11
32
  name: ACTIONS.PING,
33
+ title: 'Check the WhatsApp connection',
34
+ annotations: { title: 'Check the WhatsApp connection', ...READ },
12
35
  description:
13
36
  'Health check. Confirms the Reply Wizard extension is connected and an active ' +
14
37
  'WhatsApp Web tab can be reached. Returns { pong: true }.',
@@ -20,6 +43,8 @@ export const TOOLS = [
20
43
  },
21
44
  {
22
45
  name: ACTIONS.LIST_CHATS,
46
+ title: 'List WhatsApp chats',
47
+ annotations: { title: 'List WhatsApp chats', ...READ },
23
48
  description:
24
49
  'List the user\'s WhatsApp chats, most recently active first. Returns id, name, ' +
25
50
  'phone, isGroup, unreadCount and timestamp for each. Use the returned `id` with ' +
@@ -35,6 +60,8 @@ export const TOOLS = [
35
60
  },
36
61
  {
37
62
  name: ACTIONS.GET_MESSAGES,
63
+ title: 'Read messages in a chat',
64
+ annotations: { title: 'Read messages in a chat', ...READ },
38
65
  description:
39
66
  'Get recent messages for a chat (those currently loaded in WhatsApp Web), oldest→newest. ' +
40
67
  'Each message has sender, timestamp, type and text (voice notes report duration; use ' +
@@ -56,6 +83,8 @@ export const TOOLS = [
56
83
  },
57
84
  {
58
85
  name: ACTIONS.GET_CONTACT,
86
+ title: 'Look up a contact',
87
+ annotations: { title: 'Look up a contact', ...READ },
59
88
  description: 'Look up a single contact by id. Returns name, pushname and business/contact flags.',
60
89
  inputSchema: {
61
90
  type: 'object',
@@ -74,6 +103,8 @@ export const TOOLS = [
74
103
  },
75
104
  {
76
105
  name: ACTIONS.LIST_CONTACTS,
106
+ title: 'List contacts',
107
+ annotations: { title: 'List contacts', ...READ },
77
108
  description:
78
109
  'List the user\'s saved WhatsApp contacts. By default only address-book contacts are returned.',
79
110
  inputSchema: {
@@ -87,6 +118,8 @@ export const TOOLS = [
87
118
  },
88
119
  {
89
120
  name: ACTIONS.SUMMARIZE_CHAT,
121
+ title: 'Summarise a chat',
122
+ annotations: { title: 'Summarise a chat', ...VALUE },
90
123
  description:
91
124
  'Summarize a chat\'s recent messages into concise bullet points (key points, ' +
92
125
  'decisions, action items). Uses the user\'s configured AI provider in the extension.',
@@ -102,6 +135,8 @@ export const TOOLS = [
102
135
  },
103
136
  {
104
137
  name: ACTIONS.SUGGEST_REPLY,
138
+ title: 'Suggest a reply (does not send)',
139
+ annotations: { title: 'Suggest a reply (does not send)', ...VALUE },
105
140
  description:
106
141
  'Draft a suggested reply (as the user) to a chat, based on its recent messages. ' +
107
142
  'Returns the suggestion text only: it does NOT send anything.',
@@ -118,6 +153,8 @@ export const TOOLS = [
118
153
  },
119
154
  {
120
155
  name: ACTIONS.TRANSCRIBE_VOICE_NOTE,
156
+ title: 'Transcribe a voice note',
157
+ annotations: { title: 'Transcribe a voice note', ...VALUE },
121
158
  description:
122
159
  'Transcribe a WhatsApp voice note to text using the configured cloud speech-to-text ' +
123
160
  'provider. Pass the message id of a voice/audio message (from get_messages).',
@@ -130,6 +167,62 @@ export const TOOLS = [
130
167
  additionalProperties: false,
131
168
  },
132
169
  },
170
+ {
171
+ name: ACTIONS.DRAFT_MESSAGE,
172
+ title: 'Put a draft in a chat\'s message box (does not send)',
173
+ annotations: { title: 'Put a draft in a chat\'s message box (does not send)', ...WRITE },
174
+ description:
175
+ 'Open a chat in the user\'s WhatsApp Web and put text in its message box, with a bar saying ' +
176
+ 'who drafted it. It does NOT send: the user reads it and presses Send. Refused if that chat ' +
177
+ 'already has unsent text in its box, so nothing the user typed is overwritten.' + OFF_UNTIL_ALLOWED,
178
+ inputSchema: {
179
+ type: 'object',
180
+ properties: {
181
+ chatId: { type: 'string', description: 'Chat id from list_chats, or a phone number in digits.' },
182
+ text: { type: 'string', maxLength: 2000, description: 'The message text, at most 2,000 characters.' },
183
+ },
184
+ required: ['chatId', 'text'],
185
+ additionalProperties: false,
186
+ },
187
+ },
188
+ {
189
+ name: ACTIONS.CREATE_REMINDER,
190
+ title: 'Set a reminder for a chat',
191
+ annotations: { title: 'Set a reminder for a chat', ...WRITE },
192
+ description:
193
+ 'Save a Reply Wizard reminder: at the time given, Chrome shows the user a notification with ' +
194
+ 'the note, and clicking it opens the chat with the note in the message box. Nothing is sent.' +
195
+ OFF_UNTIL_ALLOWED,
196
+ inputSchema: {
197
+ type: 'object',
198
+ properties: {
199
+ chatId: { type: 'string', description: 'Chat id from list_chats, or a phone number in digits.' },
200
+ text: { type: 'string', maxLength: 1000, description: 'The note, written as the message the user wants to send.' },
201
+ dueAt: { type: 'string', description: 'When, as ISO 8601 with a time zone offset, e.g. "2026-10-03T09:00:00+05:30". Must be in the future.' },
202
+ repeat: { type: 'string', description: 'Optional: "daily", "weekly", "monthly" or "weekdays". Omit for once.' },
203
+ },
204
+ required: ['chatId', 'text', 'dueAt'],
205
+ additionalProperties: false,
206
+ },
207
+ },
208
+ {
209
+ name: ACTIONS.SAVE_TEMPLATE,
210
+ title: 'Save a message template',
211
+ annotations: { title: 'Save a message template', ...WRITE },
212
+ description:
213
+ 'Save a reusable message template to Reply Wizard. Square brackets mark a part to fill in ' +
214
+ 'each time, e.g. "Running about [15] minutes late". The user inserts templates from the reply bar.' +
215
+ OFF_UNTIL_ALLOWED,
216
+ inputSchema: {
217
+ type: 'object',
218
+ properties: {
219
+ body: { type: 'string', maxLength: 2000, description: 'The template text, at most 2,000 characters.' },
220
+ title: { type: 'string', maxLength: 80, description: 'Optional short name; derived from the text if omitted.' },
221
+ },
222
+ required: ['body'],
223
+ additionalProperties: false,
224
+ },
225
+ },
133
226
  ];
134
227
 
135
228
  // name → extension action. (Identity for now; kept explicit so a tool name can
package/src/wsServer.js CHANGED
@@ -27,7 +27,7 @@ import { platform } from 'node:os';
27
27
  import { join } from 'node:path';
28
28
  import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
29
29
  import { spawn } from 'node:child_process';
30
- import { CONTROL, DEFAULT_PORT, PROTOCOL_VERSION, VALUE_ACTIONS } from './protocol.js';
30
+ import { CONTROL, DEFAULT_PORT, PROTOCOL_VERSION, VALUE_ACTIONS, WRITE_ACTIONS } from './protocol.js';
31
31
  import { hostVersion } from './hostVersion.js';
32
32
  import { readJson, stateDir, writeJsonVerified } from './stateStore.js';
33
33
 
@@ -478,7 +478,7 @@ export class ExtensionBridge {
478
478
  * (read vs value) with bounded concurrency + per-lane backpressure; the per-action
479
479
  * timeout covers queue wait + round-trip.
480
480
  */
481
- callAction(action, params = {}) {
481
+ callAction(action, params = {}, { client = null } = {}) {
482
482
  if (this.portConflict) {
483
483
  return Promise.reject(new Error(`Another Reply Wizard hub is already using port ${this.port}. Close the duplicate MCP host (or set RW_MCP_PORT to a free port) and reconnect.`));
484
484
  }
@@ -493,7 +493,7 @@ export class ExtensionBridge {
493
493
  return Promise.reject(new Error(`Reply Wizard is busy (${lane.name} queue full). Try again shortly.`));
494
494
  }
495
495
  return new Promise((resolve, reject) => {
496
- const entry = { action, params, resolve, reject, settled: false, id: null, timer: null };
496
+ const entry = { action, params, client, resolve, reject, settled: false, id: null, timer: null };
497
497
  entry.timer = setTimeout(() => this._timeout(entry, lane), this.requestTimeoutMs);
498
498
  lane.queue.push(entry);
499
499
  this._drainLane(lane);
@@ -501,7 +501,8 @@ export class ExtensionBridge {
501
501
  }
502
502
 
503
503
  _laneFor(action) {
504
- return VALUE_ACTIONS.includes(action) ? this.lanes.value : this.lanes.read;
504
+ // Writes share the one-at-a-time value lane, so two drafts can never race for one composer.
505
+ return VALUE_ACTIONS.includes(action) || WRITE_ACTIONS.includes(action) ? this.lanes.value : this.lanes.read;
505
506
  }
506
507
 
507
508
  // Dispatch as many queued entries as the lane's concurrency limit allows.
@@ -529,7 +530,7 @@ export class ExtensionBridge {
529
530
  const id = randomUUID();
530
531
  entry.id = id;
531
532
  this.pending.set(id, { entry, lane });
532
- this._send({ id, method: 'action', action: entry.action, params: entry.params });
533
+ this._send({ id, method: 'action', action: entry.action, params: entry.params, ...(entry.client ? { client: String(entry.client).slice(0, 60) } : {}) });
533
534
  }
534
535
 
535
536
  // Settle an in-flight action, free its lane slot, and pump the lane.