replywizard-whatsapp-mcp 0.3.2 → 0.4.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
@@ -151,6 +151,30 @@ launch does. It identifies itself as `replywizard-cli`, so it appears beside you
151
151
 
152
152
  `RW_MCP_PORT` is optional (defaults to `7869`); set it on both sides if you change it.
153
153
 
154
+ ### From any other computer: `--remote` (0.4.0)
155
+
156
+ The local mode needs to run on the computer where Chrome is open. Remote mode runs anywhere, a
157
+ second laptop, a server or a cloud coding agent, and reaches the same browser through Reply
158
+ Wizard's relay at `https://mcp.replywizard.app`, the server claude.ai and ChatGPT use. It needs a
159
+ paid Reply Wizard plan and the **Use from claude.ai and ChatGPT** switch on in the extension's
160
+ WhatsApp MCP tab.
161
+
162
+ ```bash
163
+ replywizard login # once: opens your browser to sign in and approve
164
+ replywizard chats --remote --limit 10
165
+ REPLYWIZARD_REMOTE=1 replywizard summarize 919110412164 # the same, for an agent's shell
166
+ replywizard status --remote # signed in, and is your browser reachable
167
+ replywizard logout
168
+ ```
169
+
170
+ Sign-in is OAuth 2.1 with PKCE over a loopback redirect on `127.0.0.1`, the flow Claude Code uses.
171
+ With no browser on the machine, open the printed link on any device, approve, and paste the
172
+ address the browser lands on back into the terminal. The sign-in lives in
173
+ `~/.replywizard-mcp/remote.json` (0600): a one-hour access token and a 30-day refresh token that
174
+ rotates on every use. Disconnect it from My account at <https://replywizard.app/account>, or with
175
+ `replywizard logout`. What a command reads passes through the relay on its way to you and is not
176
+ stored there.
177
+
154
178
  > **Pairing-code toast.** The code is also shown as a desktop notification (`osascript` on
155
179
  > macOS, a PowerShell balloon on Windows, `notify-send` on Linux), because the connector is
156
180
  > 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.2",
3
+ "version": "0.4.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
@@ -37,6 +37,7 @@ import { ACTIONS, VALUE_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';
@@ -309,6 +310,13 @@ export function helpText() {
309
310
  ' replywizard pair how to finish pairing',
310
311
  ...lines,
311
312
  '',
313
+ 'From any other computer (needs a Reply Wizard plan)',
314
+ ' replywizard login sign in once; opens your browser',
315
+ ' replywizard <command> --remote run any command above through mcp.replywizard.app',
316
+ ' replywizard status --remote signed in, and is your browser reachable',
317
+ ' replywizard logout sign out and forget the sign-in on this computer',
318
+ ' REPLYWIZARD_REMOTE=1 the same as --remote on every command, for an agent',
319
+ '',
312
320
  'Options',
313
321
  ' --json print the raw answer, for scripting',
314
322
  ' --limit <n> how many rows (where the command takes one)',
@@ -398,11 +406,29 @@ export const PAIR_TEXT = [
398
406
 
399
407
  export async function main(argv = process.argv.slice(2), deps = {}) {
400
408
  const out = deps.out || ((s) => console.log(s));
409
+ // Remote mode (ROADMAP row 20): the same commands through the relay instead of the local daemon.
410
+ const remote = wantsRemote(argv, deps.env || process.env);
411
+ argv = argv.filter((a) => a !== '--remote');
401
412
  const word = argv[0];
402
413
 
414
+ if (word === 'login') {
415
+ await login({ ...deps, note: deps.note || note });
416
+ out('Signed in. Try: replywizard chats --remote');
417
+ return 0;
418
+ }
419
+ if (word === 'logout') {
420
+ out((await logout(deps)) ? 'Signed out. This computer no longer holds a Reply Wizard sign-in.' : 'Not signed in.');
421
+ return 0;
422
+ }
423
+
403
424
  if (!word || word === '--help' || word === '-h' || word === 'help') { out(helpText()); return 0; }
404
425
  if (word === '--version' || word === '-v') { out(deps.version || 'dev'); return 0; }
405
426
 
427
+ if (word === 'status' && remote) {
428
+ const s = await remoteStatus(deps);
429
+ out(argv.includes('--json') ? JSON.stringify(s, null, 2) : remoteStatusLines(s).join('\n'));
430
+ return s.signedIn && s.browser === 'connected' ? 0 : 1;
431
+ }
406
432
  if (word === 'status') {
407
433
  const s = await status(deps);
408
434
  const rest = parseArgs({ name: 'status', inputSchema: { properties: {} } }, argv.slice(1));
@@ -427,6 +453,11 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
427
453
  return 2;
428
454
  }
429
455
 
456
+ if (remote) {
457
+ out(format(await callRemote(tool.name, args, deps), { json }));
458
+ return 0;
459
+ }
460
+
430
461
  // Start the daemon if it is not up, exactly as the stdio connector does, so the first
431
462
  // command on a fresh machine works rather than explaining how to start a server.
432
463
  const healthUrl = `${deps.base || `http://${HOST}:${Number(process.env.RW_MCP_HTTP_PORT) || DEFAULT_HTTP_PORT}`}/healthz`;
package/src/connector.js CHANGED
@@ -24,16 +24,88 @@ const HOST = '127.0.0.1';
24
24
  const log = (...args) => console.error('[replywizard-mcp:connector]', ...args);
25
25
  const delay = (ms) => new Promise((r) => setTimeout(r, ms));
26
26
 
27
+ /**
28
+ * JSON-RPC error handed back when a request cannot reach the daemon, or when the daemon goes
29
+ * away while the request is in flight. -32000 is the "implementation-defined server error"
30
+ * range, which is what this is: the protocol was fine and the hop underneath it was not.
31
+ */
32
+ const DAEMON_GONE = -32000;
33
+ const DAEMON_GONE_TEXT =
34
+ 'The Reply Wizard MCP daemon is not reachable. It may have been stopped, or the machine '
35
+ + 'may have slept. Run `replywizard status` to restart it, then try again.';
36
+
37
+ /** A JSON-RPC REQUEST is the only frame anybody is waiting on: it has BOTH an id and a method. */
38
+ function isRequest(msg) {
39
+ return !!msg && typeof msg === 'object' && msg.method !== undefined
40
+ && msg.id !== undefined && msg.id !== null;
41
+ }
42
+
27
43
  /**
28
44
  * Wire two MCP transports so every message on one is forwarded to the other, in both
29
45
  * directions, and a close/error on either tears down the pair. Pure plumbing: no
30
- * protocol knowledge. Returns nothing; assign the transports' lifecycle to the caller.
46
+ * protocol knowledge beyond "which frames is somebody waiting for an answer to".
47
+ *
48
+ * WHY THIS IS NOT A BARE RELAY, AND THE MEASUREMENT BEHIND IT (2026-09-21)
49
+ * It used to be one: a failed forward was `.catch((e) => log(...))`, logged to stderr and
50
+ * swallowed. **stderr is not shown to anyone.** An MCP client that had sent `tools/call` and
51
+ * whose request could not be forwarded therefore waited FOR EVER, because a JSON-RPC client
52
+ * has nothing to wait on but the matching id.
53
+ *
54
+ * That is not theoretical. The owner hit it on 2026-09-21 and reported it as "you were
55
+ * working for an unusually long time on a single tool call", and the only way out was to
56
+ * interrupt. Reproduced deterministically: connect a client, prove a call works, `kill -9`
57
+ * the daemon, send the same call again -- the connector printed `→daemon send failed: fetch
58
+ * failed` and the client received nothing in 30 seconds and would have received nothing ever.
59
+ *
60
+ * A daemon that dies is ordinary. It is a detached background process, so it goes with a
61
+ * crash, a laptop sleeping, an OOM kill, `pkill node`, or a machine restart, and the client
62
+ * that started it has no idea. **The failure is unavoidable; being silent about it is not.**
63
+ *
64
+ * So every frame anybody is waiting on gets an answer, one way or the other:
65
+ * - a request that cannot be FORWARDED is answered immediately with an error, and
66
+ * - a request already IN FLIGHT when the daemon drops is answered on the way down,
67
+ * which is why `pending` exists rather than only a catch.
68
+ * Notifications and responses are still relayed best-effort and still only logged: nothing
69
+ * is waiting on them, and inventing an error for a notification would corrupt the stream.
31
70
  */
32
71
  export function pumpTransports(clientFacing, daemonFacing) {
33
- clientFacing.onmessage = (msg) => { daemonFacing.send(msg).catch((e) => log('→daemon send failed:', e && e.message)); };
34
- daemonFacing.onmessage = (msg) => { clientFacing.send(msg).catch((e) => log('→client send failed:', e && e.message)); };
72
+ /** Request ids the client is waiting on. Settled by the daemon, or by us on the way down. */
73
+ const pending = new Set();
74
+
75
+ const failClient = (id, message) => {
76
+ pending.delete(id);
77
+ clientFacing.send({ jsonrpc: '2.0', id, error: { code: DAEMON_GONE, message } })
78
+ .catch((e) => log('could not report the failure to the client:', e && e.message));
79
+ };
80
+ /** Answer everything still outstanding. Called once, when the daemon side goes away. */
81
+ const failAllPending = () => {
82
+ if (!pending.size) return;
83
+ log(`daemon gone with ${pending.size} request(s) in flight; answering them with an error.`);
84
+ for (const id of [...pending]) failClient(id, DAEMON_GONE_TEXT);
85
+ };
86
+
87
+ clientFacing.onmessage = (msg) => {
88
+ const waiting = isRequest(msg);
89
+ if (waiting) pending.add(msg.id);
90
+ daemonFacing.send(msg).catch((e) => {
91
+ log('→daemon send failed:', e && e.message);
92
+ // The whole point: a request that never reached the daemon is answered here, because
93
+ // nothing downstream exists to answer it.
94
+ if (waiting) failClient(msg.id, DAEMON_GONE_TEXT);
95
+ });
96
+ };
97
+ daemonFacing.onmessage = (msg) => {
98
+ // Any frame carrying an id settles that id, whether it is a result or an error.
99
+ if (msg && typeof msg === 'object' && msg.id !== undefined && msg.id !== null) pending.delete(msg.id);
100
+ clientFacing.send(msg).catch((e) => log('→client send failed:', e && e.message));
101
+ };
35
102
  clientFacing.onclose = () => { daemonFacing.close().catch(() => {}); };
36
- daemonFacing.onclose = () => { clientFacing.close().catch(() => {}); };
103
+ daemonFacing.onclose = () => {
104
+ // Before the client transport goes, not after: once it is closed nothing can be sent on
105
+ // it, and the in-flight requests would be lost in exactly the silent way this fixes.
106
+ failAllPending();
107
+ clientFacing.close().catch(() => {});
108
+ };
37
109
  clientFacing.onerror = (e) => log('client transport error:', e && e.message);
38
110
  daemonFacing.onerror = (e) => log('daemon transport error:', e && e.message);
39
111
  }
package/src/mcpServer.js CHANGED
@@ -31,7 +31,9 @@ export function createMcpServer(bridge) {
31
31
  }
32
32
  try {
33
33
  const result = await bridge.callAction(action, args || {});
34
- return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
34
+ // Compact, not pretty-printed (2026-10-02): every result is read by a model, and the
35
+ // indentation was paid for in tokens on every call. The remote relay answers the same way.
36
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
35
37
  } catch (err) {
36
38
  return {
37
39
  isError: true,
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,24 @@
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
+
9
22
  export const TOOLS = [
10
23
  {
11
24
  name: ACTIONS.PING,
25
+ title: 'Check the WhatsApp connection',
26
+ annotations: { title: 'Check the WhatsApp connection', ...READ },
12
27
  description:
13
28
  'Health check. Confirms the Reply Wizard extension is connected and an active ' +
14
29
  'WhatsApp Web tab can be reached. Returns { pong: true }.',
@@ -20,9 +35,13 @@ export const TOOLS = [
20
35
  },
21
36
  {
22
37
  name: ACTIONS.LIST_CHATS,
38
+ title: 'List WhatsApp chats',
39
+ annotations: { title: 'List WhatsApp chats', ...READ },
23
40
  description:
24
41
  'List the user\'s WhatsApp chats, most recently active first. Returns id, name, ' +
25
- 'isGroup, unreadCount and timestamp for each. Use the returned `id` with get_messages.',
42
+ 'phone, isGroup, unreadCount and timestamp for each. Use the returned `id` with ' +
43
+ 'get_messages. `phone` is the dialable number in digits, or null: a group never has ' +
44
+ 'one, and a small number of one-to-one chats do not either, so it is never required.',
26
45
  inputSchema: {
27
46
  type: 'object',
28
47
  properties: {
@@ -33,6 +52,8 @@ export const TOOLS = [
33
52
  },
34
53
  {
35
54
  name: ACTIONS.GET_MESSAGES,
55
+ title: 'Read messages in a chat',
56
+ annotations: { title: 'Read messages in a chat', ...READ },
36
57
  description:
37
58
  'Get recent messages for a chat (those currently loaded in WhatsApp Web), oldest→newest. ' +
38
59
  'Each message has sender, timestamp, type and text (voice notes report duration; use ' +
@@ -54,6 +75,8 @@ export const TOOLS = [
54
75
  },
55
76
  {
56
77
  name: ACTIONS.GET_CONTACT,
78
+ title: 'Look up a contact',
79
+ annotations: { title: 'Look up a contact', ...READ },
57
80
  description: 'Look up a single contact by id. Returns name, pushname and business/contact flags.',
58
81
  inputSchema: {
59
82
  type: 'object',
@@ -72,6 +95,8 @@ export const TOOLS = [
72
95
  },
73
96
  {
74
97
  name: ACTIONS.LIST_CONTACTS,
98
+ title: 'List contacts',
99
+ annotations: { title: 'List contacts', ...READ },
75
100
  description:
76
101
  'List the user\'s saved WhatsApp contacts. By default only address-book contacts are returned.',
77
102
  inputSchema: {
@@ -85,6 +110,8 @@ export const TOOLS = [
85
110
  },
86
111
  {
87
112
  name: ACTIONS.SUMMARIZE_CHAT,
113
+ title: 'Summarise a chat',
114
+ annotations: { title: 'Summarise a chat', ...VALUE },
88
115
  description:
89
116
  'Summarize a chat\'s recent messages into concise bullet points (key points, ' +
90
117
  'decisions, action items). Uses the user\'s configured AI provider in the extension.',
@@ -100,6 +127,8 @@ export const TOOLS = [
100
127
  },
101
128
  {
102
129
  name: ACTIONS.SUGGEST_REPLY,
130
+ title: 'Suggest a reply (does not send)',
131
+ annotations: { title: 'Suggest a reply (does not send)', ...VALUE },
103
132
  description:
104
133
  'Draft a suggested reply (as the user) to a chat, based on its recent messages. ' +
105
134
  'Returns the suggestion text only: it does NOT send anything.',
@@ -116,6 +145,8 @@ export const TOOLS = [
116
145
  },
117
146
  {
118
147
  name: ACTIONS.TRANSCRIBE_VOICE_NOTE,
148
+ title: 'Transcribe a voice note',
149
+ annotations: { title: 'Transcribe a voice note', ...VALUE },
119
150
  description:
120
151
  'Transcribe a WhatsApp voice note to text using the configured cloud speech-to-text ' +
121
152
  'provider. Pass the message id of a voice/audio message (from get_messages).',