Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
149 changes: 144 additions & 5 deletions bridge/mcp_server.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,66 @@
"""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
except (Exception, SystemExit):
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:
Expand Down Expand Up @@ -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)


Expand All @@ -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)


Expand All @@ -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)


Expand All @@ -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")
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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()
34 changes: 34 additions & 0 deletions docs/AI-AGENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
Loading
Loading