diff --git a/README.en.md b/README.en.md index a824208..cd12bac 100644 --- a/README.en.md +++ b/README.en.md @@ -123,6 +123,8 @@ adh tools --json --endpoint http://127.0.0.1:8088 `status --json` returns a read-only snapshot with `schemaVersion: 1`, `checkedAt`, service observations in `connections`, and current app/PID identifiers in `targets`. An offline address is never reported as an online target. Status does not save connections, inject, restart apps, or upgrade the CLI. `tools --json` reads the real MCP tool descriptions and argument schemas. Refresh status, select a unique returned target, then use `call` or the persistent MCP connection; ask the user when multiple targets match. +`configuration.source` is `explicit` or `saved`. An explicit `--endpoint` checks only the given addresses and ignores saved ones. The desktop can receive limited verified usage receipts from the same local stdio MCP subprocess. They are not tool output and do not change permissions, target selection, or call logic; without such a receipt, AI usage cannot be assumed. + ADH defaults to port 8088. `devices --endpoint` inspects a temporary address. `call` exits nonzero for an MCP error or `isError` result. ## Development checks diff --git a/README.md b/README.md index 18b6c88..24aba0a 100644 --- a/README.md +++ b/README.md @@ -169,6 +169,8 @@ adh tools --json --endpoint http://127.0.0.1:8088 `status --json` 返回带 `schemaVersion: 1` 和 `checkedAt` 的只读快照,分别列出 `connections` 的服务在线事实及 `targets` 的应用/PID/目标标识;离线地址不会冒充在线目标。状态查询不保存地址、不注入、不启停应用,也不自动升级 CLI。`tools --json` 返回当前目标的真实 MCP 工具说明和参数 schema。先查询状态,再选择本次返回的唯一目标,最后通过现有 `call` 或持久 MCP 连接执行分析;多个候选必须让用户选择。 +`configuration.source` 为 `explicit` 或 `saved`。显式 `--endpoint` 只检查传入地址,忽略已保存的地址。 桌面端可从同一个本机 stdio MCP 子进程收到有限的已验证使用回报。它不是工具输出,不改变权限、目标选择或调用逻辑;无相应回报时不能认定 AI 已使用。 + ADH 省略端口时默认连接 8088;`devices --endpoint` 支持临时探测,`call` 收到 MCP 错误或 `isError` 时返回非零退出码。 ## 开发验证 diff --git a/pyproject.toml b/pyproject.toml index bfc52d6..39c304f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "android-decrypt-hub" -version = "0.2.0" +version = "0.2.1" description = "Connect to Host ADH Daemon and bridge HTTP MCP to stdio" readme = "README.md" requires-python = ">=3.10" diff --git a/src/adh/__init__.py b/src/adh/__init__.py index 41394a8..47fc440 100644 --- a/src/adh/__init__.py +++ b/src/adh/__init__.py @@ -1,3 +1,3 @@ """Android DecryptHub MCP gateway.""" -__version__ = "0.2.0" +__version__ = "0.2.1" diff --git a/src/adh/cli.py b/src/adh/cli.py index 2c4e92e..5e41058 100644 --- a/src/adh/cli.py +++ b/src/adh/cli.py @@ -186,7 +186,7 @@ def _cmd_devices(args: argparse.Namespace) -> int: def _cmd_status(args: argparse.Namespace) -> int: endpoints = [HostEndpoint.from_url(value) for value in args.endpoint] if args.endpoint else load_saved_endpoints() - data = inventory(endpoints, timeout=args.timeout) + data = inventory(endpoints, timeout=args.timeout, source="explicit" if args.endpoint else "saved") print(json.dumps(data, ensure_ascii=False, indent=2)) return 0 diff --git a/src/adh/http_mcp.py b/src/adh/http_mcp.py index 73e24a6..42f684e 100644 --- a/src/adh/http_mcp.py +++ b/src/adh/http_mcp.py @@ -10,6 +10,7 @@ from urllib.request import Request, urlopen from . import __version__ +from .observation import observe_result from .endpoint import HostEndpoint @@ -53,7 +54,8 @@ def send(self, message: Any) -> Any | None: payload = response.read() if response.status in (202, 204) or not payload: return None - return json.loads(payload) + value = json.loads(payload) + return observe_result(message, value, request.full_url, response.geturl()) except HTTPError as exc: detail = exc.read().decode("utf-8", errors="replace") raise MCPTransportError( diff --git a/src/adh/observation.py b/src/adh/observation.py new file mode 100644 index 0000000..41882da --- /dev/null +++ b/src/adh/observation.py @@ -0,0 +1,38 @@ +"""Opt-in, read-only receipt metadata for the owning desktop.""" +from __future__ import annotations + +import os +import re +from typing import Any + +_META_KEY = "decrypthub/usage" +_NONCE = re.compile(r"[0-9a-f]{32}") + + +def observe_result( + request: Any, response: Any, endpoint: str, response_url: str +) -> Any: + """Stamp the service that answered this tool call, without changing routing.""" + nonce = os.environ.get("DECRYPTHUB_MCP_OBSERVATION", "") + if not _NONCE.fullmatch(nonce) or not isinstance(request, dict) or request.get("method") != "tools/call": + return response + if not isinstance(response, dict) or "error" in response: + return response + result = response.get("result") + if "id" not in request or response.get("id") != request["id"] or not isinstance(result, dict): + return response + incoming = result.get("_meta") + metadata = dict(incoming) if isinstance(incoming, dict) else {} + # The remote service cannot report on behalf of the local CLI. + metadata.pop(_META_KEY, None) + if response_url == endpoint and result.get("isError") is not True and isinstance(result.get("content"), list): + metadata[_META_KEY] = { + "schemaVersion": 1, + "nonce": nonce, + "component": "adh", + "target": {"kind": "service", "id": endpoint, "endpoint": endpoint}, + } + value = {key: item for key, item in result.items() if key != "_meta"} + if metadata: + value["_meta"] = metadata + return {**response, "result": value} diff --git a/src/adh/status.py b/src/adh/status.py index c889678..9fe761d 100644 --- a/src/adh/status.py +++ b/src/adh/status.py @@ -10,7 +10,7 @@ from .http_mcp import probe_endpoint -def inventory(endpoints: list[HostEndpoint], *, timeout: float = 3.0) -> dict[str, Any]: +def inventory(endpoints: list[HostEndpoint], *, timeout: float = 3.0, source: str = "explicit") -> dict[str, Any]: unique = list({endpoint.key: endpoint for endpoint in endpoints}.values()) with ThreadPoolExecutor(max_workers=max(1, min(8, len(unique)))) as pool: checked = list(pool.map(lambda endpoint: probe_endpoint(endpoint, timeout=timeout), unique)) @@ -29,4 +29,5 @@ def inventory(endpoints: list[HostEndpoint], *, timeout: float = 3.0) -> dict[st "package": app.get("package"), "pid": app.get("pid"), "endpoint": endpoint.mcp_url, "online": online and app.get("online") is True}) return {"schemaVersion": 1, "component": "adh", "version": __version__, - "checkedAt": datetime.now(timezone.utc).isoformat(), "connections": connections, "targets": targets} + "checkedAt": datetime.now(timezone.utc).isoformat(), "connections": connections, "targets": targets, + "configuration": {"source": source, "endpoints": [endpoint.mcp_url for endpoint in checked]}} diff --git a/tests/test_observation.py b/tests/test_observation.py new file mode 100644 index 0000000..d0ab243 --- /dev/null +++ b/tests/test_observation.py @@ -0,0 +1,67 @@ +"""Connection receipts are only produced at a verified local HTTP response.""" +from __future__ import annotations + +import json + +from adh.http_mcp import MCPHTTPClient +from adh.endpoint import HostEndpoint +from adh.status import inventory + + +def test_status_keeps_configuration_separate_from_live_inventory(): + assert inventory([], source="explicit")["configuration"] == { + "source": "explicit", + "endpoints": [], + } + + +def test_receipt_tracks_the_actual_responding_service(monkeypatch): + a = HostEndpoint.from_url("http://127.0.0.1:49301") + b = HostEndpoint.from_url("http://127.0.0.1:49302") + nonce = "9e" * 16 + request = {"jsonrpc": "2.0", "id": 7, "method": "tools/call", "params": {"name": "fixture"}} + result = { + "jsonrpc": "2.0", + "id": 7, + "result": { + "content": [{"type": "text", "text": "fixture"}], + "_meta": {"unrelated": "retained", "decrypthub/usage": {"endpoint": b.mcp_url}}, + }, + } + + class Response: + headers = {} + status = 200 + url = a.mcp_url + + def read(self): + return json.dumps(result).encode() + + def geturl(self): + return self.url + + def __enter__(self): + return self + + def __exit__(self, *_args): + return None + + response = Response() + monkeypatch.setattr("adh.http_mcp.urlopen", lambda *_a, **_k: response) + client = MCPHTTPClient(a) + monkeypatch.delenv("DECRYPTHUB_MCP_OBSERVATION", raising=False) + assert client.send(request) == result + monkeypatch.setenv("DECRYPTHUB_MCP_OBSERVATION", nonce) + received = client.send(request)["result"]["_meta"] + assert received["unrelated"] == "retained" + assert received["decrypthub/usage"] == { + "schemaVersion": 1, + "nonce": nonce, + "component": "adh", + "target": {"kind": "service", "id": a.mcp_url, "endpoint": a.mcp_url}, + } + response.url = b.mcp_url + assert client.send(request)["result"]["_meta"] == {"unrelated": "retained"} + response.url = a.mcp_url + result["result"]["isError"] = True + assert client.send(request)["result"]["_meta"] == {"unrelated": "retained"}