From 41ca7b44ed3475ae5f84e6f6b2efd3b8fadba3f5 Mon Sep 17 00:00:00 2001 From: Vash Patel <5833901+vpatel9202@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:51:19 -0600 Subject: [PATCH 1/6] MCP server: an HTTP mode for Home Assistant (COUCH_MCP_HTTP=1) Same tools on a second FastMCP on 127.0.0.1, with a tv_ prefix, no screenshot or uninstall, power off only when allowed, and a tool that takes over 24 s answers pending and finishes in the background (Home Assistant gives a tool 30 s). The instructions and docstrings no longer name a room or a city. Co-Authored-By: Claude Opus 5.5 --- bridge/mcp_server.py | 97 +++++++++++++++++++++++++-- docs/AI-AGENT.md | 30 +++++++++ tests/test_mcp_http.py | 148 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 270 insertions(+), 5 deletions(-) create mode 100644 tests/test_mcp_http.py diff --git a/bridge/mcp_server.py b/bridge/mcp_server.py index 29d63ab8..2f777035 100644 --- a/bridge/mcp_server.py +++ b/bridge/mcp_server.py @@ -1,19 +1,30 @@ -"""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 +HTTP = os.environ.get("COUCH_MCP_HTTP") == "1" +ALLOW_POWER_OFF = os.environ.get("COUCH_MCP_ALLOW_POWER_OFF") == "1" # HTTP only +WAIT = float(os.environ.get("COUCH_MCP_WAIT") or 24) # HTTP only: Home Assistant gives a tool 30 s in all 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 +32,17 @@ 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)."} + + def call(method, path, payload=None, raw=False, tv=None, timeout=60, headers_out=None): tv = tv or TV_ID if tv: @@ -131,6 +146,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 +160,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 +277,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 +433,73 @@ 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 WAIT 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} +HTTP_TV_NOTE = (" tv: the TV's id from tv_list. Pass it when the home has more than one TV and the person" + " named one; leave it out for the default TV.") +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. There can be more than one TV (tv_list).") + + +def _within_wait(fn): + """Run fn in a thread; if it is not done in WAIT seconds, answer PENDING and let it finish alone.""" + @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() + try: + out = await asyncio.wait_for(asyncio.shield(done), WAIT) + except asyncio.TimeoutError: + return PENDING + if isinstance(out, Exception): + raise out + return out + return run + + +def http_server(port): + srv = FastMCP("tv", instructions=HTTP_INSTRUCTIONS, host="127.0.0.1", port=port, 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 + 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), 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..18fc44e8 100644 --- a/docs/AI-AGENT.md +++ b/docs/AI-AGENT.md @@ -58,6 +58,36 @@ 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://:5401/mcp`. +It listens on `127.0.0.1` only and takes no sign in, because Home Assistant cannot send one. So Home +Assistant has to run on that same computer, or you put your own private link in front of it (an SSH tunnel, +for example). Never open a router port to it. It also refuses a request whose `Host` is not `127.0.0.1` or +`localhost`. + +| 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_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`: with more than one TV, pass a TV's id from it as `tv`. +- 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`, and `tv_off_after_episode`) is refused unless `COUCH_MCP_ALLOW_POWER_OFF=1`. Turning it on always works. +- 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..e9e0600a --- /dev/null +++ b/tests/test_mcp_http.py @@ -0,0 +1,148 @@ +"""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 threading +import time +import unittest +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 + + 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) + 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.port = free_port() + env = dict(os.environ, COUCH_MCP_HTTP="1", COUCH_MCP_PORT=str(cls.port), COUCH_MCP_WAIT="1.5", + 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) + cls.proc = subprocess.Popen([sys.executable, os.path.join(ROOT, "bridge", "mcp_server.py")], env=env, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + for _ in range(100): + with socket.socket() as s: + if s.connect_ex(("127.0.0.1", cls.port)) == 0: + return + time.sleep(0.1) + raise RuntimeError("the MCP server did not start") + + @classmethod + def tearDownClass(cls): + cls.proc.terminate() + cls.proc.wait(timeout=10) + cls.bridge.shutdown() + + def setUp(self): + SEEN.clear() + + def run_tools(self, work): + async def go(): + async with streamablehttp_client("http://127.0.0.1:%d/mcp" % self.port) as (r, w, _): + async with ClientSession(r, w) as s: + await s.initialize() + return await work(s) + return asyncio.run(go()) + + 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) + self.assertEqual(SEEN, []) + + 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"]) + + 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"]) + + +if __name__ == "__main__": + unittest.main() From a43aaa9ab23a1e80a5dbd7926e730e6097a71a7c Mon Sep 17 00:00:00 2001 From: Vash Patel <5833901+vpatel9202@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:01:25 -0600 Subject: [PATCH 2/6] MCP HTTP mode: refuse the power and sleep keys, never HTTP in an ask child, wait parsed only in HTTP, docs say 127.0.0.1 Co-Authored-By: Claude Opus 5.5 --- bridge/mcp_server.py | 19 +++++++++++-------- docs/AI-AGENT.md | 14 +++++++------- tests/test_mcp_http.py | 20 ++++++++++++++++++++ 3 files changed, 38 insertions(+), 15 deletions(-) diff --git a/bridge/mcp_server.py b/bridge/mcp_server.py index 2f777035..d78ab7b0 100644 --- a/bridge/mcp_server.py +++ b/bridge/mcp_server.py @@ -22,9 +22,9 @@ 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 -HTTP = os.environ.get("COUCH_MCP_HTTP") == "1" +# 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 -WAIT = float(os.environ.get("COUCH_MCP_WAIT") or 24) # HTTP only: Home Assistant gives a tool 30 s in all 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 @@ -114,6 +114,8 @@ 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.""" + if HTTP and key.strip().lower() in ("power", "sleep") and not ALLOW_POWER_OFF: # these turn the TV off + return NO_POWER_OFF return call("POST", "/api/key", {"key": key, "hold": hold}, tv=tv) @@ -435,7 +437,7 @@ def tv_says(tv: str | None = None) -> dict: # ---- 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 WAIT seconds answers "pending" and finishes in the background; no screenshot and no uninstall; names +# 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"} @@ -443,17 +445,18 @@ def tv_says(tv: str | None = None) -> dict: "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} -HTTP_TV_NOTE = (" tv: the TV's id from tv_list. Pass it when the home has more than one TV and the person" - " named one; leave it out for the default TV.") +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. There can be more than one TV (tv_list).") + "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): - """Run fn in a thread; if it is not done in WAIT seconds, answer PENDING and let it finish alone.""" + """Run fn in a thread; if it is not done in COUCH_MCP_WAIT seconds, answer PENDING and let it finish alone.""" @functools.wraps(fn) async def run(*a, **k): loop = asyncio.get_running_loop() @@ -470,7 +473,7 @@ def work(): pass threading.Thread(target=work, daemon=True).start() try: - out = await asyncio.wait_for(asyncio.shield(done), WAIT) + out = await asyncio.wait_for(asyncio.shield(done), float(os.environ.get("COUCH_MCP_WAIT") or 24)) except asyncio.TimeoutError: return PENDING if isinstance(out, Exception): diff --git a/docs/AI-AGENT.md b/docs/AI-AGENT.md index 18fc44e8..61ead51b 100644 --- a/docs/AI-AGENT.md +++ b/docs/AI-AGENT.md @@ -67,11 +67,11 @@ computer that runs the bridge: 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://:5401/mcp`. -It listens on `127.0.0.1` only and takes no sign in, because Home Assistant cannot send one. So Home -Assistant has to run on that same computer, or you put your own private link in front of it (an SSH tunnel, -for example). Never open a router port to it. It also refuses a request whose `Host` is not `127.0.0.1` or -`localhost`. +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 | |---|---| @@ -82,10 +82,10 @@ for example). Never open a router port to it. It also refuses a request whose `H The tool set differs from stdio on purpose: -- Names start with `tv_` (`tv_play`, `tv_key`, `tv_now`). `tvs` is `tv_list`: with more than one TV, pass a TV's id from it as `tv`. +- 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`, and `tv_off_after_episode`) is refused unless `COUCH_MCP_ALLOW_POWER_OFF=1`. Turning it on always works. +- 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. - 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 diff --git a/tests/test_mcp_http.py b/tests/test_mcp_http.py index e9e0600a..5d5a3c2e 100644 --- a/tests/test_mcp_http.py +++ b/tests/test_mcp_http.py @@ -15,6 +15,7 @@ import threading import time import unittest +from unittest.mock import patch import urllib.error import urllib.request @@ -31,6 +32,7 @@ class FakeBridge(http.server.BaseHTTPRequestHandler): delay = 0 + done = [] # paths the fake has answered in full def log_message(self, *a): pass @@ -40,6 +42,7 @@ def reply(self): 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))) @@ -82,6 +85,7 @@ def tearDownClass(cls): def setUp(self): SEEN.clear() + FakeBridge.done.clear() def run_tools(self, work): async def go(): @@ -107,6 +111,11 @@ def test_power_off_is_refused(self): 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"): + r = self.run_tools(lambda s: s.call_tool("tv_key", {"key": k})) + self.assertIn("switched off", 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_power_on_works(self): @@ -123,6 +132,9 @@ def test_slow_tool_answers_pending(self): 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_foreign_host_is_refused(self): req = urllib.request.Request("http://127.0.0.1:%d/mcp" % self.port, method="POST", data=b"{}", @@ -143,6 +155,14 @@ def test_names_are_unchanged(self): 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") + self.assertEqual([a[1] for a in seen], ["/api/power", "/api/key"]) + if __name__ == "__main__": unittest.main() From 266a5923193aef1a5ca65c8b743372383f17c0e6 Mon Sep 17 00:00:00 2001 From: Vash Patel <5833901+vpatel9202@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:40:54 -0600 Subject: [PATCH 3/6] MCP HTTP mode: keep the response stream alive while a tool works, name it Couch TV, stateless Home Assistant's client drops a response stream that is silent for 5 s, so a slow tool (tv_play, about 15 s) looked like an error. A log line now goes down the request's own stream every 2 s. Stateless, because Home Assistant opens a new session for every call: no session to close, so no standalone SSE writer traceback. Co-Authored-By: Claude Opus 5.5 --- bridge/mcp_server.py | 31 +++++++++++++++------ tests/test_mcp_http.py | 61 +++++++++++++++++++++++++++++++++--------- 2 files changed, 72 insertions(+), 20 deletions(-) diff --git a/bridge/mcp_server.py b/bridge/mcp_server.py index d78ab7b0..b4990bca 100644 --- a/bridge/mcp_server.py +++ b/bridge/mcp_server.py @@ -455,8 +455,10 @@ def tv_says(tv: str | None = None) -> dict: "pass its id (from tv_list) as tv.") -def _within_wait(fn): - """Run fn in a thread; if it is not done in COUCH_MCP_WAIT seconds, answer PENDING and let it finish alone.""" +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() @@ -472,10 +474,20 @@ def work(): except RuntimeError: # the server has stopped pass threading.Thread(target=work, daemon=True).start() - try: - out = await asyncio.wait_for(asyncio.shield(done), float(os.environ.get("COUCH_MCP_WAIT") or 24)) - except asyncio.TimeoutError: - return PENDING + 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 @@ -483,7 +495,10 @@ def work(): def http_server(port): - srv = FastMCP("tv", instructions=HTTP_INSTRUCTIONS, host="127.0.0.1", port=port, transport_security=TransportSecuritySettings( + # 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() @@ -496,7 +511,7 @@ def http_server(port): 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), name=names[t.name], description=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 diff --git a/tests/test_mcp_http.py b/tests/test_mcp_http.py index 5d5a3c2e..150b697e 100644 --- a/tests/test_mcp_http.py +++ b/tests/test_mcp_http.py @@ -12,6 +12,7 @@ import socket import subprocess import sys +import tempfile import threading import time import unittest @@ -63,37 +64,44 @@ class HttpMode(unittest.TestCase): 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.port = free_port() - env = dict(os.environ, COUCH_MCP_HTTP="1", COUCH_MCP_PORT=str(cls.port), COUCH_MCP_WAIT="1.5", + cls.log = tempfile.TemporaryFile() + cls.proc, cls.port = cls.start("1.5", cls.log) + cls.proc2, cls.port2 = cls.start("12", subprocess.DEVNULL) + + @classmethod + def start(cls, wait, log): + 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) - cls.proc = subprocess.Popen([sys.executable, os.path.join(ROOT, "bridge", "mcp_server.py")], env=env, - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + 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 s: - if s.connect_ex(("127.0.0.1", cls.port)) == 0: - return + 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): - cls.proc.terminate() - cls.proc.wait(timeout=10) + for p in (cls.proc, cls.proc2): + p.terminate() + p.wait(timeout=10) cls.bridge.shutdown() def setUp(self): SEEN.clear() FakeBridge.done.clear() - def run_tools(self, work): + def run_tools(self, work, port=None, **client): async def go(): - async with streamablehttp_client("http://127.0.0.1:%d/mcp" % self.port) as (r, w, _): + 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(go()) + 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} @@ -136,6 +144,35 @@ def test_slow_tool_answers_pending(self): 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", From 7591f4e90e8329f71901b5d4c115b830363fbfda Mon Sep 17 00:00:00 2001 From: Vash Patel <5833901+vpatel9202@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:57:52 -0600 Subject: [PATCH 4/6] MCP HTTP mode: tv_key takes only the named keys (every TV maker has a raw name for off: KEYCODE_POWER, KEY_POWER, PowerOff, power_toggle), tv_launch takes no links Review on Seagey/couch-tv#352. Raw key names still work with COUCH_MCP_ALLOW_POWER_OFF=1, and stdio mode is unchanged. Co-Authored-By: Claude Opus 5.5 --- bridge/mcp_server.py | 20 ++++++++++++++++---- docs/AI-AGENT.md | 2 ++ tests/test_mcp_http.py | 20 ++++++++++++++++++-- 3 files changed, 36 insertions(+), 6 deletions(-) diff --git a/bridge/mcp_server.py b/bridge/mcp_server.py index b4990bca..8a78cd64 100644 --- a/bridge/mcp_server.py +++ b/bridge/mcp_server.py @@ -41,6 +41,12 @@ 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)) + "."} +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): @@ -114,8 +120,10 @@ 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.""" - if HTTP and key.strip().lower() in ("power", "sleep") and not ALLOW_POWER_OFF: # these turn the TV off - return NO_POWER_OFF + # 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 and not ALLOW_POWER_OFF and key.strip().lower() not in HTTP_KEYS: + return NO_POWER_OFF if key.strip().lower() in ("power", "sleep") else NO_RAW_KEY return call("POST", "/api/key", {"key": key, "hold": hold}, tv=tv) @@ -130,6 +138,8 @@ 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 return call("POST", "/api/launch", {"app": app}, tv=tv) @@ -444,7 +454,9 @@ def tv_says(tv: str | None = None) -> dict: 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} +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 = ( @@ -507,7 +519,7 @@ def http_server(port): for t in tools: if t.name in HTTP_DROP: continue - text = t.description + HTTP_NOTES.get(t.name, "") + (HTTP_TV_NOTE if "tv" in t.parameters["properties"] else "") + 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) diff --git a/docs/AI-AGENT.md b/docs/AI-AGENT.md index 61ead51b..67c8bc64 100644 --- a/docs/AI-AGENT.md +++ b/docs/AI-AGENT.md @@ -86,6 +86,8 @@ The tool set differs from stdio on purpose: - 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`). `COUCH_MCP_ALLOW_POWER_OFF=1` lets raw names through too. +- `tv_launch` takes app ids and package names, not links: a link can open any screen inside any app. The TV's Settings can still be opened (`settings`). - 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 diff --git a/tests/test_mcp_http.py b/tests/test_mcp_http.py index 150b697e..7341e08d 100644 --- a/tests/test_mcp_http.py +++ b/tests/test_mcp_http.py @@ -119,13 +119,28 @@ def test_power_off_is_refused(self): 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"): + 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_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"})) @@ -198,7 +213,8 @@ def test_power_off_still_reaches_the_bridge(self): with patch.object(mcp_server, "call", lambda *a, **k: seen.append(a) or {"ok": True}): mcp_server.power("off") mcp_server.key("power") - self.assertEqual([a[1] for a in seen], ["/api/power", "/api/key"]) + mcp_server.launch("intent://x#Intent;end") + self.assertEqual([a[1] for a in seen], ["/api/power", "/api/key", "/api/launch"]) if __name__ == "__main__": From 191fdbdff9734dbe51e868a88d8b26b93ff5583d Mon Sep 17 00:00:00 2001 From: Vash Patel <5833901+vpatel9202@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:18:58 -0600 Subject: [PATCH 5/6] MCP HTTP mode: COUCH_MCP_ALLOW_POWER_OFF lets only the power and sleep keys through, raw key names stay refused Co-Authored-By: Claude Opus 5.5 --- bridge/mcp_server.py | 9 +++++++-- docs/AI-AGENT.md | 2 +- tests/test_mcp_http.py | 14 ++++++++++++-- 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/bridge/mcp_server.py b/bridge/mcp_server.py index 8a78cd64..be6c7596 100644 --- a/bridge/mcp_server.py +++ b/bridge/mcp_server.py @@ -122,8 +122,13 @@ def key(key: str, hold: bool = False, tv: str | None = None) -> dict: 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 and not ALLOW_POWER_OFF and key.strip().lower() not in HTTP_KEYS: - return NO_POWER_OFF if key.strip().lower() in ("power", "sleep") else NO_RAW_KEY + if HTTP: + k = key.strip().lower() + if k in ("power", "sleep"): + if not ALLOW_POWER_OFF: + return NO_POWER_OFF + elif k not in HTTP_KEYS: + return NO_RAW_KEY return call("POST", "/api/key", {"key": key, "hold": hold}, tv=tv) diff --git a/docs/AI-AGENT.md b/docs/AI-AGENT.md index 67c8bc64..910ae38d 100644 --- a/docs/AI-AGENT.md +++ b/docs/AI-AGENT.md @@ -86,7 +86,7 @@ The tool set differs from stdio on purpose: - 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`). `COUCH_MCP_ALLOW_POWER_OFF=1` lets raw names through too. +- `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. The TV's Settings can still be opened (`settings`). - 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. diff --git a/tests/test_mcp_http.py b/tests/test_mcp_http.py index 7341e08d..e40d42d1 100644 --- a/tests/test_mcp_http.py +++ b/tests/test_mcp_http.py @@ -67,14 +67,16 @@ def setUpClass(cls): 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") @classmethod - def start(cls, wait, log): + 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.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): @@ -86,7 +88,7 @@ def start(cls, wait, log): @classmethod def tearDownClass(cls): - for p in (cls.proc, cls.proc2): + for p in (cls.proc, cls.proc2, cls.proc3): p.terminate() p.wait(timeout=10) cls.bridge.shutdown() @@ -141,6 +143,14 @@ def test_launch_refuses_links(self): 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_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"})) From 5cb2331874bd9eba2772c01f8089edca49469cb2 Mon Sep 17 00:00:00 2001 From: Vash Patel <5833901+vpatel9202@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:26:56 -0600 Subject: [PATCH 6/6] MCP HTTP mode: the TV's own settings are refused unless COUCH_MCP_ALLOW_SETTINGS=1 (the settings, bluetooth and network ids, each kind of TV's settings app, the settings key) Co-Authored-By: Claude Opus 5.5 --- bridge/mcp_server.py | 17 +++++++++++++++++ docs/AI-AGENT.md | 4 +++- tests/test_mcp_http.py | 15 ++++++++++++++- 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/bridge/mcp_server.py b/bridge/mcp_server.py index be6c7596..59a80d97 100644 --- a/bridge/mcp_server.py +++ b/bridge/mcp_server.py @@ -25,6 +25,7 @@ # 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 @@ -45,6 +46,17 @@ 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."} @@ -127,6 +139,9 @@ def key(key: str, hold: bool = False, tv: str | None = None) -> dict: 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) @@ -145,6 +160,8 @@ def launch(app: str, tv: str | None = None) -> dict: 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) diff --git a/docs/AI-AGENT.md b/docs/AI-AGENT.md index 910ae38d..f0b2fdfa 100644 --- a/docs/AI-AGENT.md +++ b/docs/AI-AGENT.md @@ -78,6 +78,7 @@ router port to it. | `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: @@ -87,7 +88,8 @@ The tool set differs from stdio on purpose: - 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. The TV's Settings can still be opened (`settings`). +- `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 diff --git a/tests/test_mcp_http.py b/tests/test_mcp_http.py index e40d42d1..160bc5a8 100644 --- a/tests/test_mcp_http.py +++ b/tests/test_mcp_http.py @@ -67,7 +67,7 @@ def setUpClass(cls): 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") + 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): @@ -76,6 +76,7 @@ def start(cls, wait, log, **extra): 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) @@ -151,6 +152,18 @@ def test_allowing_power_off_allows_only_power_off(self): 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"}))