wa-mcp-server 0.1.0__tar.gz

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.
Files changed (48) hide show
  1. wa_mcp_server-0.1.0/.gitignore +32 -0
  2. wa_mcp_server-0.1.0/PKG-INFO +9 -0
  3. wa_mcp_server-0.1.0/pyproject.toml +21 -0
  4. wa_mcp_server-0.1.0/tests/remote_env.py +131 -0
  5. wa_mcp_server-0.1.0/tests/test_accounts_server.py +231 -0
  6. wa_mcp_server-0.1.0/tests/test_ai_vision_stdio.py +237 -0
  7. wa_mcp_server-0.1.0/tests/test_deploy_files.py +80 -0
  8. wa_mcp_server-0.1.0/tests/test_embed.py +98 -0
  9. wa_mcp_server-0.1.0/tests/test_import_tool.py +192 -0
  10. wa_mcp_server-0.1.0/tests/test_remote_http.py +187 -0
  11. wa_mcp_server-0.1.0/tests/test_remote_oauth.py +466 -0
  12. wa_mcp_server-0.1.0/tests/test_remote_units.py +560 -0
  13. wa_mcp_server-0.1.0/tests/test_round2_server.py +99 -0
  14. wa_mcp_server-0.1.0/tests/test_round3_server.py +41 -0
  15. wa_mcp_server-0.1.0/tests/test_security_status.py +92 -0
  16. wa_mcp_server-0.1.0/tests/test_stdio_tools.py +634 -0
  17. wa_mcp_server-0.1.0/wa_mcp_server/__init__.py +3 -0
  18. wa_mcp_server-0.1.0/wa_mcp_server/__main__.py +3 -0
  19. wa_mcp_server-0.1.0/wa_mcp_server/agent_cli.py +64 -0
  20. wa_mcp_server-0.1.0/wa_mcp_server/app.py +124 -0
  21. wa_mcp_server-0.1.0/wa_mcp_server/common.py +379 -0
  22. wa_mcp_server-0.1.0/wa_mcp_server/embed.py +89 -0
  23. wa_mcp_server-0.1.0/wa_mcp_server/py.typed +0 -0
  24. wa_mcp_server-0.1.0/wa_mcp_server/remote/__init__.py +13 -0
  25. wa_mcp_server-0.1.0/wa_mcp_server/remote/cli.py +201 -0
  26. wa_mcp_server-0.1.0/wa_mcp_server/remote/consent.py +357 -0
  27. wa_mcp_server-0.1.0/wa_mcp_server/remote/guard.py +252 -0
  28. wa_mcp_server-0.1.0/wa_mcp_server/remote/http.py +228 -0
  29. wa_mcp_server-0.1.0/wa_mcp_server/remote/oauth.py +492 -0
  30. wa_mcp_server-0.1.0/wa_mcp_server/remote/sdk.py +66 -0
  31. wa_mcp_server-0.1.0/wa_mcp_server/remote/settings.py +328 -0
  32. wa_mcp_server-0.1.0/wa_mcp_server/remote/store.py +643 -0
  33. wa_mcp_server-0.1.0/wa_mcp_server/remote/web/consent.html +101 -0
  34. wa_mcp_server-0.1.0/wa_mcp_server/tools/__init__.py +1 -0
  35. wa_mcp_server-0.1.0/wa_mcp_server/tools/accounts.py +21 -0
  36. wa_mcp_server-0.1.0/wa_mcp_server/tools/agent.py +110 -0
  37. wa_mcp_server-0.1.0/wa_mcp_server/tools/calls.py +37 -0
  38. wa_mcp_server-0.1.0/wa_mcp_server/tools/chat_import.py +73 -0
  39. wa_mcp_server-0.1.0/wa_mcp_server/tools/chats.py +104 -0
  40. wa_mcp_server-0.1.0/wa_mcp_server/tools/history.py +78 -0
  41. wa_mcp_server-0.1.0/wa_mcp_server/tools/images.py +64 -0
  42. wa_mcp_server-0.1.0/wa_mcp_server/tools/insight.py +228 -0
  43. wa_mcp_server-0.1.0/wa_mcp_server/tools/media.py +135 -0
  44. wa_mcp_server-0.1.0/wa_mcp_server/tools/messages.py +131 -0
  45. wa_mcp_server-0.1.0/wa_mcp_server/tools/schedule.py +101 -0
  46. wa_mcp_server-0.1.0/wa_mcp_server/tools/send.py +295 -0
  47. wa_mcp_server-0.1.0/wa_mcp_server/tools/status.py +54 -0
  48. wa_mcp_server-0.1.0/wa_mcp_server/tools/transcribe.py +43 -0
@@ -0,0 +1,32 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ .mypy_cache/
5
+ .ruff_cache/
6
+ .pytest_cache/
7
+ .coverage
8
+ htmlcov/
9
+ dist/
10
+ *.egg-info/
11
+ /config.json
12
+ /store/
13
+ /downloads/
14
+ /exports/
15
+ store/
16
+ !bridge/internal/store/
17
+ *.db
18
+ *.db-wal
19
+ *.db-shm
20
+ .env
21
+ .env.*
22
+ api.token
23
+ *.dpapi
24
+ /wa-bridge
25
+ /wa-bridge.exe
26
+ # Local settings and secrets of deploy/docker
27
+ deploy/docker/config.json
28
+ deploy/docker/secrets/*
29
+ !deploy/docker/secrets/README.md
30
+ !deploy/docker/secrets/make-key.sh
31
+ *.key
32
+ *_key
@@ -0,0 +1,9 @@
1
+ Metadata-Version: 2.5
2
+ Name: wa-mcp-server
3
+ Version: 0.1.0
4
+ Summary: MCP server (stdio and Streamable HTTP) that gives AI assistants access to a wa-mcp WhatsApp bridge
5
+ Author: tsahospital-beep
6
+ License-Expression: MIT
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: mcp~=1.30
9
+ Requires-Dist: wa-mcp-sdk>=0.1.0
@@ -0,0 +1,21 @@
1
+ [project]
2
+ name = "wa-mcp-server"
3
+ version = "0.1.0"
4
+ description = "MCP server (stdio and Streamable HTTP) that gives AI assistants access to a wa-mcp WhatsApp bridge"
5
+ license = "MIT"
6
+ authors = [{ name = "tsahospital-beep" }]
7
+ requires-python = ">=3.11"
8
+ dependencies = [
9
+ "wa-mcp-sdk>=0.1.0",
10
+ "mcp~=1.30",
11
+ ]
12
+
13
+ [project.scripts]
14
+ wa-mcp = "wa_mcp_server.app:main"
15
+
16
+ [build-system]
17
+ requires = ["hatchling>=1.25.0"]
18
+ build-backend = "hatchling.build"
19
+
20
+ [tool.hatch.build.targets.wheel]
21
+ packages = ["wa_mcp_server"]
@@ -0,0 +1,131 @@
1
+ """Helpers for the remote-mode tests: a synthetic store, the wa-mcp CLI and a real HTTP server process."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import json
7
+ import os
8
+ import shutil
9
+ import socket
10
+ import subprocess
11
+ import sys
12
+ import time
13
+ from collections.abc import Iterator
14
+ from dataclasses import dataclass
15
+ from datetime import timedelta
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ import httpx
20
+
21
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "sdk" / "python" / "tests"))
22
+
23
+ import synth
24
+ from mcp import ClientSession
25
+ from mcp.client.streamable_http import streamable_http_client
26
+
27
+ PASSWORD = "correct horse battery staple"
28
+
29
+
30
+ def free_port() -> int:
31
+ with socket.socket() as probe:
32
+ probe.bind(("127.0.0.1", 0))
33
+ return int(probe.getsockname()[1])
34
+
35
+
36
+ def command() -> list[str]:
37
+ exe = shutil.which("wa-mcp", path=str(Path(sys.executable).parent))
38
+ return [exe] if exe else [sys.executable, "-m", "wa_mcp_server"]
39
+
40
+
41
+ def environ(cfg: Path, **extra: str) -> dict[str, str]:
42
+ env = {k: v for k, v in os.environ.items() if not k.startswith("WA_MCP_")}
43
+ env.update(WA_MCP_CONFIG=str(cfg), PYTHONDONTWRITEBYTECODE="1", **extra)
44
+ return env
45
+
46
+
47
+ def make_store(root: Path, port: int, server: dict[str, Any]) -> Path:
48
+ """config.json with a server section, a synthetic wa.db and no reachable bridge."""
49
+ cfg = synth.make_config(root, port=free_port(), server={"listen": f"127.0.0.1:{port}", **server})
50
+ synth.build_wa_db(root / "store" / "wa.db")
51
+ synth.build_session_db(root / "store" / "session.db")
52
+ return cfg
53
+
54
+
55
+ def cli(cfg: Path, *args: str, env: dict[str, str] | None = None) -> subprocess.CompletedProcess[str]:
56
+ return subprocess.run(
57
+ [*command(), *args],
58
+ env=env or environ(cfg),
59
+ capture_output=True,
60
+ text=True,
61
+ encoding="utf-8",
62
+ timeout=120,
63
+ check=False,
64
+ )
65
+
66
+
67
+ def create_token(cfg: Path, name: str) -> str:
68
+ out = cli(cfg, "token", "create", "--name", name)
69
+ assert out.returncode == 0, out.stderr
70
+ return next(w for w in out.stdout.split() if w.startswith("wam_"))
71
+
72
+
73
+ @dataclass
74
+ class Server:
75
+ base: str
76
+ cfg: Path
77
+ log: Path
78
+ proc: subprocess.Popen[bytes]
79
+
80
+ def log_text(self) -> str:
81
+ return self.log.read_text(encoding="utf-8", errors="replace")
82
+
83
+
84
+ @contextlib.contextmanager
85
+ def running(cfg: Path, port: int, *args: str, env: dict[str, str] | None = None) -> Iterator[Server]:
86
+ """Start `wa-mcp serve --http` and stop it (by its own PID) afterwards."""
87
+ log = cfg.parent / f"server-{port}.log"
88
+ with log.open("wb") as fh:
89
+ proc = subprocess.Popen(
90
+ [*command(), "serve", "--http", *args],
91
+ env=env or environ(cfg),
92
+ stdout=fh,
93
+ stderr=subprocess.STDOUT,
94
+ )
95
+ server = Server(base=f"http://127.0.0.1:{port}", cfg=cfg, log=log, proc=proc)
96
+ try:
97
+ deadline = time.monotonic() + 60
98
+ while True:
99
+ if proc.poll() is not None:
100
+ raise RuntimeError(f"server stopped: {server.log_text()}")
101
+ try:
102
+ if httpx.get(server.base + "/health", timeout=2, trust_env=False).status_code == 200:
103
+ break
104
+ except httpx.HTTPError:
105
+ pass
106
+ if time.monotonic() > deadline:
107
+ raise RuntimeError(f"server did not start: {server.log_text()}")
108
+ time.sleep(0.2)
109
+ yield server
110
+ finally:
111
+ proc.terminate()
112
+ try:
113
+ proc.wait(timeout=15)
114
+ except subprocess.TimeoutExpired:
115
+ proc.kill()
116
+ proc.wait(timeout=15)
117
+
118
+
119
+ async def mcp_session(url: str, auth: httpx.Auth | None = None, token: str = "") -> dict[str, Any]:
120
+ """initialize, list the tools and call list_chats over Streamable HTTP."""
121
+ headers = {"Authorization": f"Bearer {token}"} if token else {}
122
+ async with (
123
+ httpx.AsyncClient(headers=headers, auth=auth, timeout=60, trust_env=False) as http,
124
+ streamable_http_client(url, http_client=http) as (read, write, _),
125
+ ClientSession(read, write) as session,
126
+ ):
127
+ init = await session.initialize()
128
+ tools = {t.name for t in (await session.list_tools()).tools}
129
+ res = await session.call_tool("list_chats", {}, read_timeout_seconds=timedelta(seconds=60))
130
+ data = json.loads("".join(getattr(c, "text", "") for c in res.content))
131
+ return {"server": init.serverInfo.name, "tools": tools, "list_chats": data}
@@ -0,0 +1,231 @@
1
+ """Two accounts through the real stdio server: each tool call goes to the store and bridge of its account."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import importlib.util
7
+ import json
8
+ import os
9
+ import shutil
10
+ import sys
11
+ import threading
12
+ from collections.abc import Iterator
13
+ from datetime import datetime, timedelta
14
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import pytest
19
+
20
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "sdk" / "python" / "tests"))
21
+
22
+ import synth
23
+ from mcp import ClientSession, StdioServerParameters
24
+ from mcp.client.stdio import stdio_client
25
+
26
+ from wa_mcp_server.app import ACCOUNTS_NOTE
27
+
28
+ TOKEN = "test-token-0123456789"
29
+ T0_DAY = datetime.fromtimestamp(synth.T0).date().isoformat()
30
+
31
+
32
+ def fake_bridge(number: str) -> tuple[ThreadingHTTPServer, list[tuple[str, str, Any]]]:
33
+ """A bridge API on a free port that records requests and reports `number` as its account."""
34
+ seen: list[tuple[str, str, Any]] = []
35
+
36
+ class Handler(BaseHTTPRequestHandler):
37
+ def _reply(self, status: int, data: dict[str, Any]) -> None:
38
+ out = json.dumps(data).encode()
39
+ self.send_response(status)
40
+ self.send_header("Content-Type", "application/json")
41
+ self.send_header("Content-Length", str(len(out)))
42
+ self.end_headers()
43
+ self.wfile.write(out)
44
+
45
+ def _handle(self, method: str) -> None:
46
+ if self.headers.get("Authorization") != f"Bearer {TOKEN}":
47
+ self._reply(401, {"ok": False, "error": "unauthorized"})
48
+ return
49
+ length = int(self.headers.get("Content-Length") or 0)
50
+ body = json.loads(self.rfile.read(length)) if length else None
51
+ path = self.path.split("?", 1)[0].removeprefix("/api/v1")
52
+ seen.append((method, path, body))
53
+ if path == "/status":
54
+ self._reply(
55
+ 200, {"ok": True, "connected": True, "logged_in": True, "account": number, "version": "t"}
56
+ )
57
+ elif path == "/send":
58
+ self._reply(
59
+ 200, {"ok": True, "id": "SENT-" + number[-4:], "sent_at": synth.T0, "waited_ms": 0}
60
+ )
61
+ else:
62
+ self._reply(404, {"ok": False, "error": "not found"})
63
+
64
+ def do_GET(self) -> None:
65
+ self._handle("GET")
66
+
67
+ def do_POST(self) -> None:
68
+ self._handle("POST")
69
+
70
+ def log_message(self, *args: Any) -> None:
71
+ return
72
+
73
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
74
+ threading.Thread(target=server.serve_forever, daemon=True).start()
75
+ return server, seen
76
+
77
+
78
+ @pytest.fixture(scope="module")
79
+ def env(tmp_path_factory: pytest.TempPathFactory) -> Iterator[dict[str, Any]]:
80
+ root = tmp_path_factory.mktemp("accounts")
81
+ home, home_seen = fake_bridge("+1 *** *** 0001")
82
+ work, work_seen = fake_bridge("+1 *** *** 0009")
83
+ cfg = synth.make_config(
84
+ root,
85
+ port=home.server_address[1],
86
+ sending={"enabled": False},
87
+ accounts={
88
+ "work": {
89
+ "api": {"listen": f"127.0.0.1:{work.server_address[1]}"},
90
+ "sending": {"enabled": True, "require_confirm": True, "allow_confirm_flag": True},
91
+ }
92
+ },
93
+ )
94
+ synth.build_wa_db(root / "store" / "wa.db")
95
+ synth.build_session_db(root / "store" / "session.db")
96
+ synth.build_work_store(root / "store" / "work")
97
+ yield {"root": root, "cfg": cfg, "home": home_seen, "work": work_seen}
98
+ home.shutdown()
99
+ work.shutdown()
100
+
101
+
102
+ def _command() -> tuple[str, list[str]]:
103
+ exe = shutil.which("wa-mcp", path=str(Path(sys.executable).parent))
104
+ return (exe, []) if exe else (sys.executable, ["-m", "wa_mcp_server"])
105
+
106
+
107
+ async def _session(cfg: Path, calls: list[tuple[str, dict[str, Any]]]) -> dict[str, Any]:
108
+ command, args = _command()
109
+ environ = dict(os.environ, WA_MCP_CONFIG=str(cfg))
110
+ environ.pop("WA_MCP_SENDING_ENABLED", None)
111
+ params = StdioServerParameters(command=command, args=args, env=environ)
112
+ results: list[dict[str, Any]] = []
113
+ async with stdio_client(params) as (read, write), ClientSession(read, write) as session:
114
+ init = await session.initialize()
115
+ tools = (await session.list_tools()).tools
116
+ for name, arguments in calls:
117
+ res = await session.call_tool(name, arguments, read_timeout_seconds=timedelta(seconds=90))
118
+ results.append(json.loads("".join(getattr(c, "text", "") for c in res.content)))
119
+ return {"instructions": init.instructions or "", "tools": tools, "results": results}
120
+
121
+
122
+ @pytest.fixture(scope="module")
123
+ def run(env: dict[str, Any]) -> dict[str, Any]:
124
+ calls: list[tuple[str, dict[str, Any]]] = [
125
+ ("list_accounts", {}),
126
+ ("list_messages", {"query": "quarterly"}),
127
+ ("list_messages", {"query": "quarterly", "account": "work"}),
128
+ ("get_chat", {"chat": "Dana", "account": "work"}),
129
+ ("get_chat", {"chat": "Dana"}),
130
+ ("bridge_status", {"account": "work"}),
131
+ ("bridge_status", {}),
132
+ ("send_message", {"to": synth.DANA, "text": "On it", "confirm": True}),
133
+ ("send_message", {"to": synth.DANA, "text": "On it", "confirm": True, "account": "work"}),
134
+ ("list_chats", {"account": "club"}),
135
+ ("my_day", {"date": T0_DAY}),
136
+ ("my_day", {"date": T0_DAY, "account": "work"}),
137
+ ("list_accounts", {"account": "work"}),
138
+ ]
139
+ return asyncio.run(_session(env["cfg"], calls))
140
+
141
+
142
+ def test_every_tool_takes_an_account(run: dict[str, Any]) -> None:
143
+ tools = {t.name: t for t in run["tools"]}
144
+ assert "list_accounts" in tools
145
+ missing = sorted(
146
+ n for n, t in tools.items() if "account" not in (t.inputSchema or {}).get("properties", {})
147
+ )
148
+ assert not missing, missing
149
+ prop = tools["list_messages"].inputSchema["properties"]["account"]
150
+ assert "list_accounts" in prop["description"] and "account" not in tools["list_messages"].inputSchema.get(
151
+ "required", []
152
+ )
153
+ assert ACCOUNTS_NOTE.strip() in run["instructions"]
154
+
155
+
156
+ def test_list_accounts(run: dict[str, Any]) -> None:
157
+ res = run["results"][0]
158
+ assert res["ok"] and res["count"] == 2 and res["default"] == "default"
159
+ home, work = res["accounts"]
160
+ assert home["name"] == "default" and home["store"] == "store" and home["number"] == "+1 *** *** 0001"
161
+ assert work["name"] == "work" and work["store"] == "store/work" and work["number"] == "+1 *** *** 0009"
162
+ for a in (home, work):
163
+ assert a["linked"] is True and a["bridge_running"] is True and a["connected"] is True
164
+ assert home["sending_enabled"] is False and work["sending_enabled"] is True
165
+ only = run["results"][12]
166
+ assert only["count"] == 1 and only["accounts"][0]["name"] == "work"
167
+
168
+
169
+ def test_reads_go_to_the_right_store(run: dict[str, Any]) -> None:
170
+ r = run["results"]
171
+ assert r[1]["ok"] and r[1]["messages"] == []
172
+ assert [m["id"] for m in r[2]["messages"]] == ["W1"]
173
+ assert r[3]["ok"] and r[3]["chat"]["jid"] == synth.DANA and r[3]["chat"]["name"] == "Dana Work"
174
+ assert r[4]["ok"] is False and "Dana" in r[4]["error"]
175
+
176
+
177
+ def test_stdio_reports_optional_speech_backend(run: dict[str, Any]) -> None:
178
+ status = run["results"][6]
179
+ assert status["transcription_backend"] == "faster-whisper"
180
+ assert status["transcription_ready"] == (importlib.util.find_spec("faster_whisper") is not None)
181
+
182
+
183
+ def test_bridge_calls_go_to_the_right_bridge(run: dict[str, Any], env: dict[str, Any]) -> None:
184
+ r = run["results"]
185
+ assert r[5]["bridge"]["account"] == "+1 *** *** 0009" and r[5]["sending_enabled"] is True
186
+ assert r[6]["bridge"]["account"] == "+1 *** *** 0001" and r[6]["sending_enabled"] is False
187
+ # sending settings are per account: off for default, on for work
188
+ assert r[7]["ok"] is False and "disabled" in r[7]["error"]
189
+ assert r[8]["ok"] and r[8]["id"] == "SENT-0009" and r[8]["to_name"] == "Dana Work"
190
+ assert [p for _, p, _ in env["home"] if p == "/send"] == []
191
+ work_sends = [b for _, p, b in env["work"] if p == "/send"]
192
+ assert len(work_sends) == 1 and work_sends[0]["to"] == synth.DANA and work_sends[0]["text"] == "On it"
193
+
194
+
195
+ def test_unknown_account(run: dict[str, Any]) -> None:
196
+ res = run["results"][9]
197
+ assert res["ok"] is False and 'account "club" is not configured (accounts: default, work)' in res["error"]
198
+
199
+
200
+ def test_my_day_covers_all_accounts(run: dict[str, Any], env: dict[str, Any]) -> None:
201
+ merged, work = run["results"][10], run["results"][11]
202
+ assert merged["ok"] and merged["accounts"] == ["default", "work"]
203
+ assert {g["account"] for g in merged["people"]} <= {"default", "work"}
204
+ assert all(it["account"] in ("default", "work") for g in merged["people"] for it in g["items"])
205
+ assert work["ok"] and work["accounts"] == ["work"]
206
+ assert all(g["account"] == "work" for g in work["people"])
207
+ assert (env["root"] / "store" / "work" / "insight.db").is_file()
208
+
209
+
210
+ def test_approval_prompt_names_the_account(env: dict[str, Any]) -> None:
211
+ from wa_mcp import config, db
212
+ from wa_mcp_server import common
213
+ from wa_mcp_server.tools import send
214
+
215
+ common.setup(config.load(env["cfg"]))
216
+ with db.use_account("work"):
217
+ checked = send.plan(synth.DANA, text="On it")
218
+ assert checked.lines[0] == "From account: work" and checked.lines[1].startswith("To: Dana Work")
219
+
220
+
221
+ def test_single_account_output_has_no_account_fields(tmp_path: Path) -> None:
222
+ cfg = synth.make_config(tmp_path, port=1)
223
+ synth.build_wa_db(tmp_path / "store" / "wa.db")
224
+ synth.build_session_db(tmp_path / "store" / "session.db")
225
+ out = asyncio.run(_session(cfg, [("my_day", {"date": T0_DAY}), ("list_accounts", {})]))
226
+ day, listing = out["results"]
227
+ assert day["ok"] and "accounts" not in day
228
+ assert all("account" not in g for g in day["people"])
229
+ assert listing["count"] == 1 and listing["accounts"][0]["name"] == "default"
230
+ assert listing["accounts"][0]["bridge_running"] is False
231
+ assert ACCOUNTS_NOTE.strip() not in out["instructions"]
@@ -0,0 +1,237 @@
1
+ """Image text, image descriptions and the my_day summary through the real MCP stdio server.
2
+
3
+ The AI provider is a small HTTP server on 127.0.0.1 that speaks the OpenAI chat completions format.
4
+ OCR runs a fake tesseract program that is put first on PATH.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import json
11
+ import os
12
+ import shutil
13
+ import sqlite3
14
+ import sys
15
+ import threading
16
+ from collections.abc import Iterator
17
+ from datetime import datetime, timedelta
18
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
19
+ from pathlib import Path
20
+ from typing import Any, ClassVar
21
+
22
+ import pytest
23
+
24
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "sdk" / "python" / "tests"))
25
+
26
+ import synth
27
+ from mcp import ClientSession, StdioServerParameters
28
+ from mcp.client.stdio import stdio_client
29
+ from vision_data import PNG, fake_tesseract
30
+
31
+ from wa_mcp_server.common import UNTRUSTED
32
+
33
+ KEY = "stdio-test-key-42"
34
+ T0_DAY = datetime.fromtimestamp(synth.T0).date().isoformat()
35
+ NOT_CONFIGURED = "no AI provider configured; your assistant can summarize this"
36
+
37
+
38
+ class FakeAI(BaseHTTPRequestHandler):
39
+ requests: ClassVar[list[dict[str, Any]]] = []
40
+
41
+ def do_POST(self) -> None:
42
+ length = int(self.headers.get("Content-Length") or 0)
43
+ body = json.loads(self.rfile.read(length))
44
+ FakeAI.requests.append({"path": self.path, "auth": self.headers.get("Authorization"), "body": body})
45
+ user = body["messages"][-1]["content"]
46
+ text = "A screenshot of an invoice." if isinstance(user, list) else "Two things need you today."
47
+ out = json.dumps({"choices": [{"message": {"role": "assistant", "content": text}}]}).encode()
48
+ self.send_response(200)
49
+ self.send_header("Content-Type", "application/json")
50
+ self.send_header("Content-Length", str(len(out)))
51
+ self.end_headers()
52
+ self.wfile.write(out)
53
+
54
+ def log_message(self, *args: Any) -> None:
55
+ return
56
+
57
+
58
+ def _store(root: Path, config_extra: dict[str, Any], images: list[str]) -> Path:
59
+ cfg = synth.make_config(root, **config_extra)
60
+ synth.build_wa_db(root / "store" / "wa.db")
61
+ synth.build_session_db(root / "store" / "session.db")
62
+ conn = sqlite3.connect(root / "store" / "wa.db")
63
+ for i, msg_id in enumerate(images):
64
+ path = root / "downloads" / f"{msg_id}.png"
65
+ path.parent.mkdir(parents=True, exist_ok=True)
66
+ path.write_bytes(PNG)
67
+ conn.execute(
68
+ "INSERT INTO chat_messages (conv, msg_id, author, sent_at, body, kind, mime, local_path) "
69
+ "VALUES (?, ?, ?, ?, '', 'image', 'image/png', ?)",
70
+ (synth.ALICE, msg_id, synth.ALICE, synth.T0 + 1000 + i * 10, str(path)),
71
+ )
72
+ conn.commit()
73
+ conn.close()
74
+ return cfg
75
+
76
+
77
+ async def _session(
78
+ cfg: Path, calls: list[tuple[str, dict[str, Any]]], path_first: Path | None = None
79
+ ) -> list[dict[str, Any]]:
80
+ scripts = Path(sys.executable).parent
81
+ exe = shutil.which("wa-mcp", path=str(scripts))
82
+ command, args = (exe, []) if exe else (sys.executable, ["-m", "wa_mcp_server"])
83
+ environ = dict(os.environ, WA_MCP_CONFIG=str(cfg), WA_MCP_AI_TEST_KEY=KEY)
84
+ environ.pop("WA_MCP_SENDING_ENABLED", None)
85
+ if path_first is not None:
86
+ environ["PATH"] = f"{path_first}{os.pathsep}{environ.get('PATH', '')}"
87
+ params = StdioServerParameters(command=command, args=args, env=environ)
88
+ results: list[dict[str, Any]] = []
89
+ async with stdio_client(params) as (read, write), ClientSession(read, write) as session:
90
+ await session.initialize()
91
+ for name, arguments in calls:
92
+ res = await session.call_tool(name, arguments, read_timeout_seconds=timedelta(seconds=90))
93
+ data = json.loads("".join(getattr(c, "text", "") for c in res.content))
94
+ data["_raw"] = "".join(getattr(c, "text", "") for c in res.content)
95
+ results.append(data)
96
+ return results
97
+
98
+
99
+ @pytest.fixture(scope="module")
100
+ def ai_server() -> Iterator[str]:
101
+ server = ThreadingHTTPServer(("127.0.0.1", 0), FakeAI)
102
+ threading.Thread(target=server.serve_forever, daemon=True).start()
103
+ yield f"http://127.0.0.1:{server.server_address[1]}/v1"
104
+ server.shutdown()
105
+
106
+
107
+ @pytest.fixture(scope="module")
108
+ def with_provider(tmp_path_factory: pytest.TempPathFactory, ai_server: str) -> dict[str, Any]:
109
+ root = tmp_path_factory.mktemp("ai-on")
110
+ folder = root / "bin"
111
+ fake_tesseract(folder, out="Invoice 4711\nDue Friday\n")
112
+ cfg = _store(
113
+ root,
114
+ {
115
+ "ai": {
116
+ "provider": "openai-compatible",
117
+ "base_url": ai_server,
118
+ "text_model": "text-m",
119
+ "vision_model": "vision-m",
120
+ "api_key_env": "WA_MCP_AI_TEST_KEY",
121
+ "max_calls_per_day": 3,
122
+ },
123
+ "vision": {"ocr": "tesseract", "languages": ["eng"]},
124
+ },
125
+ ["IMG1", "IMG2"],
126
+ )
127
+ FakeAI.requests.clear()
128
+ calls: list[tuple[str, dict[str, Any]]] = [
129
+ ("bridge_status", {}),
130
+ ("read_images", {"chat": "Alice", "describe": True}),
131
+ ("list_messages", {"chat": "Alice", "query": "4711"}),
132
+ ("get_media_text", {"chat": "Alice", "message_id": "IMG1"}),
133
+ ("read_images", {"chat": "Alice", "describe": True}),
134
+ ("my_day", {"date": T0_DAY, "summary": True}),
135
+ ("my_day", {"date": T0_DAY}),
136
+ ("my_day", {"date": T0_DAY, "summary": True}),
137
+ ("read_images", {"chat": "Alice", "describe": True, "force": True}),
138
+ ]
139
+ results = asyncio.run(_session(cfg, calls, path_first=folder))
140
+ by: dict[str, list[dict[str, Any]]] = {}
141
+ for (name, _), res in zip(calls, results, strict=True):
142
+ by.setdefault(name, []).append(res)
143
+ return {"by": by, "results": results, "requests": list(FakeAI.requests)}
144
+
145
+
146
+ def test_status_reports_ocr_and_provider(with_provider: dict[str, Any]) -> None:
147
+ status = with_provider["by"]["bridge_status"][0]
148
+ assert status["ai_provider"] == "openai-compatible" and status["ocr_engine"] == "tesseract"
149
+ assert status["ocr_ready"] is True
150
+
151
+
152
+ def test_read_images_reads_and_describes(with_provider: dict[str, Any]) -> None:
153
+ first = with_provider["by"]["read_images"][0]
154
+ assert first["ok"] is True and first["complete"] is True and first["candidates"] == 2
155
+ assert {r["msg_id"] for r in first["read"]} == {"IMG1", "IMG2"}
156
+ item = first["read"][0]
157
+ assert item["text"] == "Invoice 4711\nDue Friday" and item["description"] == "A screenshot of an invoice."
158
+ assert first["note"] == UNTRUSTED
159
+
160
+
161
+ def test_image_text_is_searchable_and_shown(with_provider: dict[str, Any]) -> None:
162
+ found = with_provider["by"]["list_messages"][0]["messages"]
163
+ assert {m["id"] for m in found} == {"IMG1", "IMG2"}
164
+ assert found[0]["image_text"] == "Invoice 4711\nDue Friday"
165
+ assert found[0]["image_description"] == "A screenshot of an invoice."
166
+ media = with_provider["by"]["get_media_text"][0]
167
+ assert media["ok"] and media["kind"] == "image"
168
+ assert {(i["source"], i["text"]) for i in media["items"]} == {
169
+ ("image", "Invoice 4711\nDue Friday"),
170
+ ("image_description", "A screenshot of an invoice."),
171
+ }
172
+
173
+
174
+ def test_second_run_skips_finished_images(with_provider: dict[str, Any]) -> None:
175
+ second = with_provider["by"]["read_images"][1]
176
+ assert second["ok"] and second["read"] == [] and second["already_done"] == 2
177
+
178
+
179
+ def test_my_day_summary_and_the_default(with_provider: dict[str, Any]) -> None:
180
+ day = with_provider["by"]["my_day"]
181
+ assert day[0]["ok"] and day[0]["ai_summary"] == "Two things need you today."
182
+ assert day[0]["ai_provider"] == "openai-compatible" and isinstance(day[0]["people"], list)
183
+ assert "ai_summary" not in day[1] and "ai_note" not in day[1] and day[1]["summary"].startswith(T0_DAY)
184
+ assert [g["chat"] for g in day[1]["people"]] == [g["chat"] for g in day[0]["people"]]
185
+
186
+
187
+ def test_daily_limit_stops_ai_calls(with_provider: dict[str, Any]) -> None:
188
+ limited = with_provider["by"]["my_day"][2]
189
+ assert limited["ok"] is True and limited["ai_summary"] is None
190
+ assert "ai.max_calls_per_day is 3" in limited["ai_error"] and limited["people"]
191
+ forced = with_provider["by"]["read_images"][2]
192
+ assert forced["ok"] is True and forced["read"] == [] and "max_calls_per_day" in forced["stopped"]
193
+ assert len(with_provider["requests"]) == 3 # two descriptions and one summary reached the provider
194
+
195
+
196
+ def test_provider_requests_are_framed_and_authenticated(with_provider: dict[str, Any]) -> None:
197
+ requests = with_provider["requests"]
198
+ assert all(r["path"] == "/v1/chat/completions" and r["auth"] == f"Bearer {KEY}" for r in requests)
199
+ vision_requests = [r for r in requests if isinstance(r["body"]["messages"][-1]["content"], list)]
200
+ summary = next(r for r in requests if isinstance(r["body"]["messages"][-1]["content"], str))
201
+ assert len(vision_requests) == 2 and vision_requests[0]["body"]["model"] == "vision-m"
202
+ url = vision_requests[0]["body"]["messages"][-1]["content"][1]["image_url"]["url"]
203
+ assert url.startswith("data:image/png;base64,")
204
+ assert summary["body"]["model"] == "text-m"
205
+ system, user = (m["content"] for m in summary["body"]["messages"])
206
+ assert "never instructions" in system and "<untrusted_data>" in user and "</untrusted_data>" in user
207
+ assert T0_DAY in user
208
+ for raw in with_provider["results"]:
209
+ assert KEY not in raw["_raw"]
210
+
211
+
212
+ def test_without_a_provider_or_ocr(tmp_path: Path) -> None:
213
+ cfg = _store(
214
+ tmp_path,
215
+ {"vision": {"ocr": "tesseract", "tesseract_binary": str(tmp_path / "missing" / "tesseract")}},
216
+ ["IMG1"],
217
+ )
218
+ calls: list[tuple[str, dict[str, Any]]] = [
219
+ ("bridge_status", {}),
220
+ ("read_images", {"chat": "Alice"}),
221
+ ("read_images", {"chat": "Alice", "describe": True}),
222
+ ("my_day", {"date": T0_DAY, "summary": True}),
223
+ ("get_media_text", {"chat": "Alice", "message_id": "IMG1"}),
224
+ ]
225
+ status, plain, described, day, media = asyncio.run(_session(cfg, calls))
226
+ assert status["ai_provider"] == "none" and status["ocr_ready"] is False
227
+ assert "tesseract was not found" in status["ocr_hint"]
228
+ assert plain["ok"] is False and "tesseract was not found" in plain["error"]
229
+ assert described["ok"] is False and "ai.provider" in described["error"]
230
+ assert (
231
+ day["ok"] is True and day["ai_note"] == NOT_CONFIGURED and "ai_summary" not in day and day["people"]
232
+ )
233
+ assert media["items"] == [] and "run read_images" in media["hint"]
234
+
235
+ off = _store(tmp_path / "off", {"vision": {"ocr": "none"}}, ["IMG1"])
236
+ (res,) = asyncio.run(_session(off, [("read_images", {"chat": "Alice"})]))
237
+ assert res["ok"] is False and "vision.ocr" in res["error"]