replywizard-whatsapp-mcp 0.1.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 +101 -0
- package/package.json +45 -0
- package/src/index.js +39 -0
- package/src/mcpServer.js +44 -0
- package/src/protocol.js +58 -0
- package/src/tools.js +124 -0
- package/src/wsServer.js +167 -0
package/README.md
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# replywizard-whatsapp-mcp
|
|
2
|
+
|
|
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**.
|
|
5
|
+
|
|
6
|
+
v1 is **read + value only** and **local-only**: there is no path that can send or modify WhatsApp
|
|
7
|
+
messages, and nothing leaves your machine.
|
|
8
|
+
|
|
9
|
+
## How it works
|
|
10
|
+
|
|
11
|
+
A Chrome extension cannot itself be an MCP server (no listening socket / stdio). So this is a small
|
|
12
|
+
companion process that bridges two connections:
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
AI client ──MCP over stdio──▶ replywizard-whatsapp-mcp ──WebSocket (127.0.0.1)──▶ Reply Wizard extension ──▶ WhatsApp Web
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
- The **AI client** speaks MCP to this process over stdio.
|
|
19
|
+
- This process runs a **WebSocket server** on `127.0.0.1:7869`; the **extension dials in** as a client.
|
|
20
|
+
- Each `tools/call` is forwarded to the extension, executed against the WhatsApp page, and returned.
|
|
21
|
+
|
|
22
|
+
This package is intentionally self-contained (only `@modelcontextprotocol/sdk` and `ws`) so it can be
|
|
23
|
+
lifted into its own repository without touching the extension.
|
|
24
|
+
|
|
25
|
+
## Tools
|
|
26
|
+
|
|
27
|
+
| Tool | Kind | What it does |
|
|
28
|
+
|------|------|--------------|
|
|
29
|
+
| `ping` | health | Confirms the extension is connected and a WhatsApp Web tab is reachable. |
|
|
30
|
+
| `list_chats` | read | Recent chats: id, name, isGroup, unreadCount, timestamp. |
|
|
31
|
+
| `get_messages` | read | Recent (loaded) messages for a chat; media is labelled, voice notes report duration. |
|
|
32
|
+
| `get_contact` | read | Look up one contact by id. |
|
|
33
|
+
| `list_contacts` | read | Your saved (address-book) contacts. |
|
|
34
|
+
| `summarize_chat` | value | Bulleted summary of a chat's recent messages (uses your configured AI provider). |
|
|
35
|
+
| `suggest_reply` | value | Drafts a reply as you — returns text only, **never sends**. |
|
|
36
|
+
| `transcribe_voice_note` | value | Transcribes a voice note via your configured **cloud** speech-to-text provider. |
|
|
37
|
+
|
|
38
|
+
Value tools reuse the extension's existing AI/STT configuration; **your API keys never leave the
|
|
39
|
+
extension** (the hub only sees tool arguments and results).
|
|
40
|
+
|
|
41
|
+
## Setup
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
cd mcp-host
|
|
45
|
+
npm install
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### Claude Desktop
|
|
49
|
+
|
|
50
|
+
Add to `claude_desktop_config.json`:
|
|
51
|
+
|
|
52
|
+
```json
|
|
53
|
+
{
|
|
54
|
+
"mcpServers": {
|
|
55
|
+
"replywizard": {
|
|
56
|
+
"command": "node",
|
|
57
|
+
"args": ["/absolute/path/to/Reply-Wizard-App/mcp-host/src/index.js"],
|
|
58
|
+
"env": { "RW_MCP_PORT": "7869" }
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### Claude Code
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
claude mcp add replywizard -- node /absolute/path/to/Reply-Wizard-App/mcp-host/src/index.js
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`RW_MCP_PORT` is optional (defaults to `7869`); set it on both sides if you change it.
|
|
71
|
+
|
|
72
|
+
## First-run pairing
|
|
73
|
+
|
|
74
|
+
1. Open **WhatsApp Web** in the browser with Reply Wizard installed.
|
|
75
|
+
2. Click the Reply Wizard toolbar icon → **AI client access** → **Enable AI access**.
|
|
76
|
+
3. Start your AI client (it launches this hub). The hub prints a **6-digit pairing code** to its
|
|
77
|
+
stderr / the client's MCP log.
|
|
78
|
+
4. Enter that code in the extension popup. Once paired, the extension stores a session token and
|
|
79
|
+
reconnects automatically on subsequent runs (no code needed again).
|
|
80
|
+
|
|
81
|
+
Use **Revoke access** in the popup to drop the token and disable the bridge.
|
|
82
|
+
|
|
83
|
+
## Security
|
|
84
|
+
|
|
85
|
+
- Binds to `127.0.0.1` only.
|
|
86
|
+
- No tool runs until the pairing code is confirmed in the extension.
|
|
87
|
+
- **Read + value tools only** — v1 has no send/modify capability.
|
|
88
|
+
- The session token is stored at `~/.replywizard-mcp/session.json` (mode 600).
|
|
89
|
+
|
|
90
|
+
## Troubleshooting
|
|
91
|
+
|
|
92
|
+
| Symptom | Fix |
|
|
93
|
+
|---------|-----|
|
|
94
|
+
| `Reply Wizard extension is not connected` | Open WhatsApp Web and enable AI access in the popup. |
|
|
95
|
+
| `Not paired yet` | Enter the 6-digit code (printed to the hub's stderr) in the popup. |
|
|
96
|
+
| `No WhatsApp Web tab is open` | A read/value tool needs an open, logged-in WhatsApp Web tab. |
|
|
97
|
+
| Transcription error about a cloud provider | `transcribe_voice_note` needs a **cloud** STT key in Options → Speech-to-Text (on-device STT is not used over MCP). |
|
|
98
|
+
| Port in use | The default is `7869`. Changing it is advanced (set `RW_MCP_PORT` on the hub **and** the `rw_mcp_port` value in the extension's storage to match). |
|
|
99
|
+
|
|
100
|
+
See [`../docs/MCP_EXECUTION_PLAN.md`](../docs/MCP_EXECUTION_PLAN.md) and
|
|
101
|
+
[`../docs/MCP_INTEGRATION_IMPLEMENTATION_PLAN.md`](../docs/MCP_INTEGRATION_IMPLEMENTATION_PLAN.md).
|
package/package.json
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "replywizard-whatsapp-mcp",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Local MCP server that exposes WhatsApp Web (read + value tools) to AI clients via the Reply Wizard Chrome extension.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"replywizard-whatsapp-mcp": "src/index.js"
|
|
8
|
+
},
|
|
9
|
+
"exports": {
|
|
10
|
+
"./protocol": "./src/protocol.js"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"src",
|
|
14
|
+
"README.md"
|
|
15
|
+
],
|
|
16
|
+
"scripts": {
|
|
17
|
+
"start": "node src/index.js",
|
|
18
|
+
"test": "node --test"
|
|
19
|
+
},
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=18"
|
|
22
|
+
},
|
|
23
|
+
"keywords": [
|
|
24
|
+
"mcp",
|
|
25
|
+
"model-context-protocol",
|
|
26
|
+
"whatsapp",
|
|
27
|
+
"reply-wizard",
|
|
28
|
+
"claude",
|
|
29
|
+
"ai"
|
|
30
|
+
],
|
|
31
|
+
"repository": {
|
|
32
|
+
"type": "git",
|
|
33
|
+
"url": "git+https://github.com/PalWorks/Reply-Wizard-App.git",
|
|
34
|
+
"directory": "mcp-host"
|
|
35
|
+
},
|
|
36
|
+
"homepage": "https://github.com/PalWorks/Reply-Wizard-App/tree/main/mcp-host#readme",
|
|
37
|
+
"bugs": {
|
|
38
|
+
"url": "https://github.com/PalWorks/Reply-Wizard-App/issues"
|
|
39
|
+
},
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"@modelcontextprotocol/sdk": "^1.0.0",
|
|
42
|
+
"ws": "^8.18.0"
|
|
43
|
+
},
|
|
44
|
+
"license": "MIT"
|
|
45
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// index.js — replywizard-mcp entry point.
|
|
3
|
+
//
|
|
4
|
+
// Starts the local WebSocket server (which the extension dials into) and the MCP
|
|
5
|
+
// stdio server (which the AI client connects to), and bridges the two.
|
|
6
|
+
//
|
|
7
|
+
// Usage (e.g. in Claude Desktop config):
|
|
8
|
+
// { "command": "node", "args": ["/path/to/mcp-host/src/index.js"] }
|
|
9
|
+
// optional env: RW_MCP_PORT=7869
|
|
10
|
+
//
|
|
11
|
+
// NOTE: stdout is reserved for the MCP stdio protocol. ALL logging goes to stderr.
|
|
12
|
+
|
|
13
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
14
|
+
import { ExtensionBridge } from './wsServer.js';
|
|
15
|
+
import { createMcpServer } from './mcpServer.js';
|
|
16
|
+
import { DEFAULT_PORT } from './protocol.js';
|
|
17
|
+
|
|
18
|
+
const log = (...args) => console.error('[replywizard-mcp]', ...args);
|
|
19
|
+
|
|
20
|
+
async function main() {
|
|
21
|
+
const port = Number(process.env.RW_MCP_PORT) || DEFAULT_PORT;
|
|
22
|
+
|
|
23
|
+
const bridge = new ExtensionBridge({ port });
|
|
24
|
+
await bridge.listen();
|
|
25
|
+
|
|
26
|
+
const server = createMcpServer(bridge);
|
|
27
|
+
const transport = new StdioServerTransport();
|
|
28
|
+
await server.connect(transport);
|
|
29
|
+
log('MCP stdio server ready. Waiting for the Reply Wizard extension to connect…');
|
|
30
|
+
|
|
31
|
+
const shutdown = () => { try { bridge.close(); } catch { /* noop */ } process.exit(0); };
|
|
32
|
+
process.on('SIGINT', shutdown);
|
|
33
|
+
process.on('SIGTERM', shutdown);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
main().catch((err) => {
|
|
37
|
+
log('Fatal:', (err && err.stack) || err);
|
|
38
|
+
process.exit(1);
|
|
39
|
+
});
|
package/src/mcpServer.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// mcpServer.js — the MCP server presented to the AI client over stdio.
|
|
2
|
+
//
|
|
3
|
+
// Translates MCP tools/list and tools/call into extension actions via the
|
|
4
|
+
// ExtensionBridge WebSocket. Returns tool results as JSON text content.
|
|
5
|
+
|
|
6
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
7
|
+
import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
8
|
+
import { TOOLS, TOOL_TO_ACTION } from './tools.js';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Build (but do not connect) the MCP server.
|
|
12
|
+
* @param {import('./wsServer.js').ExtensionBridge} bridge
|
|
13
|
+
* @returns {import('@modelcontextprotocol/sdk/server/index.js').Server}
|
|
14
|
+
*/
|
|
15
|
+
export function createMcpServer(bridge) {
|
|
16
|
+
const server = new Server(
|
|
17
|
+
{ name: 'replywizard-mcp', version: '0.1.0' },
|
|
18
|
+
{ capabilities: { tools: {} } },
|
|
19
|
+
);
|
|
20
|
+
|
|
21
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
|
|
22
|
+
|
|
23
|
+
server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
24
|
+
const { name, arguments: args } = req.params;
|
|
25
|
+
const action = TOOL_TO_ACTION[name];
|
|
26
|
+
if (!action) {
|
|
27
|
+
return {
|
|
28
|
+
isError: true,
|
|
29
|
+
content: [{ type: 'text', text: `Unknown tool: ${name}` }],
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
try {
|
|
33
|
+
const result = await bridge.callAction(action, args || {});
|
|
34
|
+
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
|
|
35
|
+
} catch (err) {
|
|
36
|
+
return {
|
|
37
|
+
isError: true,
|
|
38
|
+
content: [{ type: 'text', text: (err && err.message) || 'Tool call failed' }],
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
return server;
|
|
44
|
+
}
|
package/src/protocol.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// protocol.js — wire contract shared with the Reply Wizard extension.
|
|
2
|
+
//
|
|
3
|
+
// This is a self-contained copy so the hub can be spun off into its own repo.
|
|
4
|
+
// While co-located in the extension repo, `tests/mcpProtocol.test.js` asserts the
|
|
5
|
+
// exported values here stay identical to the canonical `src/mcpProtocol.js`.
|
|
6
|
+
//
|
|
7
|
+
// Keep the EXPORTED VALUES below byte-identical to the extension's copy.
|
|
8
|
+
|
|
9
|
+
export const PROTOCOL_VERSION = 1;
|
|
10
|
+
|
|
11
|
+
export const PAGE_REQ = 'RW_MCP_REQ';
|
|
12
|
+
export const PAGE_RESP = 'RW_MCP_RESP';
|
|
13
|
+
|
|
14
|
+
export const TAB_ACTION = 'rw_mcp_action';
|
|
15
|
+
|
|
16
|
+
export const ACTIONS = Object.freeze({
|
|
17
|
+
PING: 'ping',
|
|
18
|
+
LIST_CHATS: 'list_chats',
|
|
19
|
+
GET_MESSAGES: 'get_messages',
|
|
20
|
+
GET_CONTACT: 'get_contact',
|
|
21
|
+
LIST_CONTACTS: 'list_contacts',
|
|
22
|
+
TRANSCRIBE_VOICE_NOTE: 'transcribe_voice_note',
|
|
23
|
+
SUMMARIZE_CHAT: 'summarize_chat',
|
|
24
|
+
SUGGEST_REPLY: 'suggest_reply',
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
export const READ_ACTIONS = Object.freeze([
|
|
28
|
+
ACTIONS.LIST_CHATS, ACTIONS.GET_MESSAGES, ACTIONS.GET_CONTACT, ACTIONS.LIST_CONTACTS,
|
|
29
|
+
]);
|
|
30
|
+
export const VALUE_ACTIONS = Object.freeze([
|
|
31
|
+
ACTIONS.TRANSCRIBE_VOICE_NOTE, ACTIONS.SUMMARIZE_CHAT, ACTIONS.SUGGEST_REPLY,
|
|
32
|
+
]);
|
|
33
|
+
|
|
34
|
+
export const STATUS = Object.freeze({
|
|
35
|
+
DISCONNECTED: 'disconnected',
|
|
36
|
+
CONNECTING: 'connecting',
|
|
37
|
+
AUTH_REQUIRED: 'auth_required',
|
|
38
|
+
CONNECTED: 'connected',
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
export const CONTROL = Object.freeze({
|
|
42
|
+
HANDSHAKE: 'handshake',
|
|
43
|
+
PAIRING_REQUEST: 'pairing_request',
|
|
44
|
+
PAIRING_RESPONSE: 'pairing_response',
|
|
45
|
+
PAIRING_COMPLETE: 'pairing_complete',
|
|
46
|
+
AUTH_SUCCESS: 'auth_success',
|
|
47
|
+
PING: 'ping',
|
|
48
|
+
PONG: 'pong',
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
export const DEFAULT_PORT = 7869;
|
|
52
|
+
|
|
53
|
+
export const STORAGE_KEYS = Object.freeze({
|
|
54
|
+
ENABLED: 'rw_mcp_enabled',
|
|
55
|
+
PORT: 'rw_mcp_port',
|
|
56
|
+
SESSION_TOKEN: 'rw_mcp_session_token',
|
|
57
|
+
SESSION_ID: 'rw_mcp_session_id',
|
|
58
|
+
});
|
package/src/tools.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// tools.js — MCP tool definitions exposed to the AI client.
|
|
2
|
+
//
|
|
3
|
+
// Each tool maps 1:1 to an extension action (see protocol.js ACTIONS). The hub's
|
|
4
|
+
// CallTool handler forwards `arguments` to the extension over the WebSocket and
|
|
5
|
+
// returns the result. v1 ships read + value tools; this file covers read + ping.
|
|
6
|
+
|
|
7
|
+
import { ACTIONS } from './protocol.js';
|
|
8
|
+
|
|
9
|
+
export const TOOLS = [
|
|
10
|
+
{
|
|
11
|
+
name: ACTIONS.PING,
|
|
12
|
+
description:
|
|
13
|
+
'Health check. Confirms the Reply Wizard extension is connected and an active ' +
|
|
14
|
+
'WhatsApp Web tab can be reached. Returns { pong: true }.',
|
|
15
|
+
inputSchema: {
|
|
16
|
+
type: 'object',
|
|
17
|
+
properties: { echo: { type: 'string', description: 'Optional string echoed back.' } },
|
|
18
|
+
additionalProperties: false,
|
|
19
|
+
},
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
name: ACTIONS.LIST_CHATS,
|
|
23
|
+
description:
|
|
24
|
+
'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.',
|
|
26
|
+
inputSchema: {
|
|
27
|
+
type: 'object',
|
|
28
|
+
properties: {
|
|
29
|
+
limit: { type: 'integer', minimum: 1, maximum: 100, description: 'Max chats to return (default 20).' },
|
|
30
|
+
},
|
|
31
|
+
additionalProperties: false,
|
|
32
|
+
},
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
name: ACTIONS.GET_MESSAGES,
|
|
36
|
+
description:
|
|
37
|
+
'Get recent messages for a chat (those currently loaded in WhatsApp Web), oldest→newest. ' +
|
|
38
|
+
'Each message has sender, timestamp, type and text (voice notes report duration; use ' +
|
|
39
|
+
'transcribe_voice_note in a later version to read them).',
|
|
40
|
+
inputSchema: {
|
|
41
|
+
type: 'object',
|
|
42
|
+
properties: {
|
|
43
|
+
chatId: { type: 'string', description: 'Chat id from list_chats (e.g. "12345@g.us").' },
|
|
44
|
+
limit: { type: 'integer', minimum: 1, maximum: 100, description: 'Max messages (default 30).' },
|
|
45
|
+
},
|
|
46
|
+
required: ['chatId'],
|
|
47
|
+
additionalProperties: false,
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
name: ACTIONS.GET_CONTACT,
|
|
52
|
+
description: 'Look up a single contact by id. Returns name, pushname and business/contact flags.',
|
|
53
|
+
inputSchema: {
|
|
54
|
+
type: 'object',
|
|
55
|
+
properties: {
|
|
56
|
+
contactId: { type: 'string', description: 'Contact id (e.g. "12345@c.us").' },
|
|
57
|
+
},
|
|
58
|
+
required: ['contactId'],
|
|
59
|
+
additionalProperties: false,
|
|
60
|
+
},
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
name: ACTIONS.LIST_CONTACTS,
|
|
64
|
+
description:
|
|
65
|
+
'List the user\'s saved WhatsApp contacts. By default only address-book contacts are returned.',
|
|
66
|
+
inputSchema: {
|
|
67
|
+
type: 'object',
|
|
68
|
+
properties: {
|
|
69
|
+
limit: { type: 'integer', minimum: 1, maximum: 500, description: 'Max contacts (default 100).' },
|
|
70
|
+
includeNonContacts: { type: 'boolean', description: 'Include people not in the address book (default false).' },
|
|
71
|
+
},
|
|
72
|
+
additionalProperties: false,
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
name: ACTIONS.SUMMARIZE_CHAT,
|
|
77
|
+
description:
|
|
78
|
+
'Summarize a chat\'s recent messages into concise bullet points (key points, ' +
|
|
79
|
+
'decisions, action items). Uses the user\'s configured AI provider in the extension.',
|
|
80
|
+
inputSchema: {
|
|
81
|
+
type: 'object',
|
|
82
|
+
properties: {
|
|
83
|
+
chatId: { type: 'string', description: 'Chat id from list_chats.' },
|
|
84
|
+
limit: { type: 'integer', minimum: 1, maximum: 100, description: 'Messages to summarize (default 40).' },
|
|
85
|
+
},
|
|
86
|
+
required: ['chatId'],
|
|
87
|
+
additionalProperties: false,
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
name: ACTIONS.SUGGEST_REPLY,
|
|
92
|
+
description:
|
|
93
|
+
'Draft a suggested reply (as the user) to a chat, based on its recent messages. ' +
|
|
94
|
+
'Returns the suggestion text only — it does NOT send anything.',
|
|
95
|
+
inputSchema: {
|
|
96
|
+
type: 'object',
|
|
97
|
+
properties: {
|
|
98
|
+
chatId: { type: 'string', description: 'Chat id from list_chats.' },
|
|
99
|
+
limit: { type: 'integer', minimum: 1, maximum: 100, description: 'Context messages (default 20).' },
|
|
100
|
+
guidance: { type: 'string', description: 'Optional steer, e.g. "politely decline" or "ask for a call".' },
|
|
101
|
+
},
|
|
102
|
+
required: ['chatId'],
|
|
103
|
+
additionalProperties: false,
|
|
104
|
+
},
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
name: ACTIONS.TRANSCRIBE_VOICE_NOTE,
|
|
108
|
+
description:
|
|
109
|
+
'Transcribe a WhatsApp voice note to text using the configured cloud speech-to-text ' +
|
|
110
|
+
'provider. Pass the message id of a voice/audio message (from get_messages).',
|
|
111
|
+
inputSchema: {
|
|
112
|
+
type: 'object',
|
|
113
|
+
properties: {
|
|
114
|
+
messageId: { type: 'string', description: 'The voice note\'s message id (from get_messages).' },
|
|
115
|
+
},
|
|
116
|
+
required: ['messageId'],
|
|
117
|
+
additionalProperties: false,
|
|
118
|
+
},
|
|
119
|
+
},
|
|
120
|
+
];
|
|
121
|
+
|
|
122
|
+
// name → extension action. (Identity for now; kept explicit so a tool name can
|
|
123
|
+
// diverge from its wire action without touching the dispatch logic.)
|
|
124
|
+
export const TOOL_TO_ACTION = Object.fromEntries(TOOLS.map(t => [t.name, t.name]));
|
package/src/wsServer.js
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
// wsServer.js — local WebSocket server the extension dials into.
|
|
2
|
+
//
|
|
3
|
+
// The Reply Wizard extension (background SW) is the WebSocket *client*; this hub is
|
|
4
|
+
// the server, bound to 127.0.0.1 only.
|
|
5
|
+
//
|
|
6
|
+
// Auth flow:
|
|
7
|
+
// • extension sends `handshake { session_token }` on connect.
|
|
8
|
+
// • if the token matches the persisted one → `auth_success` (no prompt). This is
|
|
9
|
+
// what makes reconnects seamless.
|
|
10
|
+
// • otherwise the hub prints a one-time 6-digit code to STDERR (stdout is reserved
|
|
11
|
+
// for the MCP stdio protocol) and sends `pairing_request`. The extension shows a
|
|
12
|
+
// code entry in its popup; on a correct `pairing_response` the hub issues + persists
|
|
13
|
+
// a session token (`pairing_complete`) and sends `auth_success`.
|
|
14
|
+
//
|
|
15
|
+
// The token is persisted to ~/.replywizard-mcp/session.json so it survives restarts.
|
|
16
|
+
//
|
|
17
|
+
// Public surface:
|
|
18
|
+
// const bridge = new ExtensionBridge({ port });
|
|
19
|
+
// await bridge.listen();
|
|
20
|
+
// const result = await bridge.callAction('list_chats', { limit: 20 });
|
|
21
|
+
//
|
|
22
|
+
// Self-contained: depends only on `ws`, node builtins, and ./protocol.js.
|
|
23
|
+
|
|
24
|
+
import { WebSocketServer } from 'ws';
|
|
25
|
+
import { randomBytes, randomUUID } from 'node:crypto';
|
|
26
|
+
import { homedir } from 'node:os';
|
|
27
|
+
import { join } from 'node:path';
|
|
28
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
29
|
+
import { CONTROL, DEFAULT_PORT, PROTOCOL_VERSION } from './protocol.js';
|
|
30
|
+
|
|
31
|
+
const log = (...args) => console.error('[replywizard-mcp]', ...args);
|
|
32
|
+
|
|
33
|
+
const STATE_DIR = join(homedir(), '.replywizard-mcp');
|
|
34
|
+
const STATE_FILE = join(STATE_DIR, 'session.json');
|
|
35
|
+
|
|
36
|
+
function loadToken() {
|
|
37
|
+
try { return JSON.parse(readFileSync(STATE_FILE, 'utf8')).token || null; } catch { return null; }
|
|
38
|
+
}
|
|
39
|
+
function saveToken(token) {
|
|
40
|
+
try { mkdirSync(STATE_DIR, { recursive: true }); writeFileSync(STATE_FILE, JSON.stringify({ token }), { mode: 0o600 }); }
|
|
41
|
+
catch (e) { log('Could not persist session token:', e && e.message); }
|
|
42
|
+
}
|
|
43
|
+
function sixDigitCode() {
|
|
44
|
+
return String(parseInt(randomBytes(4).toString('hex'), 16) % 1_000_000).padStart(6, '0');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export class ExtensionBridge {
|
|
48
|
+
constructor({ port = DEFAULT_PORT, host = '127.0.0.1' } = {}) {
|
|
49
|
+
this.port = port;
|
|
50
|
+
this.host = host;
|
|
51
|
+
this.wss = null;
|
|
52
|
+
this.socket = null; // the single connected extension socket
|
|
53
|
+
this.paired = false;
|
|
54
|
+
this.pairingCode = null;
|
|
55
|
+
this.sessionToken = loadToken();
|
|
56
|
+
this.pending = new Map(); // requestId → { resolve, reject, timer }
|
|
57
|
+
this.requestTimeoutMs = 25_000;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
listen() {
|
|
61
|
+
return new Promise((resolve, reject) => {
|
|
62
|
+
this.wss = new WebSocketServer({ host: this.host, port: this.port });
|
|
63
|
+
this.wss.on('listening', () => { log(`WebSocket server listening on ws://${this.host}:${this.port}`); resolve(); });
|
|
64
|
+
this.wss.on('error', reject);
|
|
65
|
+
this.wss.on('connection', (ws) => this._onConnection(ws));
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
_onConnection(ws) {
|
|
70
|
+
if (this.socket && this.socket.readyState === this.socket.OPEN) {
|
|
71
|
+
log('Rejecting extra connection; one extension is already connected.');
|
|
72
|
+
try { ws.close(1013, 'busy'); } catch { /* noop */ }
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
this.socket = ws;
|
|
76
|
+
this.paired = false;
|
|
77
|
+
this.pairingCode = null;
|
|
78
|
+
log('Extension connected. Waiting for handshake…');
|
|
79
|
+
|
|
80
|
+
ws.on('message', (raw) => this._onMessage(raw));
|
|
81
|
+
ws.on('close', () => {
|
|
82
|
+
log('Extension disconnected.');
|
|
83
|
+
this._failAllPending(new Error('Extension disconnected.'));
|
|
84
|
+
if (this.socket === ws) { this.socket = null; this.paired = false; }
|
|
85
|
+
});
|
|
86
|
+
ws.on('error', (e) => log('Socket error:', e && e.message));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
_onMessage(raw) {
|
|
90
|
+
let msg;
|
|
91
|
+
try { msg = JSON.parse(raw.toString()); } catch { log('Dropped non-JSON message'); return; }
|
|
92
|
+
|
|
93
|
+
if (msg.method === CONTROL.HANDSHAKE) {
|
|
94
|
+
const token = msg.params && msg.params.session_token;
|
|
95
|
+
if (token && this.sessionToken && token === this.sessionToken) {
|
|
96
|
+
this.paired = true;
|
|
97
|
+
this._send({ method: CONTROL.AUTH_SUCCESS, params: { protocol: PROTOCOL_VERSION } });
|
|
98
|
+
log('Reconnected with a valid session token (no pairing needed).');
|
|
99
|
+
} else {
|
|
100
|
+
this.pairingCode = sixDigitCode();
|
|
101
|
+
log('');
|
|
102
|
+
log(' ┌──────────────────────────────────────────────┐');
|
|
103
|
+
log(` │ Reply Wizard pairing code: ${this.pairingCode} │`);
|
|
104
|
+
log(' └──────────────────────────────────────────────┘');
|
|
105
|
+
log(' Enter it in Reply Wizard → popup → AI client access.');
|
|
106
|
+
this._send({ method: CONTROL.PAIRING_REQUEST, params: { hub_name: 'Reply Wizard MCP', protocol: PROTOCOL_VERSION } });
|
|
107
|
+
}
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (msg.method === CONTROL.PAIRING_RESPONSE) {
|
|
112
|
+
const ok = msg.params && msg.params.approved && this.pairingCode && msg.params.code === this.pairingCode;
|
|
113
|
+
if (ok) {
|
|
114
|
+
this.paired = true;
|
|
115
|
+
this.sessionToken = randomUUID();
|
|
116
|
+
saveToken(this.sessionToken);
|
|
117
|
+
this._send({ method: CONTROL.PAIRING_COMPLETE, params: { session_id: randomUUID(), session_token: this.sessionToken } });
|
|
118
|
+
this._send({ method: CONTROL.AUTH_SUCCESS, params: {} });
|
|
119
|
+
log('Pairing approved.');
|
|
120
|
+
} else {
|
|
121
|
+
log('Pairing rejected or wrong code.');
|
|
122
|
+
}
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (msg.method === CONTROL.PONG) return;
|
|
127
|
+
|
|
128
|
+
// Action result correlation.
|
|
129
|
+
if (msg.id && this.pending.has(msg.id)) {
|
|
130
|
+
const { resolve, reject, timer } = this.pending.get(msg.id);
|
|
131
|
+
clearTimeout(timer);
|
|
132
|
+
this.pending.delete(msg.id);
|
|
133
|
+
if (msg.error) reject(new Error(msg.error.message || 'Action failed'));
|
|
134
|
+
else resolve(msg.result);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Forward an action to the extension and await the result. */
|
|
139
|
+
callAction(action, params = {}) {
|
|
140
|
+
if (!this.socket || this.socket.readyState !== this.socket.OPEN) {
|
|
141
|
+
return Promise.reject(new Error('Reply Wizard extension is not connected. Open WhatsApp Web and enable AI client access in the extension.'));
|
|
142
|
+
}
|
|
143
|
+
if (!this.paired) {
|
|
144
|
+
return Promise.reject(new Error('Not paired yet. Enter the pairing code shown above in the extension popup.'));
|
|
145
|
+
}
|
|
146
|
+
const id = randomUUID();
|
|
147
|
+
return new Promise((resolve, reject) => {
|
|
148
|
+
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`Action "${action}" timed out.`)); }, this.requestTimeoutMs);
|
|
149
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
150
|
+
this._send({ id, method: 'action', action, params });
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
_send(obj) {
|
|
155
|
+
if (this.socket && this.socket.readyState === this.socket.OPEN) this.socket.send(JSON.stringify(obj));
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
_failAllPending(err) {
|
|
159
|
+
for (const { reject, timer } of this.pending.values()) { clearTimeout(timer); reject(err); }
|
|
160
|
+
this.pending.clear();
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
close() {
|
|
164
|
+
this._failAllPending(new Error('Hub shutting down.'));
|
|
165
|
+
if (this.wss) this.wss.close();
|
|
166
|
+
}
|
|
167
|
+
}
|