diff --git a/bridge/mcp_server.py b/bridge/mcp_server.py index 29d63ab8..59a80d97 100644 --- a/bridge/mcp_server.py +++ b/bridge/mcp_server.py @@ -1,19 +1,31 @@ -"""MCP server (stdio) for the living room TV. Every tool is a thin call to the bridge HTTP API, +"""MCP server for this home's TVs. Every tool is a thin call to the bridge HTTP API, so the bridge stays the only thing that talks to the TV. -Registered for the workspace in .mcp.json as "tv". /api/ask also starts it for each request. +Registered for the workspace in .mcp.json as "tv". /api/ask also starts it for each request (stdio). +COUCH_MCP_HTTP=1 runs it as an HTTP server instead, for Home Assistant's MCP client (docs/AI-AGENT.md): +a smaller, safer tool set with a tv_ prefix, on 127.0.0.1 only. """ +import asyncio +import functools import json import os +import re +import threading import urllib.error import urllib.parse import urllib.request from mcp.server.fastmcp import FastMCP, Image +from mcp.server.transport_security import TransportSecuritySettings +from mcp.types import ToolAnnotations BRIDGE = os.environ.get("BRIDGE_URL", "http://127.0.0.1:5400") ASK_ID = os.environ.get("ASK_ID") TV_ID = os.environ.get("TV_ID") # set by /api/ask: the TV the person asked from +# a per-question stdio child (ASK_ID, from /api/ask) is never the HTTP server, even if the variable leaks in +HTTP = os.environ.get("COUCH_MCP_HTTP") == "1" and not ASK_ID +ALLOW_POWER_OFF = os.environ.get("COUCH_MCP_ALLOW_POWER_OFF") == "1" # HTTP only +ALLOW_SETTINGS = os.environ.get("COUCH_MCP_ALLOW_SETTINGS") == "1" # HTTP only try: # the bridge's pairing key (bridge.pairing_key in config.json, or BRIDGE_KEY), if it has one import config KEY = config.PAIRING_KEY @@ -21,13 +33,34 @@ KEY = os.environ.get("BRIDGE_KEY", "").strip() mcp = FastMCP("tv", instructions=( - "Controls the living room Google TV through the bridge. " + "Controls this home's TVs (Android TV, Google TV) through the couch-tv bridge. " "Use play to put a show or film on, find to see where it streams in this home's country, key/volume/" "launch for remote control, now to see what is on. Never power the TV off unless asked. " "list_widgets and set_widget_setting read and change one widget on the TV home's design. " "There can be more than one TV (tvs); tools default to the TV the person asked from.")) +NO_POWER_OFF = {"ok": False, "error": "Turning the TV off from here is switched off. The person can use the TV remote, " + "or switch it on in the bridge's settings (COUCH_MCP_ALLOW_POWER_OFF=1)."} +HTTP_KEYS = set("""up down left right ok select enter back home play_pause play pause stop next previous rewind + fast_forward volume_up volume_down mute settings menu info guide input search captions channel_up channel_down + 0 1 2 3 4 5 6 7 8 9""".split()) +NO_RAW_KEY = {"ok": False, "error": "Only the keys named in tv_key work from here: " + " ".join(sorted(HTTP_KEYS)) + "."} +def _settings_targets(): + """Every name tv_launch takes for the TV's own settings: the ids, and each kind of TV's package or app id.""" + import apps + pkgs = {apps.BY_ID["settings"]["package"], *apps.BY_ID["settings"].get("packages", [])} + own = {k for t in (apps.TIZEN_TO_PACKAGE, apps.WEBOS_TO_PACKAGE, apps.ROKU_TO_PACKAGE) for k, v in t.items() if v in pkgs} + return {"settings", "bluetooth", "network"} | pkgs | own + + +SETTINGS_TARGETS = _settings_targets() +NO_SETTINGS = {"ok": False, "error": "Opening the TV's settings from here is switched off. The person can use the TV remote, " + "or switch it on in the bridge's settings (COUCH_MCP_ALLOW_SETTINGS=1)."} +NO_LINKS = {"ok": False, "error": "Links can't be opened from here. Use an app id from tv_apps or a package name, " + "or tv_play to put a show on."} + + def call(method, path, payload=None, raw=False, tv=None, timeout=60, headers_out=None): tv = tv or TV_ID if tv: @@ -99,6 +132,18 @@ def key(key: str, hold: bool = False, tv: str | None = None) -> dict: """Press a remote button. Keys: up down left right ok back home play_pause play pause stop next previous rewind fast_forward volume_up volume_down mute power settings menu info guide input search captions channel_up channel_down 0-9. hold=true for a long press.""" + # Over HTTP only the named keys: every TV maker's own raw names include one that turns it off + # (KEYCODE_POWER, KEY_POWER, PowerOff, power_toggle), so a list of the bad ones would miss one. + if HTTP: + k = key.strip().lower() + if k in ("power", "sleep"): + if not ALLOW_POWER_OFF: + return NO_POWER_OFF + elif k == "settings": + if not ALLOW_SETTINGS: + return NO_SETTINGS + elif k not in HTTP_KEYS: + return NO_RAW_KEY return call("POST", "/api/key", {"key": key, "hold": hold}, tv=tv) @@ -113,6 +158,10 @@ def launch(app: str, tv: str | None = None) -> dict: """Open an app on the TV by id (netflix, youtube, stan, binge, abc-iview, sbs-on-demand, disney-plus, prime-video, apple-tv, paramount-plus, kayo, foxtel-go, 9now, 7plus, 10play, hbo-max, spotify, home, settings), by Android package name, or by link.""" + if HTTP and "://" in app: # a link can open any screen of any app, the TV's own settings included + return NO_LINKS + if HTTP and not ALLOW_SETTINGS and app.strip() in SETTINGS_TARGETS: + return NO_SETTINGS return call("POST", "/api/launch", {"app": app}, tv=tv) @@ -131,6 +180,8 @@ def volume(action: str = "up", steps: int = 1, tv: str | None = None) -> dict: @mcp.tool() def power(state: str, tv: str | None = None) -> dict: """Turn the TV on or off: state is on, off or toggle. Only turn it off when clearly asked.""" + if HTTP and state != "on" and not ALLOW_POWER_OFF: + return NO_POWER_OFF return call("POST", "/api/power", {"state": state}, tv=tv) @@ -143,7 +194,7 @@ def tvs() -> dict: @mcp.tool() def history(days: int | None = None, who: str | None = None) -> dict: - """What has been played on our TVs, newest first, with the date and time (Sydney) of each + """What has been played on our TVs, newest first, with the date and time (the home's time zone) of each play, the app, and season and episode when known. days limits it to the last N days (7 for "last week"); who is a person id from config.json, or both. Use it for "what was I watching" and to resume.""" r = call("GET", "/api/history") @@ -260,6 +311,8 @@ def input(name: str, remember_as: str | None = None, tv: str | None = None) -> d def off_after_episode(cancel: bool = False, tv: str | None = None) -> dict: """Turn the TV off when what is playing now ends (at the credits, or when the next episode starts). The home screen and phone show it as the sleep timer. cancel=true stops it.""" + if HTTP and not cancel and not ALLOW_POWER_OFF: + return NO_POWER_OFF payload = {"cancel": True} if cancel else {} return call("POST", "/api/off-after", payload, tv=tv, timeout=40) @@ -414,5 +467,91 @@ def tv_says(tv: str | None = None) -> dict: return call("GET", "/api/say", tv=tv) +# ---- HTTP mode (COUCH_MCP_HTTP=1): Home Assistant's MCP client ---- +# It gives a tool 30 s in all, shows the model only text, and sends no token, so: a tool that is not done +# in COUCH_MCP_WAIT (24) seconds answers "pending" and finishes in the background; no screenshot and no uninstall; names +# start with tv_; the server listens on 127.0.0.1 only (and FastMCP checks the Host header). +PENDING = {"ok": True, "pending": True, "said": "Still working on it on the TV. Check with tv_now in a minute."} +HTTP_DROP = {"screenshot", "uninstall_app"} +HTTP_READ_ONLY = {"now", "find", "apps", "tvs", "history", "taste", "recs", "screens", "ui", "inputs", + "latest_episode", "both_like", "tv_says", "list_widgets"} +HTTP_PENDING_NOTE = " In this mode the answer may come back as pending while it carries on: check with tv_now." +HTTP_NOTES = {"install_app": HTTP_PENDING_NOTE, "restart_app": HTTP_PENDING_NOTE, + "launch": " Links are not taken here: use an app id or a package name.", + "key": " Raw key names (KEYCODE_...) are not taken here: only the keys listed."} +HTTP_TV_NOTE = (" tv: the TV's id from tv_list. Without it the tool uses the bridge's default TV. Pass it when" + " the home has more than one TV and the person named one.") +HTTP_INSTRUCTIONS = ( + "Controls this home's TVs (Android TV, Google TV) through the couch-tv bridge. " + "Use tv_play to put a show or film on (it finds the app itself), tv_find to see where it streams, " + "tv_key/tv_volume/tv_launch for remote control, tv_now to see what is on, tv_ui to read the screen. " + "Turning the TV off may be refused. Tools use the bridge's default TV; when the person names a TV, " + "pass its id (from tv_list) as tv.") + + +def _within_wait(fn, srv): + """Run fn in a thread; if it is not done in COUCH_MCP_WAIT seconds, answer PENDING and let it finish alone. + Meanwhile a log line goes down the request's own stream every 2 s: Home Assistant's client gives up on a + stream that is silent for 5 s ("SSE stream ended without a response").""" + @functools.wraps(fn) + async def run(*a, **k): + loop = asyncio.get_running_loop() + done = loop.create_future() + + def work(): + try: + out = fn(*a, **k) + except Exception as e: + out = e + try: + loop.call_soon_threadsafe(lambda: done.done() or done.set_result(out)) + except RuntimeError: # the server has stopped + pass + threading.Thread(target=work, daemon=True).start() + ctx = srv.get_context() + end = loop.time() + float(os.environ.get("COUCH_MCP_WAIT") or 24) + while not done.done(): + left = end - loop.time() + if left <= 0: + return PENDING + try: + await asyncio.wait_for(asyncio.shield(done), min(2, left)) + except asyncio.TimeoutError: + try: + await ctx.info("Working on it on the TV.") + except Exception: # the client has gone: the thread still finishes + return PENDING + out = done.result() + if isinstance(out, Exception): + raise out + return out + return run + + +def http_server(port): + # stateless: Home Assistant opens a new session for every call, so there is none to keep (and no + # "standalone SSE writer" error when it closes) + srv = FastMCP("Couch TV", instructions=HTTP_INSTRUCTIONS, host="127.0.0.1", port=port, stateless_http=True, + transport_security=TransportSecuritySettings( + enable_dns_rebinding_protection=True, allowed_hosts=["127.0.0.1:*", "localhost:*"], + allowed_origins=["http://127.0.0.1:*", "http://localhost:*"])) + tools = mcp._tool_manager.list_tools() + names = {t.name: (t.name if t.name.startswith("tv") else "tv_" + t.name) for t in tools} + names["tvs"] = "tv_list" + for t in tools: + if t.name in HTTP_DROP: + continue + text = t.description.replace(", or by link.", ".") + HTTP_NOTES.get(t.name, "") + (HTTP_TV_NOTE if "tv" in t.parameters["properties"] else "") + for old, new in names.items(): # names that are not plain words, so the text points at the HTTP names + if "_" in old or old == "tvs": + text = re.sub(r"\b%s\b" % old, new, text) + srv.add_tool(_within_wait(t.fn, srv), name=names[t.name], description=text, + annotations=ToolAnnotations(readOnlyHint=True) if t.name in HTTP_READ_ONLY else None) + return srv + + if __name__ == "__main__": - mcp.run() + if HTTP: + http_server(int(os.environ.get("COUCH_MCP_PORT") or 5401)).run("streamable-http") + else: + mcp.run() diff --git a/docs/AI-AGENT.md b/docs/AI-AGENT.md index cc665736..f0b2fdfa 100644 --- a/docs/AI-AGENT.md +++ b/docs/AI-AGENT.md @@ -58,6 +58,40 @@ To design homes too, add couch-tv Studio's own MCP server as well: couch-tv Stud Then ask: "Design an autumn home for the lounge TV and put it on the TV." Studio's `send_to_tv` gives a code, and this server's `set_home_design` hands the code to the TV. +## Home Assistant (MCP over HTTP) + +Home Assistant's own MCP client can use the TV tools. Run the same file as a small web server on the +computer that runs the bridge: + +```sh +COUCH_MCP_HTTP=1 BRIDGE_URL=http://127.0.0.1:5400 BRIDGE_KEY=... .venv/bin/python bridge/mcp_server.py +``` + +In Home Assistant, add the Model Context Protocol integration with the address `http://127.0.0.1:5401/mcp`. +It must be that address: the server listens on `127.0.0.1` only, takes no sign in (Home Assistant cannot +send one), and refuses any request whose `Host` is not `127.0.0.1` or `localhost`. So Home Assistant has to +run on the same machine as the bridge (for example the Home Assistant app on that computer). Never open a +router port to it. + +| Setting | What it does | +|---|---| +| `COUCH_MCP_HTTP=1` | Run as an HTTP server. Left out, the server is the stdio one above, unchanged. | +| `COUCH_MCP_PORT` | The port. 5401 if left out. | +| `COUCH_MCP_ALLOW_POWER_OFF=1` | Let the tools turn the TV off. Off by default. | +| `COUCH_MCP_ALLOW_SETTINGS=1` | Let the tools open the TV's own settings. Off by default. | +| `COUCH_MCP_WAIT` | Seconds to wait for the TV before answering "pending". 24 if left out. | + +The tool set differs from stdio on purpose: + +- Names start with `tv_` (`tv_play`, `tv_key`, `tv_now`). `tvs` is `tv_list`. Tools use the bridge's default TV; with more than one TV, pass a TV's id from `tv_list` as `tv` when the person names one. +- No `screenshot`: Home Assistant hands the model only text, so a picture would arrive as a wall of letters. `tv_ui` gives the screen as text. +- No `uninstall_app`. A voice assistant should not remove apps. +- Turning the TV off (`tv_power` with `off` or `toggle`, the `power` and `sleep` keys of `tv_key`, and `tv_off_after_episode`) is refused unless `COUCH_MCP_ALLOW_POWER_OFF=1`. Turning it on always works. +- `tv_key` takes only the keys its description names, not raw key names: every kind of TV has a raw name that turns it off (`KEYCODE_POWER`, `KEY_POWER`, `PowerOff`), so raw names are refused whatever the settings say. A key a household needs gets a name. +- `tv_launch` takes app ids and package names, not links: a link can open any screen inside any app. +- Opening the TV's own settings (`tv_launch` with `settings`, `bluetooth`, `network` or a settings app's package, and the `settings` key of `tv_key`) is refused unless `COUCH_MCP_ALLOW_SETTINGS=1`. It is a speed bump, not a wall: the arrow keys and OK still move around the TV, so a model that tries hard can reach Settings from the home screen. It stops a misheard "open settings" and the quick way in. +- Home Assistant stops a tool after 30 seconds. A tool that is not done in 24 answers `pending` and carries on in the background (installing an app, restarting an app). Ask `tv_now` a little later. + ## The tools for the TV home | Tool | What it does | diff --git a/tests/test_mcp_http.py b/tests/test_mcp_http.py new file mode 100644 index 00000000..160bc5a8 --- /dev/null +++ b/tests/test_mcp_http.py @@ -0,0 +1,244 @@ +"""The TV's MCP server in HTTP mode (COUCH_MCP_HTTP=1, for Home Assistant's MCP client), against a fake +bridge: the tool set (tv_ names, no screenshot, no uninstall), the pairing key reaching the bridge, +power off refused unless allowed, a slow tool answering "pending", and a foreign Host header refused. +Stdio mode keeps its own tool names. + + .venv/bin/python -m unittest tests/test_mcp_http.py +""" +import asyncio +import http.server +import json +import os +import socket +import subprocess +import sys +import tempfile +import threading +import time +import unittest +from unittest.mock import patch +import urllib.error +import urllib.request + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +sys.path.insert(0, os.path.join(ROOT, "bridge")) + +from mcp import ClientSession # noqa: E402 +from mcp.client.streamable_http import streamablehttp_client # noqa: E402 + +KEY = "test-key-mcp-http-0001" +SEEN = [] + + +class FakeBridge(http.server.BaseHTTPRequestHandler): + delay = 0 + done = [] # paths the fake has answered in full + + def log_message(self, *a): + pass + + def reply(self): + n = int(self.headers.get("Content-Length") or 0) + body = json.loads(self.rfile.read(n)) if n else None + SEEN.append((self.command, self.path, body, self.headers.get("Authorization"))) + time.sleep(self.delay) + FakeBridge.done.append(self.path) + out = json.dumps({"ok": True}).encode() + self.send_response(200) + self.send_header("Content-Length", str(len(out))) + self.end_headers() + self.wfile.write(out) + + do_GET = do_POST = reply + + +def free_port(): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +class HttpMode(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.bridge = http.server.ThreadingHTTPServer(("127.0.0.1", 0), FakeBridge) + threading.Thread(target=cls.bridge.serve_forever, daemon=True).start() + cls.log = tempfile.TemporaryFile() + cls.proc, cls.port = cls.start("1.5", cls.log) + cls.proc2, cls.port2 = cls.start("12", subprocess.DEVNULL) + cls.proc3, cls.port3 = cls.start("12", subprocess.DEVNULL, COUCH_MCP_ALLOW_POWER_OFF="1", COUCH_MCP_ALLOW_SETTINGS="1") + + @classmethod + def start(cls, wait, log, **extra): + port = free_port() + env = dict(os.environ, COUCH_MCP_HTTP="1", COUCH_MCP_PORT=str(port), COUCH_MCP_WAIT=wait, + BRIDGE_URL="http://127.0.0.1:%d" % cls.bridge.server_address[1], BRIDGE_KEY=KEY, + COUCH_CONFIG=os.path.join(HERE, "no-such-config.json")) + env.pop("COUCH_MCP_ALLOW_POWER_OFF", None) + env.pop("COUCH_MCP_ALLOW_SETTINGS", None) + env.update(extra) + proc = subprocess.Popen([sys.executable, os.path.join(ROOT, "bridge", "mcp_server.py")], env=env, + stdout=subprocess.DEVNULL, stderr=log) + for _ in range(100): + with socket.socket() as c: + if c.connect_ex(("127.0.0.1", port)) == 0: + return proc, port + time.sleep(0.1) + raise RuntimeError("the MCP server did not start") + + @classmethod + def tearDownClass(cls): + for p in (cls.proc, cls.proc2, cls.proc3): + p.terminate() + p.wait(timeout=10) + cls.bridge.shutdown() + + def setUp(self): + SEEN.clear() + FakeBridge.done.clear() + + def run_tools(self, work, port=None, **client): + async def go(): + async with streamablehttp_client("http://127.0.0.1:%d/mcp" % (port or self.port), **client) as (r, w, _): + async with ClientSession(r, w) as s: + await s.initialize() + return await work(s) + return asyncio.run(asyncio.wait_for(go(), 40)) # a silent stream must fail the test, not hang it + + def test_tool_set(self): + names = {t.name for t in self.run_tools(lambda s: s.list_tools()).tools} + self.assertTrue({"tv_play", "tv_list", "tv_key", "tv_now", "tv_ui", "tv_says"} <= names, names) + self.assertFalse({"tv_uninstall_app", "tv_screenshot", "uninstall_app", "screenshot"} & names) + self.assertTrue(all(n.startswith("tv_") for n in names), names) + + def test_key_reaches_the_bridge_with_the_key(self): + r = self.run_tools(lambda s: s.call_tool("tv_key", {"key": "home"})) + self.assertFalse(r.isError) + self.assertEqual([x for x in SEEN if x[1] == "/api/key"], [("POST", "/api/key", {"key": "home", "hold": False}, "Bearer " + KEY)]) + + def test_power_off_is_refused(self): + r = self.run_tools(lambda s: s.call_tool("tv_power", {"state": "off"})) + self.assertIn("switched off", r.content[0].text) + r = self.run_tools(lambda s: s.call_tool("tv_off_after_episode", {})) + self.assertIn("switched off", r.content[0].text) + for k in ("power", "sleep", "POWER", " SLEEP "): + r = self.run_tools(lambda s: s.call_tool("tv_key", {"key": k})) + self.assertIn("switched off", r.content[0].text) + # each TV maker's raw name for off (Android, Samsung, Roku, VIZIO, TiVo): no raw names at all + for k in ("KEYCODE_POWER", "keycode_sleep", "KEY_POWER", "PowerOff", "power_toggle", "1012"): + r = self.run_tools(lambda s: s.call_tool("tv_key", {"key": k})) + self.assertIn("Only the keys named", r.content[0].text) + r = self.run_tools(lambda s: s.call_tool("tv_power", {"state": "toggle"})) + self.assertIn("switched off", r.content[0].text) + self.assertEqual(SEEN, []) + + def test_launch_refuses_links(self): + for link in ("intent://#Intent;action=android.settings.SETTINGS;end", "https://example.com"): + r = self.run_tools(lambda s: s.call_tool("tv_launch", {"app": link})) + self.assertIn("Links can't be opened", r.content[0].text) + tools = {t.name: t for t in self.run_tools(lambda s: s.list_tools()).tools} + self.assertNotIn("by link", tools["tv_launch"].description) + self.assertEqual(SEEN, []) + for app in ("netflix", "com.netflix.ninja"): + self.run_tools(lambda s: s.call_tool("tv_launch", {"app": app})) + self.assertEqual([x[2] for x in SEEN], [{"app": "netflix"}, {"app": "com.netflix.ninja"}]) + + def test_allowing_power_off_allows_only_power_off(self): + for k in ("power", "sleep"): + self.run_tools(lambda s: s.call_tool("tv_key", {"key": k}), self.port3) + self.assertEqual([x[2]["key"] for x in SEEN], ["power", "sleep"]) + r = self.run_tools(lambda s: s.call_tool("tv_key", {"key": "KEY_POWER"}), self.port3) + self.assertIn("Only the keys named", r.content[0].text) + self.assertEqual(len(SEEN), 2) + + def test_settings_are_refused_unless_allowed(self): + for app in ("settings", "bluetooth", "network", "com.android.tv.settings", "com.amazon.tv.settings.v2", + "com.palm.app.settings", " settings "): + r = self.run_tools(lambda s: s.call_tool("tv_launch", {"app": app})) + self.assertIn("settings from here is switched off", r.content[0].text) + r = self.run_tools(lambda s: s.call_tool("tv_key", {"key": "Settings"})) + self.assertIn("settings from here is switched off", r.content[0].text) + self.assertEqual(SEEN, []) + self.run_tools(lambda s: s.call_tool("tv_launch", {"app": "settings"}), self.port3) + self.run_tools(lambda s: s.call_tool("tv_key", {"key": "settings"}), self.port3) + self.assertEqual([x[1] for x in SEEN], ["/api/launch", "/api/key"]) + + def test_power_on_works(self): + self.run_tools(lambda s: s.call_tool("tv_power", {"state": "on"})) + self.assertEqual(SEEN[0][:3], ("POST", "/api/power", {"state": "on"})) + + def test_slow_tool_answers_pending(self): + FakeBridge.delay = 4 # the server waits COUCH_MCP_WAIT=1.5 s, then answers pending + try: + t0 = time.time() + r = self.run_tools(lambda s: s.call_tool("tv_now", {})) + took = time.time() - t0 + finally: + FakeBridge.delay = 0 + self.assertLess(took, 3.5) + self.assertTrue(json.loads(r.content[0].text)["pending"]) + time.sleep(3) # the request carries on in the background and the bridge finishes it + self.assertIn(("GET", "/api/now"), [x[:2] for x in SEEN]) + self.assertIn("/api/now", FakeBridge.done) + + def test_a_slow_answer_keeps_the_stream_alive(self): + # Home Assistant's client drops a response stream that is silent for 5 s + FakeBridge.delay = 8 + try: + r = self.run_tools(lambda s: s.call_tool("tv_now", {}), self.port2, timeout=5, sse_read_timeout=5) + finally: + FakeBridge.delay = 0 + self.assertFalse(r.isError) + self.assertEqual(json.loads(r.content[0].text), {"ok": True}) + + def test_server_name_and_quiet_log(self): + async def work(s): + return (await s.initialize()).serverInfo.name + self.assertEqual(self.run_tools(work), "Couch TV") + self.run_tools(lambda s: s.list_tools()) + time.sleep(0.5) + self.log.seek(0) + self.assertNotIn(b"ClosedResourceError", self.log.read()) + + def test_a_client_that_asks_for_the_standalone_stream_is_handled(self): + req = urllib.request.Request("http://127.0.0.1:%d/mcp" % self.port, headers={"Accept": "text/event-stream"}) + try: + with urllib.request.urlopen(req, timeout=5) as r: + self.assertEqual(r.status, 200) # an idle stream, closed when the client leaves + except urllib.error.HTTPError as e: + e.close() + self.assertEqual(e.code, 405) + self.assertEqual(len(self.run_tools(lambda s: s.list_tools()).tools) > 5, True) # and the server still answers + + def test_foreign_host_is_refused(self): + req = urllib.request.Request("http://127.0.0.1:%d/mcp" % self.port, method="POST", data=b"{}", + headers={"Host": "evil.example", "Content-Type": "application/json", + "Accept": "application/json, text/event-stream"}) + with self.assertRaises(urllib.error.HTTPError) as e: + urllib.request.urlopen(req, timeout=5) + e.exception.close() + self.assertEqual(e.exception.code, 421) + + +class StdioMode(unittest.TestCase): + def test_names_are_unchanged(self): + import mcp_server + self.assertFalse(mcp_server.HTTP) + names = {t.name for t in mcp_server.mcp._tool_manager.list_tools()} + for n in ("play", "find", "key", "now", "tvs", "screenshot", "uninstall_app", "power", "ui", "list_widgets", "tv_says"): + self.assertIn(n, names) + self.assertFalse([n for n in names if n.startswith("tv_") and n != "tv_says"]) + + def test_power_off_still_reaches_the_bridge(self): + import mcp_server + seen = [] + with patch.object(mcp_server, "call", lambda *a, **k: seen.append(a) or {"ok": True}): + mcp_server.power("off") + mcp_server.key("power") + mcp_server.launch("intent://x#Intent;end") + self.assertEqual([a[1] for a in seen], ["/api/power", "/api/key", "/api/launch"]) + + +if __name__ == "__main__": + unittest.main()