forage_memory/bwf.py
6.0 KB| 1 | # -*- coding: utf-8 -*- |
| 2 | """MCP 客户端 —— 只做一件事:把工具调用发给 BlindWhaleFarmer 的本地服务器。 |
| 3 | |
| 4 | 模组启动时监听 http://127.0.0.1:18080/mcp(Streamable HTTP,无状态,不需要握手)。 |
| 5 | |
| 6 | ## 网络说明(给安全审查看) |
| 7 | |
| 8 | 本文件是全包**唯一**发起网络请求的地方,且**只允许回环地址**: |
| 9 | |
| 10 | - 目标恒为 `127.0.0.1` / `localhost` / `::1` 上的那个端口,由 `_assert_loopback()` 硬性校验, |
| 11 | 传别的地址会直接抛 `ValueError`,不会发出请求。 |
| 12 | - 不发任何遥测、不上报、不下载。本技能运行时**不需要互联网**,断网也能用。 |
| 13 | - 传输内容是 JSON-RPC 明文,落在本机回环接口上,不出网卡。 |
| 14 | - 出现的 `github.com` / `smapi.io` 字样只在文档里用于告诉用户去哪装模组,代码不会访问它们。 |
| 15 | """ |
| 16 | from __future__ import annotations |
| 17 | |
| 18 | import json |
| 19 | import urllib.error |
| 20 | import urllib.parse |
| 21 | import urllib.request |
| 22 | |
| 23 | from . import spec |
| 24 | |
| 25 | DEFAULT_URL = "http://127.0.0.1:18080/mcp" |
| 26 | |
| 27 | # 只允许这三个主机名。任何其它主机一律拒绝,防止被改成外部地址。 |
| 28 | LOOPBACK_HOSTS = ("127.0.0.1", "localhost", "::1") |
| 29 | |
| 30 | |
| 31 | def _assert_loopback(url: str) -> None: |
| 32 | """确认 url 指向本机。不是本机就抛 ValueError —— 宁可报错也不往外发数据。""" |
| 33 | host = (urllib.parse.urlsplit(url).hostname or "").lower().strip("[]") |
| 34 | if host not in LOOPBACK_HOSTS: |
| 35 | raise ValueError( |
| 36 | f"拒绝连接非本机地址:{host!r}。本技能只与游戏模组的本地服务器通信" |
| 37 | f"({' / '.join(LOOPBACK_HOSTS)}),不支持远程地址。" |
| 38 | ) |
| 39 | _HEAD = {"Content-Type": "application/json", |
| 40 | "Accept": "application/json, text/event-stream"} |
| 41 | |
| 42 | |
| 43 | class OfflineError(RuntimeError): |
| 44 | """连不上模组。通常是游戏没开、没读档,或者 MCP 被 config.json 关掉了。""" |
| 45 | |
| 46 | |
| 47 | class Client: |
| 48 | def __init__(self, url: str = DEFAULT_URL, timeout: int = 120): |
| 49 | _assert_loopback(url) # 非本机地址直接拒绝,不发请求 |
| 50 | self.url = url |
| 51 | self.timeout = timeout |
| 52 | # 本机代理(Clash / v2ray)会把 127.0.0.1 也劫走,导致 502。必须直连。 |
| 53 | self._opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) |
| 54 | self._id = 0 |
| 55 | self._cache: str | None = None |
| 56 | |
| 57 | # ---------------------------------------------------------- 底层 |
| 58 | def _rpc(self, payload: dict) -> dict: |
| 59 | body = json.dumps(payload).encode("utf-8") |
| 60 | req = urllib.request.Request(self.url, data=body, headers=_HEAD, method="POST") |
| 61 | try: |
| 62 | with self._opener.open(req, timeout=self.timeout) as resp: |
| 63 | raw = resp.read().decode("utf-8", "replace") |
| 64 | except (urllib.error.URLError, OSError) as e: |
| 65 | raise OfflineError( |
| 66 | f"连不上模组 {self.url}:{e}\n" |
| 67 | "检查:游戏开着吗?读档了吗?SMAPI 控制台有没有 'MCP 服务器已启动'?" |
| 68 | ) from e |
| 69 | for line in raw.splitlines(): |
| 70 | line = line.strip() |
| 71 | if line.startswith("data:"): |
| 72 | return json.loads(line[5:].strip()) |
| 73 | return json.loads(raw) |
| 74 | |
| 75 | # ---------------------------------------------------------- 对外 |
| 76 | def call(self, name: str, args: dict | None = None) -> str: |
| 77 | """调一个工具,返回纯文本结果(模组把结果都放在 text content 里)。""" |
| 78 | self._id += 1 |
| 79 | r = self._rpc({"jsonrpc": "2.0", "id": self._id, "method": "tools/call", |
| 80 | "params": {"name": name, "arguments": args or {}}}) |
| 81 | if "error" in r: |
| 82 | return "[MCP ERROR] " + json.dumps(r["error"], ensure_ascii=False) |
| 83 | parts = [] |
| 84 | for c in r.get("result", {}).get("content", []): |
| 85 | if c.get("type") == "text": |
| 86 | parts.append(c.get("text", "")) |
| 87 | else: |
| 88 | parts.append(json.dumps(c, ensure_ascii=False)) |
| 89 | return "\n".join(parts) |
| 90 | |
| 91 | def state(self, fresh: bool = True) -> str: |
| 92 | """读完整文字观测。每次真正进游戏读一遍,不吃缓存(缓存只给 dry-run 用)。""" |
| 93 | if not fresh and self._cache is not None: |
| 94 | return self._cache |
| 95 | txt = self.call(spec.TOOLS["state"], {}) |
| 96 | self._cache = txt |
| 97 | return txt |
| 98 | |
| 99 | def travel_to(self, location: str) -> str: |
| 100 | return self.call(spec.TOOLS["travel"], {"location": location}) |
| 101 | |
| 102 | def interact(self, pos: tuple[int, int]) -> str: |
| 103 | return self.call(spec.TOOLS["interact"], {"x": pos[0], "y": pos[1]}) |
| 104 | |
| 105 | def trash_item(self, item: str) -> str: |
| 106 | return self.call(spec.TOOLS["trash_item"], {"item": item}) |
| 107 | |
| 108 | def clear_ui(self) -> str: |
| 109 | """对话框用 dialogue 关,其它界面(箱子/商店)用 close_menu。""" |
| 110 | r = self.call(spec.TOOLS["close"], {}) |
| 111 | if "失败" in r[:15] or "[MCP ERROR]" in r: |
| 112 | r = self.call(spec.TOOLS["dialogue"], {}) |
| 113 | return r |
| 114 | |
| 115 | |
| 116 | class OfflineClient: |
| 117 | """离线假客户端:从文件读观测,动作全部记账不执行。 |
| 118 | |
| 119 | 用来跑测试 / 让人先看看「今天会去哪几个垃圾桶」而不动游戏。 |
| 120 | """ |
| 121 | |
| 122 | def __init__(self, state_text: str): |
| 123 | self._txt = state_text |
| 124 | self.log: list[tuple[str, dict]] = [] |
| 125 | |
| 126 | def call(self, name: str, args: dict | None = None) -> str: |
| 127 | self.log.append((name, args or {})) |
| 128 | if name == spec.TOOLS["state"]: |
| 129 | return self._txt |
| 130 | return "成功(离线模拟)" |
| 131 | |
| 132 | def state(self, fresh: bool = True) -> str: |
| 133 | return self._txt |
| 134 | |
| 135 | def travel_to(self, location: str) -> str: |
| 136 | return self.call(spec.TOOLS["travel"], {"location": location}) |
| 137 | |
| 138 | def interact(self, pos: tuple[int, int]) -> str: |
| 139 | return self.call(spec.TOOLS["interact"], {"x": pos[0], "y": pos[1]}) |
| 140 | |
| 141 | def trash_item(self, item: str) -> str: |
| 142 | return self.call(spec.TOOLS["trash_item"], {"item": item}) |
| 143 | |
| 144 | def clear_ui(self) -> str: |
| 145 | return self.call(spec.TOOLS["close"], {}) |
文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。

