tplink-modem-mcp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,145 @@
1
+ Metadata-Version: 2.4
2
+ Name: tplink-modem-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server for TP-Link routers and ISP modems: devices, Wi-Fi signal, logs, presence history
5
+ Keywords: mcp,mcp-server,tp-link,router,modem,archer,wifi,home-network
6
+ Author: Yakup Emre Yerli
7
+ License-Expression: GPL-3.0-or-later
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Environment :: Console
10
+ Classifier: Intended Audience :: End Users/Desktop
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: System :: Networking :: Monitoring
14
+ Requires-Dist: mcp[cli]>=2.3.0
15
+ Requires-Dist: tplinkrouterc6u>=5.40.0
16
+ Requires-Python: >=3.12
17
+ Project-URL: Homepage, https://github.com/YakupEmreYerli/tplink-modem-mcp
18
+ Project-URL: Issues, https://github.com/YakupEmreYerli/tplink-modem-mcp/issues
19
+ Description-Content-Type: text/markdown
20
+
21
+ # tplink-modem-mcp
22
+
23
+ An [MCP](https://modelcontextprotocol.io) server that lets an AI assistant read and manage a TP-Link router or an
24
+ ISP-supplied TP-Link modem on your local network: who is connected, how strong their Wi-Fi signal is, what the
25
+ router logged, and when each device joined or dropped off.
26
+
27
+ [![CI](https://github.com/YakupEmreYerli/tplink-modem-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/YakupEmreYerli/tplink-modem-mcp/actions/workflows/ci.yml)
28
+ [![PyPI](https://img.shields.io/pypi/v/tplink-modem-mcp)](https://pypi.org/project/tplink-modem-mcp/)
29
+ [![Python](https://img.shields.io/pypi/pyversions/tplink-modem-mcp)](https://pypi.org/project/tplink-modem-mcp/)
30
+ [![License: GPL-3.0](https://img.shields.io/badge/license-GPL--3.0-blue)](LICENSE)
31
+
32
+ ![tplink-modem-mcp](assets/brand/banner.en.png)
33
+
34
+ [Türkçe](README.tr.md)
35
+
36
+ It builds on [tplinkrouterc6u](https://github.com/AlexandrErohin/TP-Link-Archer-C6U), so every model that library
37
+ supports works. On top of it, it adds a client for older ISP firmwares that library does not detect, for example
38
+ the **Archer C5v** that Türk Telekom ships, whose web UI logs in through `/cgi/login?UserName=…&Passwd=…`.
39
+
40
+ Ask things like:
41
+
42
+ - "Which devices are on the Wi-Fi right now, and which one has the weakest signal?"
43
+ - "The TV keeps dropping off. When did it leave and come back today?"
44
+ - "Show me the router's DHCP errors from the last hour."
45
+
46
+ ## Tools
47
+
48
+ | Tool | What it does |
49
+ | --- | --- |
50
+ | `router_status` | Model, firmware, internet connection (status, external IP, uptime), LAN address, Wi-Fi networks, devices online |
51
+ | `list_clients` | Devices with hostname, IP, MAC, wired or Wi-Fi band and SSID, signal (dBm) and link rate |
52
+ | `find_client` | Search devices by name, IP or MAC |
53
+ | `client_history` | Join / leave / IP-change events recorded by this server (routers keep no such log) |
54
+ | `wifi_networks` | Every SSID with band, channel and on/off |
55
+ | `router_logs` | System log, filtered by module, text or severity |
56
+ | `dhcp_leases`, `dhcp_reservations` | DHCP leases and fixed addresses |
57
+ | `ipv6_status` | WAN / LAN IPv6 |
58
+ | `reboot_router` | Reboots, only with `confirm=true` |
59
+
60
+ Everything except `reboot_router` only reads.
61
+
62
+ ## Install
63
+
64
+ You need [uv](https://docs.astral.sh/uv/) and the router's web admin password. The server has to run on a machine
65
+ in the same network as the router.
66
+
67
+ Claude Code:
68
+
69
+ ```sh
70
+ claude mcp add tplink-modem -e TPLINK_PASSWORD='<router password>' -- uvx tplink-modem-mcp
71
+ ```
72
+
73
+ Claude Desktop, Cursor and other clients that take a JSON config:
74
+
75
+ ```json
76
+ {
77
+ "mcpServers": {
78
+ "tplink-modem": {
79
+ "command": "uvx",
80
+ "args": ["tplink-modem-mcp"],
81
+ "env": { "TPLINK_PASSWORD": "<router password>" }
82
+ }
83
+ }
84
+ }
85
+ ```
86
+
87
+ From a clone instead of PyPI: `uv --directory /path/to/tplink-modem-mcp run tplink-modem-mcp`.
88
+
89
+ ## Settings
90
+
91
+ | Variable | Default | |
92
+ | --- | --- | --- |
93
+ | `TPLINK_PASSWORD` | (required) | web admin password |
94
+ | `TPLINK_HOST` | `http://192.168.1.1` | router address |
95
+ | `TPLINK_USERNAME` | `admin` | |
96
+ | `TPLINK_CLIENT` | auto | `legacy`, or a tplinkrouterc6u class name such as `TPLinkMRClient` |
97
+ | `TPLINK_TIMEOUT` | `20` | seconds per request to the router |
98
+ | `TPLINK_PRESENCE_INTERVAL` | `60` | seconds between presence samples while the server runs; `0` turns it off |
99
+ | `TPLINK_STATE_DIR` | `$XDG_STATE_HOME/tplink-modem-mcp` | where the presence history is kept |
100
+ | `TPLINK_LOG` | `WARNING` | log level, `DEBUG` shows every router call |
101
+
102
+ TP-Link routers allow one admin session at a time. Calls go through a single shared session, and the legacy
103
+ client keeps its login for two minutes, so the web UI may ask you to take over the session while the server is in
104
+ use.
105
+
106
+ ## Presence history
107
+
108
+ Routers do not remember when a device came and went, so the server samples the client list once a minute and
109
+ writes join, leave and IP-change events to `presence.jsonl` in the state folder. It only samples while it runs.
110
+
111
+ For a history around the clock, run `tplink-modem-mcp sample` every minute from a timer on a machine that stays
112
+ on, and start the MCP server with `TPLINK_PRESENCE_INTERVAL=0` so only the timer writes:
113
+
114
+ ```sh
115
+ * * * * * TPLINK_PASSWORD=... uvx tplink-modem-mcp sample
116
+ ```
117
+
118
+ ## Tested on
119
+
120
+ - Archer C5v v1, firmware v1.8 (Türk Telekom), with the legacy client.
121
+
122
+ Models tplinkrouterc6u supports should work through it. If you try another model, please
123
+ [open a model report](https://github.com/YakupEmreYerli/tplink-modem-mcp/issues/new?template=model-report.yml),
124
+ whether it works or not.
125
+
126
+ ## Security
127
+
128
+ The password stays in an environment variable and is only sent to the router. Read tools never change anything;
129
+ `reboot_router` does nothing unless it is called with `confirm=true`, and the server's instructions tell the
130
+ assistant to ask you first. To report a vulnerability, see [SECURITY.md](SECURITY.md).
131
+
132
+ ## Contributing
133
+
134
+ See [CONTRIBUTING.md](CONTRIBUTING.md).
135
+
136
+ ## Credits
137
+
138
+ - [tplinkrouterc6u](https://github.com/AlexandrErohin/TP-Link-Archer-C6U) by Alex Erohin (GPL-3.0), which does
139
+ most of the talking to the router; the legacy client extends its MR200 client.
140
+ - [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) (MIT).
141
+ - Fonts in the brand kit: [Geist](https://vercel.com/font) (SIL OFL 1.1).
142
+
143
+ ## License
144
+
145
+ [GPL-3.0-or-later](LICENSE), because the server extends tplinkrouterc6u, which is GPL-3.0.
@@ -0,0 +1,125 @@
1
+ # tplink-modem-mcp
2
+
3
+ An [MCP](https://modelcontextprotocol.io) server that lets an AI assistant read and manage a TP-Link router or an
4
+ ISP-supplied TP-Link modem on your local network: who is connected, how strong their Wi-Fi signal is, what the
5
+ router logged, and when each device joined or dropped off.
6
+
7
+ [![CI](https://github.com/YakupEmreYerli/tplink-modem-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/YakupEmreYerli/tplink-modem-mcp/actions/workflows/ci.yml)
8
+ [![PyPI](https://img.shields.io/pypi/v/tplink-modem-mcp)](https://pypi.org/project/tplink-modem-mcp/)
9
+ [![Python](https://img.shields.io/pypi/pyversions/tplink-modem-mcp)](https://pypi.org/project/tplink-modem-mcp/)
10
+ [![License: GPL-3.0](https://img.shields.io/badge/license-GPL--3.0-blue)](LICENSE)
11
+
12
+ ![tplink-modem-mcp](assets/brand/banner.en.png)
13
+
14
+ [Türkçe](README.tr.md)
15
+
16
+ It builds on [tplinkrouterc6u](https://github.com/AlexandrErohin/TP-Link-Archer-C6U), so every model that library
17
+ supports works. On top of it, it adds a client for older ISP firmwares that library does not detect, for example
18
+ the **Archer C5v** that Türk Telekom ships, whose web UI logs in through `/cgi/login?UserName=…&Passwd=…`.
19
+
20
+ Ask things like:
21
+
22
+ - "Which devices are on the Wi-Fi right now, and which one has the weakest signal?"
23
+ - "The TV keeps dropping off. When did it leave and come back today?"
24
+ - "Show me the router's DHCP errors from the last hour."
25
+
26
+ ## Tools
27
+
28
+ | Tool | What it does |
29
+ | --- | --- |
30
+ | `router_status` | Model, firmware, internet connection (status, external IP, uptime), LAN address, Wi-Fi networks, devices online |
31
+ | `list_clients` | Devices with hostname, IP, MAC, wired or Wi-Fi band and SSID, signal (dBm) and link rate |
32
+ | `find_client` | Search devices by name, IP or MAC |
33
+ | `client_history` | Join / leave / IP-change events recorded by this server (routers keep no such log) |
34
+ | `wifi_networks` | Every SSID with band, channel and on/off |
35
+ | `router_logs` | System log, filtered by module, text or severity |
36
+ | `dhcp_leases`, `dhcp_reservations` | DHCP leases and fixed addresses |
37
+ | `ipv6_status` | WAN / LAN IPv6 |
38
+ | `reboot_router` | Reboots, only with `confirm=true` |
39
+
40
+ Everything except `reboot_router` only reads.
41
+
42
+ ## Install
43
+
44
+ You need [uv](https://docs.astral.sh/uv/) and the router's web admin password. The server has to run on a machine
45
+ in the same network as the router.
46
+
47
+ Claude Code:
48
+
49
+ ```sh
50
+ claude mcp add tplink-modem -e TPLINK_PASSWORD='<router password>' -- uvx tplink-modem-mcp
51
+ ```
52
+
53
+ Claude Desktop, Cursor and other clients that take a JSON config:
54
+
55
+ ```json
56
+ {
57
+ "mcpServers": {
58
+ "tplink-modem": {
59
+ "command": "uvx",
60
+ "args": ["tplink-modem-mcp"],
61
+ "env": { "TPLINK_PASSWORD": "<router password>" }
62
+ }
63
+ }
64
+ }
65
+ ```
66
+
67
+ From a clone instead of PyPI: `uv --directory /path/to/tplink-modem-mcp run tplink-modem-mcp`.
68
+
69
+ ## Settings
70
+
71
+ | Variable | Default | |
72
+ | --- | --- | --- |
73
+ | `TPLINK_PASSWORD` | (required) | web admin password |
74
+ | `TPLINK_HOST` | `http://192.168.1.1` | router address |
75
+ | `TPLINK_USERNAME` | `admin` | |
76
+ | `TPLINK_CLIENT` | auto | `legacy`, or a tplinkrouterc6u class name such as `TPLinkMRClient` |
77
+ | `TPLINK_TIMEOUT` | `20` | seconds per request to the router |
78
+ | `TPLINK_PRESENCE_INTERVAL` | `60` | seconds between presence samples while the server runs; `0` turns it off |
79
+ | `TPLINK_STATE_DIR` | `$XDG_STATE_HOME/tplink-modem-mcp` | where the presence history is kept |
80
+ | `TPLINK_LOG` | `WARNING` | log level, `DEBUG` shows every router call |
81
+
82
+ TP-Link routers allow one admin session at a time. Calls go through a single shared session, and the legacy
83
+ client keeps its login for two minutes, so the web UI may ask you to take over the session while the server is in
84
+ use.
85
+
86
+ ## Presence history
87
+
88
+ Routers do not remember when a device came and went, so the server samples the client list once a minute and
89
+ writes join, leave and IP-change events to `presence.jsonl` in the state folder. It only samples while it runs.
90
+
91
+ For a history around the clock, run `tplink-modem-mcp sample` every minute from a timer on a machine that stays
92
+ on, and start the MCP server with `TPLINK_PRESENCE_INTERVAL=0` so only the timer writes:
93
+
94
+ ```sh
95
+ * * * * * TPLINK_PASSWORD=... uvx tplink-modem-mcp sample
96
+ ```
97
+
98
+ ## Tested on
99
+
100
+ - Archer C5v v1, firmware v1.8 (Türk Telekom), with the legacy client.
101
+
102
+ Models tplinkrouterc6u supports should work through it. If you try another model, please
103
+ [open a model report](https://github.com/YakupEmreYerli/tplink-modem-mcp/issues/new?template=model-report.yml),
104
+ whether it works or not.
105
+
106
+ ## Security
107
+
108
+ The password stays in an environment variable and is only sent to the router. Read tools never change anything;
109
+ `reboot_router` does nothing unless it is called with `confirm=true`, and the server's instructions tell the
110
+ assistant to ask you first. To report a vulnerability, see [SECURITY.md](SECURITY.md).
111
+
112
+ ## Contributing
113
+
114
+ See [CONTRIBUTING.md](CONTRIBUTING.md).
115
+
116
+ ## Credits
117
+
118
+ - [tplinkrouterc6u](https://github.com/AlexandrErohin/TP-Link-Archer-C6U) by Alex Erohin (GPL-3.0), which does
119
+ most of the talking to the router; the legacy client extends its MR200 client.
120
+ - [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) (MIT).
121
+ - Fonts in the brand kit: [Geist](https://vercel.com/font) (SIL OFL 1.1).
122
+
123
+ ## License
124
+
125
+ [GPL-3.0-or-later](LICENSE), because the server extends tplinkrouterc6u, which is GPL-3.0.
@@ -0,0 +1,49 @@
1
+ [project]
2
+ name = "tplink-modem-mcp"
3
+ version = "0.1.0"
4
+ description = "MCP server for TP-Link routers and ISP modems: devices, Wi-Fi signal, logs, presence history"
5
+ readme = "README.md"
6
+ license = "GPL-3.0-or-later"
7
+ keywords = [
8
+ "mcp",
9
+ "mcp-server",
10
+ "tp-link",
11
+ "router",
12
+ "modem",
13
+ "archer",
14
+ "wifi",
15
+ "home-network",
16
+ ]
17
+ classifiers = [
18
+ "Development Status :: 4 - Beta",
19
+ "Environment :: Console",
20
+ "Intended Audience :: End Users/Desktop",
21
+ "Operating System :: OS Independent",
22
+ "Programming Language :: Python :: 3",
23
+ "Topic :: System :: Networking :: Monitoring",
24
+ ]
25
+ requires-python = ">=3.12"
26
+ dependencies = [
27
+ "mcp[cli]>=2.3.0",
28
+ "tplinkrouterc6u>=5.40.0",
29
+ ]
30
+
31
+ [[project.authors]]
32
+ name = "Yakup Emre Yerli"
33
+
34
+ [project.urls]
35
+ Homepage = "https://github.com/YakupEmreYerli/tplink-modem-mcp"
36
+ Issues = "https://github.com/YakupEmreYerli/tplink-modem-mcp/issues"
37
+
38
+ [project.scripts]
39
+ tplink-modem-mcp = "tplink_modem_mcp.server:main"
40
+
41
+ [build-system]
42
+ requires = ["uv_build>=0.13.8,<0.14.0"]
43
+ build-backend = "uv_build"
44
+
45
+ [dependency-groups]
46
+ dev = [
47
+ "anyio>=4.16.0",
48
+ "pytest>=9.2.0",
49
+ ]
@@ -0,0 +1,40 @@
1
+ [project]
2
+ name = "tplink-modem-mcp"
3
+ version = "0.1.0"
4
+ description = "MCP server for TP-Link routers and ISP modems: devices, Wi-Fi signal, logs, presence history"
5
+ readme = "README.md"
6
+ license = "GPL-3.0-or-later"
7
+ keywords = ["mcp", "mcp-server", "tp-link", "router", "modem", "archer", "wifi", "home-network"]
8
+ classifiers = [
9
+ "Development Status :: 4 - Beta",
10
+ "Environment :: Console",
11
+ "Intended Audience :: End Users/Desktop",
12
+ "Operating System :: OS Independent",
13
+ "Programming Language :: Python :: 3",
14
+ "Topic :: System :: Networking :: Monitoring",
15
+ ]
16
+ authors = [
17
+ { name = "Yakup Emre Yerli" }
18
+ ]
19
+ requires-python = ">=3.12"
20
+ dependencies = [
21
+ "mcp[cli]>=2.3.0",
22
+ "tplinkrouterc6u>=5.40.0",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/YakupEmreYerli/tplink-modem-mcp"
27
+ Issues = "https://github.com/YakupEmreYerli/tplink-modem-mcp/issues"
28
+
29
+ [project.scripts]
30
+ tplink-modem-mcp = "tplink_modem_mcp.server:main"
31
+
32
+ [build-system]
33
+ requires = ["uv_build>=0.13.8,<0.14.0"]
34
+ build-backend = "uv_build"
35
+
36
+ [dependency-groups]
37
+ dev = [
38
+ "anyio>=4.16.0",
39
+ "pytest>=9.2.0",
40
+ ]
@@ -0,0 +1 @@
1
+ """MCP server for TP-Link routers and ISP modems."""
@@ -0,0 +1,69 @@
1
+ """Join/leave history of clients, which the router itself does not keep.
2
+
3
+ A sampler compares the client list with the previous sample and appends events to a JSON-lines file.
4
+ """
5
+ import json
6
+ import os
7
+ import threading
8
+ import time
9
+ from pathlib import Path
10
+
11
+ STATE = Path(os.environ.get("TPLINK_STATE_DIR")
12
+ or Path(os.environ.get("XDG_STATE_HOME", Path.home() / ".local/state")) / "tplink-modem-mcp")
13
+
14
+
15
+ class History:
16
+ def __init__(self, path: Path | None = None):
17
+ self.path = path or STATE / "presence.jsonl"
18
+ self.snapshot = self.path.with_name("last.json") # previous sample, so one-shot runs can compare
19
+ self.last = None # mac -> {"ip", "name", "connection"}
20
+ self._lock = threading.Lock()
21
+
22
+ def sample(self, devices: list[dict]) -> list[dict]:
23
+ """Record one sample; returns the new events."""
24
+ now = time.time()
25
+ cur = {d["mac"]: {"ip": d.get("ip"), "name": d.get("hostname"), "connection": d.get("connection")}
26
+ for d in devices if d.get("mac")}
27
+ events = []
28
+ with self._lock:
29
+ if self.last is None and self.snapshot.exists():
30
+ try:
31
+ self.last = json.loads(self.snapshot.read_text())
32
+ except ValueError:
33
+ pass
34
+ if self.last is not None:
35
+ for mac in cur.keys() - self.last.keys():
36
+ events.append({"t": now, "event": "join", "mac": mac, **cur[mac]})
37
+ for mac in self.last.keys() - cur.keys():
38
+ events.append({"t": now, "event": "leave", "mac": mac, **self.last[mac]})
39
+ for mac in cur.keys() & self.last.keys():
40
+ if cur[mac]["ip"] != self.last[mac]["ip"]:
41
+ events.append({"t": now, "event": "ip_change", "mac": mac, "old_ip": self.last[mac]["ip"],
42
+ **cur[mac]})
43
+ self.last = cur
44
+ self.path.parent.mkdir(parents=True, exist_ok=True)
45
+ tmp = self.snapshot.with_suffix(".tmp")
46
+ tmp.write_text(json.dumps(cur, ensure_ascii=False))
47
+ tmp.replace(self.snapshot)
48
+ if events:
49
+ with self.path.open("a") as f:
50
+ for e in events:
51
+ f.write(json.dumps(e, ensure_ascii=False) + "\n")
52
+ return events
53
+
54
+ def query(self, since_hours: float = 24, mac: str = "", limit: int = 200) -> list[dict]:
55
+ if not self.path.exists():
56
+ return []
57
+ cutoff = time.time() - since_hours * 3600
58
+ mac = mac.lower().replace("-", ":")
59
+ out = []
60
+ with self.path.open() as f:
61
+ for line in f:
62
+ try:
63
+ e = json.loads(line)
64
+ except ValueError:
65
+ continue
66
+ if e["t"] >= cutoff and (not mac or e["mac"].lower().replace("-", ":") == mac):
67
+ e["time"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(e["t"]))
68
+ out.append(e)
69
+ return out[-limit:]
@@ -0,0 +1,157 @@
1
+ """Client for older TP-Link ISP firmwares (e.g. Archer C5v from Turkish Telekom) that tplinkrouterc6u does not detect.
2
+
3
+ Their web UI logs in with /cgi/login?UserName=<rsa>&Passwd=<rsa(base64(pw))>&Action=1&LoginStatus=0 (PKCS#1 v1.5,
4
+ 1024-bit key from /cgi/getParm, which has no "seq"), then (if the firmware has one) reads a token from the index page and talks plain
5
+ /cgi?<types> requests, like the MR200 client.
6
+ """
7
+ import base64
8
+ import re
9
+ import time
10
+ from binascii import hexlify
11
+
12
+ from Crypto.Cipher import PKCS1_v1_5
13
+ from Crypto.PublicKey import RSA
14
+ from tplinkrouterc6u.client.mr200 import TPLinkMR200Client
15
+ from tplinkrouterc6u.common.exception import AuthorizeError, ClientException
16
+
17
+ LOGIN_ERRORS = {71233: "wrong username or password", 71234: "bad login request"}
18
+
19
+
20
+ class LegacyCgiClient(TPLinkMR200Client):
21
+ ROUTER_NAME = "TP-Link legacy CGI"
22
+
23
+ def supports(self) -> bool:
24
+ try:
25
+ self._get_params()
26
+ return True
27
+ except ClientException:
28
+ return False
29
+
30
+ @staticmethod
31
+ def detect(host: str, timeout: int = 10) -> bool:
32
+ """The login page posts to /cgi/login?UserName= and /cgi/getParm has no "seq" (the newer MR login has one)."""
33
+ import requests
34
+ try:
35
+ page = requests.get(host, timeout=timeout).text
36
+ if "cgi/login?UserName=" not in page:
37
+ return False
38
+ parm = requests.post(f"{host}/cgi/getParm", headers={"Referer": host + "/"}, timeout=timeout).text
39
+ return 'nn="' in parm and "seq" not in parm
40
+ except requests.RequestException:
41
+ return False
42
+
43
+ SESSION_REUSE = 120 # seconds; a call that fails gets a fresh login from the Router wrapper anyway
44
+
45
+ def authorize(self) -> None:
46
+ # Logging in again on every call would also throw a person out of the web UI each time.
47
+ if getattr(self, "_authed_at", 0) > time.monotonic() - self.SESSION_REUSE:
48
+ return
49
+ self._get_params()
50
+ cipher = PKCS1_v1_5.new(RSA.construct((self._nn, self._ee)))
51
+
52
+ def enc(data: bytes) -> str:
53
+ return hexlify(cipher.encrypt(data)).decode().rjust(256, "0")
54
+
55
+ name = enc(self.username.encode())
56
+ pw = enc(base64.b64encode(self.password.encode()))
57
+ r = self.req.post(f"{self.host}/cgi/login?UserName={name}&Passwd={pw}&Action=1&LoginStatus=0",
58
+ timeout=self.timeout)
59
+ m = re.search(r"\$\.ret=(\d+)", r.text)
60
+ ret = int(m.group(1)) if m else -1
61
+ if ret != 0:
62
+ raise AuthorizeError(f"login refused ({ret}: {LOGIN_ERRORS.get(ret, 'unknown')})")
63
+ self.req.post(f"{self.host}/cgi/info", timeout=self.timeout)
64
+ # Some firmwares add a TokenID next to the session cookie; the Archer C5v uses the cookie alone.
65
+ page = self.req.get(self.host, timeout=self.timeout).text
66
+ m = re.search(r'token\s*=\s*"([^"]+)"', page)
67
+ if m:
68
+ self.req.headers["TokenID"] = m.group(1)
69
+ self._authed_at = time.monotonic()
70
+
71
+ # ----- reads the generic MR code gets wrong on these firmwares -----
72
+
73
+ def _gl(self, oid: str, gs: bool = False) -> list[dict]:
74
+ """All instances of an object: [{"_stack": "1,1,0,0,0,0", attr: value, ...}]."""
75
+ r, _ = self.req_act([self.ActItem(self.ActItem.GS if gs else self.ActItem.GL, oid)])
76
+ err = re.search(r"\[error\](\d+)", r.text)
77
+ if err and err.group(1) != "0":
78
+ self._authed_at = 0
79
+ raise ClientException(f"{oid}: router error {err.group(1)}")
80
+ out = []
81
+ for block in r.text.split("\n["):
82
+ head, _, body = block.lstrip("[").partition("\n")
83
+ m = re.match(r"([\d,]+)\]\d+$", head.strip())
84
+ if not m:
85
+ continue
86
+ item = {"_stack": m.group(1)}
87
+ for line in body.splitlines():
88
+ if "=" in line:
89
+ k, v = line.split("=", 1)
90
+ item[k] = v
91
+ out.append(item)
92
+ return out
93
+
94
+ def wifi_networks(self) -> list[dict]:
95
+ """Each SSID with band, channel, on/off; index = WLANConfiguration number."""
96
+ return [{"index": int(w["_stack"].split(",")[1]), "ssid": w.get("SSID", ""), "band": w.get("X_TP_Band", ""),
97
+ "enabled": w.get("enable") == "1", "channel": w.get("channel", ""), "standard": w.get("standard", "")}
98
+ for w in self._gl("LAN_WLAN")]
99
+
100
+ def stations(self) -> list[dict]:
101
+ """Associated Wi-Fi clients with signal (dBm) and last rate (Mbps), with the SSID index they are on."""
102
+ out = []
103
+ for s in self._gl("LAN_WLAN_ASSOC_DEV", gs=True):
104
+ sig = s.get("X_TT_SignalStrength") or s.get("X_TP_SignalStrength") or s.get("signalStrength") or ""
105
+ out.append({"mac": s.get("associatedDeviceMACAddress", "").upper(),
106
+ "network_index": int(s["_stack"].split(",")[1]),
107
+ "signal_dbm": int(sig) if sig.lstrip("-").isdigit() else None,
108
+ "rate_mbps": int(s["lastDataTransmitRate"]) if s.get("lastDataTransmitRate", "").isdigit() else None,
109
+ "packets_sent": int(s["X_TP_TotalPacketsSent"]) if s.get("X_TP_TotalPacketsSent", "").isdigit() else None})
110
+ return out
111
+
112
+ def hosts(self) -> list[dict]:
113
+ """Every host the router knows (LAN_HOST_ENTRY), merged with Wi-Fi band and signal."""
114
+ nets = {n["index"]: n for n in self.wifi_networks()}
115
+ stas = {s["mac"]: s for s in self.stations()}
116
+ out = []
117
+ for h in self._gl("LAN_HOST_ENTRY"):
118
+ mac = h.get("MACAddress", "").upper()
119
+ m = re.search(r"WLANConfiguration\.(\d+)", h.get("layer2Interface", ""))
120
+ net = nets.get(int(m.group(1))) if m else None
121
+ sta = stas.get(mac, {})
122
+ out.append({"hostname": h.get("hostName", ""), "ip": h.get("IPAddress", ""), "mac": mac,
123
+ "active": h.get("active") == "1",
124
+ "connection": f"wifi {net['band']}" if net else ("wired" if h.get("interfaceType") == "Ethernet" else h.get("interfaceType", "")),
125
+ "ssid": net["ssid"] if net else None,
126
+ "signal_dbm": sta.get("signal_dbm"), "rate_mbps": sta.get("rate_mbps"),
127
+ "address_source": h.get("addressSource", ""),
128
+ "lease_seconds_left": int(h["leaseTimeRemaining"]) if h.get("leaseTimeRemaining", "").isdigit() else None})
129
+ return out
130
+
131
+ def logs(self) -> list[dict]:
132
+ """System log, newest first: time, severity (0 emerg .. 7 debug), module, message."""
133
+ lines = self.req.get(f"{self.host}/cgi/log", timeout=self.timeout).text.split("\r\n")
134
+ out = []
135
+ for line in lines[1:]:
136
+ m = re.match(r"([\d-]+\s[\d:]+)\s\[(\d)\]\s(\w+):\s(.*)", line)
137
+ if m:
138
+ out.append({"time": m.group(1), "severity": int(m.group(2)), "module": m.group(3).upper(),
139
+ "message": m.group(4)})
140
+ return out[::-1]
141
+
142
+ def internet(self) -> dict:
143
+ """Enabled WAN connections (PPP and IP) and the LAN address; the generic IPv4 read picks the ISP's
144
+ management line on these firmwares instead of the internet one."""
145
+ wans = []
146
+ for oid in ("WAN_PPP_CONN", "WAN_IP_CONN"):
147
+ for w in self._gl(oid, gs=True):
148
+ if w.get("enable") != "1":
149
+ continue
150
+ up = w.get("uptime", "")
151
+ wans.append({"name": w.get("name", ""), "status": w.get("connectionStatus", ""),
152
+ "type": "PPPoE" if oid == "WAN_PPP_CONN" else "IP",
153
+ "external_ip": w.get("externalIPAddress", ""), "dns": w.get("DNSServers", ""),
154
+ "uptime_seconds": int(up) if up.isdigit() else None,
155
+ "ipv6_enabled": w.get("X_TP_IPv6Enabled") == "1"})
156
+ lan = next((i for i in self._gl("LAN_IP_INTF", gs=True) if i.get("enable") == "1"), {})
157
+ return {"wan": wans, "lan_ip": lan.get("IPInterfaceIPAddress", ""), "lan_mask": lan.get("IPInterfaceSubnetMask", "")}
File without changes
@@ -0,0 +1,89 @@
1
+ """One shared, serialised connection to the router.
2
+
3
+ TP-Link firmwares allow a single admin session at a time, so every call goes through one lock and one client,
4
+ and a failed call logs in again once before giving up.
5
+ """
6
+ import logging
7
+ import os
8
+ import threading
9
+ from dataclasses import fields, is_dataclass
10
+ from enum import Enum
11
+ from ipaddress import IPv4Address, IPv6Address
12
+
13
+ from tplinkrouterc6u import TplinkRouterProvider
14
+ import tplinkrouterc6u
15
+
16
+ from .legacy import LegacyCgiClient
17
+
18
+ log = logging.getLogger(__name__)
19
+
20
+
21
+ class Config:
22
+ def __init__(self):
23
+ self.host = os.environ.get("TPLINK_HOST", "http://192.168.1.1").rstrip("/")
24
+ if "://" not in self.host:
25
+ self.host = "http://" + self.host
26
+ self.username = os.environ.get("TPLINK_USERNAME", "admin")
27
+ self.password = os.environ.get("TPLINK_PASSWORD", "")
28
+ self.client = os.environ.get("TPLINK_CLIENT", "") # "legacy", a tplinkrouterc6u class name, or empty = auto-detect
29
+ self.timeout = int(os.environ.get("TPLINK_TIMEOUT", "20"))
30
+
31
+
32
+ class Router:
33
+ def __init__(self, config: Config | None = None):
34
+ self.config = config or Config()
35
+ self._lock = threading.Lock()
36
+ self._client = None
37
+
38
+ def _make_client(self):
39
+ c = self.config
40
+ if not c.password:
41
+ raise RuntimeError("TPLINK_PASSWORD is not set")
42
+ if c.client and c.client.lower() != "legacy":
43
+ cls = getattr(tplinkrouterc6u, c.client, None)
44
+ if cls is None:
45
+ raise RuntimeError(f"unknown TPLINK_CLIENT {c.client!r}")
46
+ return cls(c.host, c.password, c.username, timeout=c.timeout)
47
+ if c.client.lower() == "legacy" or (not c.client and LegacyCgiClient.detect(c.host, c.timeout)):
48
+ return LegacyCgiClient(c.host, c.password, c.username, timeout=c.timeout)
49
+ return TplinkRouterProvider.get_client(c.host, c.password, c.username, timeout=c.timeout)
50
+
51
+ def call(self, fn):
52
+ """Run fn(client) logged in; on failure drop the session, log in again and retry once."""
53
+ with self._lock:
54
+ for attempt in (1, 2):
55
+ try:
56
+ if self._client is None:
57
+ self._client = self._make_client()
58
+ self._client.authorize()
59
+ return fn(self._client)
60
+ except Exception:
61
+ log.debug("router call failed (attempt %d)", attempt, exc_info=True)
62
+ self._client = None
63
+ if attempt == 2:
64
+ raise
65
+
66
+ @property
67
+ def client_name(self) -> str:
68
+ return type(self._client).__name__ if self._client else ""
69
+
70
+
71
+ def plain(obj):
72
+ """Library dataclasses -> JSON-friendly dicts; private '_x' fields come out through their public properties."""
73
+ if isinstance(obj, (list, tuple)):
74
+ return [plain(o) for o in obj]
75
+ if isinstance(obj, Enum):
76
+ return obj.value
77
+ if isinstance(obj, (IPv4Address, IPv6Address)):
78
+ return str(obj)
79
+ if is_dataclass(obj):
80
+ out = {}
81
+ for f in fields(obj):
82
+ name = f.name.lstrip("_")
83
+ value = getattr(obj, name, None) if f.name.startswith("_") else getattr(obj, f.name)
84
+ if value is not None and value != []:
85
+ out[name] = plain(value)
86
+ return out
87
+ if isinstance(obj, (str, int, float, bool)) or obj is None:
88
+ return obj
89
+ return str(obj)
@@ -0,0 +1,191 @@
1
+ """MCP server for TP-Link routers and ISP modems.
2
+
3
+ Works with every model tplinkrouterc6u supports, plus older ISP firmwares it does not detect (Archer C5v and
4
+ relatives; see legacy.py). Read tools are free to call. Tools that change the router need confirm=true.
5
+ """
6
+ import asyncio
7
+ import logging
8
+ import os
9
+ from contextlib import asynccontextmanager
10
+
11
+ from mcp.server.mcpserver import MCPServer
12
+ from mcp.types import ToolAnnotations
13
+
14
+ from .history import History
15
+ from .router import Router, plain
16
+
17
+ log = logging.getLogger("tplink_modem_mcp")
18
+ READ = ToolAnnotations(readOnlyHint=True, idempotentHint=True, openWorldHint=False)
19
+ WRITE = ToolAnnotations(readOnlyHint=False, destructiveHint=True, openWorldHint=False)
20
+
21
+ router = Router()
22
+ history = History()
23
+ # 0 = no background sampling, e.g. when `tplink-modem-mcp sample` runs from a timer and fills the same history.
24
+ SAMPLE_SECONDS = int(os.environ.get("TPLINK_PRESENCE_INTERVAL", "60"))
25
+ SEVERITY = ["emerg", "alert", "crit", "err", "warn", "notice", "info", "debug"]
26
+
27
+
28
+ def _clients(c) -> list[dict]:
29
+ """One shape for every client class: hostname, ip, mac, active, connection, ssid, signal_dbm, rate_mbps."""
30
+ if hasattr(c, "hosts"):
31
+ return c.hosts()
32
+ out = []
33
+ for d in plain(c.get_status().devices):
34
+ out.append({"hostname": d.get("hostname", ""), "ip": d.get("ipaddr", ""), "mac": d.get("macaddr", ""),
35
+ "active": d.get("active", True), "connection": d.get("type", ""), "ssid": d.get("ssid"),
36
+ "signal_dbm": d.get("signal"), "rate_mbps": d.get("tx_rate")})
37
+ return out
38
+
39
+
40
+ async def _run(fn):
41
+ return await asyncio.to_thread(router.call, fn)
42
+
43
+
44
+ async def _sampler():
45
+ while True:
46
+ try:
47
+ clients = await _run(_clients)
48
+ history.sample([d for d in clients if d["active"]])
49
+ except Exception:
50
+ log.debug("presence sample failed", exc_info=True)
51
+ await asyncio.sleep(SAMPLE_SECONDS)
52
+
53
+
54
+ @asynccontextmanager
55
+ async def lifespan(_server):
56
+ task = asyncio.create_task(_sampler()) if SAMPLE_SECONDS > 0 else None
57
+ try:
58
+ yield None
59
+ finally:
60
+ if task:
61
+ task.cancel()
62
+
63
+
64
+ mcp = MCPServer(
65
+ "tplink-modem",
66
+ instructions="Reads and manages a TP-Link router or ISP modem on the local network. Read tools are safe. "
67
+ "Tools that change settings or reboot need confirm=true; ask the user before setting it. "
68
+ "For 'device X keeps dropping' questions combine list_clients (signal), client_history and "
69
+ "router_logs (DHCP DISCOVER lines show a device joining again).",
70
+ lifespan=lifespan,
71
+ )
72
+
73
+
74
+ @mcp.tool(annotations=READ)
75
+ async def router_status() -> dict:
76
+ """Overview: model and firmware, internet connection (status, external IP, uptime), LAN address, Wi-Fi
77
+ networks that are on, number of devices online."""
78
+ def read(c):
79
+ out = {"firmware": plain(c.get_firmware()),
80
+ "network": c.internet() if hasattr(c, "internet") else plain(c.get_ipv4_status())}
81
+ if hasattr(c, "wifi_networks"):
82
+ out["wifi"] = [n for n in c.wifi_networks() if n["enabled"]]
83
+ out["online_devices"] = sum(1 for d in _clients(c) if d["active"])
84
+ return out
85
+ status = await _run(read)
86
+ status["client_class"] = router.client_name
87
+ return status
88
+
89
+
90
+ @mcp.tool(annotations=READ)
91
+ async def list_clients(include_inactive: bool = False) -> list[dict]:
92
+ """Devices on the network: hostname, IP, MAC, wired or Wi-Fi band and SSID, signal (dBm, closer to 0 is
93
+ better; below -75 is weak) and link rate where the router reports them."""
94
+ clients = await _run(_clients)
95
+ return [d for d in clients if include_inactive or d["active"]]
96
+
97
+
98
+ @mcp.tool(annotations=READ)
99
+ async def find_client(query: str) -> list[dict]:
100
+ """Devices whose hostname, IP or MAC contains the query (case-insensitive; '-' and ':' both work in MACs)."""
101
+ q = query.lower().replace("-", ":")
102
+ return [d for d in await _run(_clients)
103
+ if q in (d["hostname"] or "").lower() or q in (d["ip"] or "")
104
+ or q in (d["mac"] or "").lower().replace("-", ":")]
105
+
106
+
107
+ @mcp.tool(annotations=READ)
108
+ async def client_history(since_hours: float = 24, mac: str = "", limit: int = 200) -> list[dict]:
109
+ """Join / leave / IP-change events recorded by this server (routers keep no such log). Shows which device
110
+ keeps dropping off the network and when. Sampled every TPLINK_PRESENCE_INTERVAL seconds (default 60) while
111
+ the server runs."""
112
+ return history.query(since_hours, mac, limit)
113
+
114
+
115
+ @mcp.tool(annotations=READ)
116
+ async def wifi_networks() -> list[dict]:
117
+ """Every SSID the router has, with band, channel, standard and whether it is on."""
118
+ def read(c):
119
+ if not hasattr(c, "wifi_networks"):
120
+ raise RuntimeError("this router model does not expose its Wi-Fi network list here")
121
+ return c.wifi_networks()
122
+ return await _run(read)
123
+
124
+
125
+ @mcp.tool(annotations=READ)
126
+ async def router_logs(module: str = "", contains: str = "", max_severity: int = 7, limit: int = 100) -> list[dict]:
127
+ """System log, newest first. module: e.g. DHCPD, PPP, DHCPC, SYSTEM. contains: text or a MAC to look for.
128
+ max_severity: 0 emerg, 3 err, 4 warn, 6 info, 7 debug (everything). Note: the router clears it on reboot."""
129
+ def read(c):
130
+ if not hasattr(c, "logs"):
131
+ raise RuntimeError("this router model does not expose its system log here")
132
+ return c.logs()
133
+ want = contains.lower()
134
+ out = []
135
+ for e in await _run(read):
136
+ if module and e["module"] != module.upper():
137
+ continue
138
+ if e["severity"] > max_severity or (want and want not in e["message"].lower()):
139
+ continue
140
+ out.append({**e, "severity": SEVERITY[e["severity"]] if e["severity"] < len(SEVERITY) else e["severity"]})
141
+ if len(out) >= limit:
142
+ break
143
+ return out
144
+
145
+
146
+ @mcp.tool(annotations=READ)
147
+ async def dhcp_leases() -> list[dict]:
148
+ """Active DHCP leases: hostname, IP, MAC, lease time left."""
149
+ return plain(await _run(lambda c: c.get_ipv4_dhcp_leases()))
150
+
151
+
152
+ @mcp.tool(annotations=READ)
153
+ async def dhcp_reservations() -> list[dict]:
154
+ """Fixed IP reservations (address reservation) configured on the router."""
155
+ return plain(await _run(lambda c: c.get_ipv4_reservations()))
156
+
157
+
158
+ @mcp.tool(annotations=READ)
159
+ async def ipv6_status() -> dict:
160
+ """WAN and LAN IPv6 status, if the model supports it."""
161
+ return plain(await _run(lambda c: c.get_ipv6_status()))
162
+
163
+
164
+ @mcp.tool(annotations=WRITE)
165
+ async def reboot_router(confirm: bool = False) -> str:
166
+ """Reboot the router. The whole network and the internet drop for a minute or two. Needs confirm=true."""
167
+ if not confirm:
168
+ return "Not rebooted. Call again with confirm=true to reboot."
169
+ await _run(lambda c: c.reboot())
170
+ return "Reboot requested; the router is back in about two minutes."
171
+
172
+
173
+ def sample_once() -> int:
174
+ """`tplink-modem-mcp sample`: one presence sample for a timer (cron, systemd); prints the new events."""
175
+ import json
176
+ events = history.sample([d for d in router.call(_clients) if d["active"]])
177
+ for e in events:
178
+ print(json.dumps(e, ensure_ascii=False))
179
+ return 0
180
+
181
+
182
+ def main():
183
+ import sys
184
+ logging.basicConfig(level=os.environ.get("TPLINK_LOG", "WARNING"))
185
+ if sys.argv[1:] == ["sample"]:
186
+ raise SystemExit(sample_once())
187
+ mcp.run()
188
+
189
+
190
+ if __name__ == "__main__":
191
+ main()