fd-open-data-protocol 0.4.0__tar.gz → 0.5.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.
Files changed (48) hide show
  1. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/PKG-INFO +3 -1
  2. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/__init__.py +1 -1
  3. fd_open_data_protocol-0.5.0/fd_open_data_protocol/line_ops/__init__.py +44 -0
  4. fd_open_data_protocol-0.5.0/fd_open_data_protocol/line_ops/assemble.py +71 -0
  5. fd_open_data_protocol-0.5.0/fd_open_data_protocol/line_ops/auth_gate.py +126 -0
  6. fd_open_data_protocol-0.5.0/fd_open_data_protocol/line_ops/client.py +121 -0
  7. fd_open_data_protocol-0.5.0/fd_open_data_protocol/line_ops/config.py +59 -0
  8. fd_open_data_protocol-0.5.0/fd_open_data_protocol/line_ops/wellknown.py +67 -0
  9. fd_open_data_protocol-0.5.0/fd_open_data_protocol/surface_selfcheck.py +242 -0
  10. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol.egg-info/PKG-INFO +3 -1
  11. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol.egg-info/SOURCES.txt +9 -0
  12. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol.egg-info/requires.txt +3 -0
  13. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/pyproject.toml +3 -0
  14. fd_open_data_protocol-0.5.0/tests/test_line_ops.py +132 -0
  15. fd_open_data_protocol-0.5.0/tests/test_surface_selfcheck.py +129 -0
  16. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/LICENSE +0 -0
  17. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/README.md +0 -0
  18. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/conformance_adapter.py +0 -0
  19. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/constants.py +0 -0
  20. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/loader.py +0 -0
  21. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/openalex_provider.py +0 -0
  22. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/provider.py +0 -0
  23. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/registry.py +0 -0
  24. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/registry_cli.py +0 -0
  25. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/registry_store.py +0 -0
  26. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/schema.py +0 -0
  27. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/surface_report.py +0 -0
  28. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/vocabulary/alignment/foundation.yaml +0 -0
  29. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/vocabulary/concepts.yaml +0 -0
  30. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/vocabulary/crosswalks/datacommons-worldbank.yaml +0 -0
  31. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/vocabulary/entity_types.yaml +0 -0
  32. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/vocabulary/event_types.yaml +0 -0
  33. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/vocabulary/qualifiers.yaml +0 -0
  34. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/vocabulary/relation_types.yaml +0 -0
  35. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/vocabulary/units.yaml +0 -0
  36. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/vocabulary.py +0 -0
  37. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol.egg-info/dependency_links.txt +0 -0
  38. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol.egg-info/entry_points.txt +0 -0
  39. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol.egg-info/top_level.txt +0 -0
  40. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/setup.cfg +0 -0
  41. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/tests/test_loader.py +0 -0
  42. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/tests/test_openalex_provider.py +0 -0
  43. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/tests/test_registry_pipeline.py +0 -0
  44. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/tests/test_registry_schema.py +0 -0
  45. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/tests/test_schema_vocabulary.py +0 -0
  46. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/tests/test_surface_report.py +0 -0
  47. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/tests/test_vocabulary.py +0 -0
  48. {fd_open_data_protocol-0.4.0 → fd_open_data_protocol-0.5.0}/tests/test_vocabulary_additive.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fd-open-data-protocol
3
- Version: 0.4.0
3
+ Version: 0.5.0
4
4
  Summary: The open-data datasource protocol: a manifest contract a datasource exposes to be ingested by fd-open-data-mcp (or any consumer).
5
5
  Author: FindDataOfficial
6
6
  License: MIT
@@ -13,6 +13,8 @@ Provides-Extra: dev
13
13
  Requires-Dist: pytest>=8.0; extra == "dev"
14
14
  Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
15
15
  Requires-Dist: httpx>=0.27; extra == "dev"
16
+ Provides-Extra: line-ops
17
+ Requires-Dist: httpx>=0.27; extra == "line-ops"
16
18
  Provides-Extra: registry
17
19
  Requires-Dist: psycopg[binary]>=3.1; extra == "registry"
18
20
  Dynamic: license-file
@@ -5,4 +5,4 @@ concept hints + fetch reference) so that fd-open-data-mcp - or any consumer -
5
5
  can ingest it via ``register_datasource``. Ship one manifest file -> the
6
6
  datasource is added; no consumer-side wiring.
7
7
  """
8
- __version__ = "0.4.0"
8
+ __version__ = "0.5.0"
@@ -0,0 +1,44 @@
1
+ """线操作 MCP 服务的共享运行时(`line-ops-runtime-core`)。
2
+
3
+ ## 为什么存在
4
+
5
+ `lex-ops-mcp` / `wire-ops-mcp` / `facet-ops-mcp` / `wanxing-ops-mcp` / `wire-build-mcp`
6
+ 五个仓各自维护一份近同的 `auth_gate.py` / `client.py` / `config.py`(规范化线名后逐行
7
+ 相同,差异只剩注释与格式)。代价不是「多写了几百行」,而是**修复到不了没被撞的那几份**:
8
+ 2026-11-09 给 wire-ops 的鉴权缓存加上界(灌 5000 个不同 bearer 后缓存留 5000 条),
9
+ 另外四个仓的 `_cache` 至今无上界。
10
+
11
+ 同类先例是 `surface_report.py`——从三份逐仓副本抽成单一实现,本模块族走同一条路。
12
+
13
+ ## 三个模块,各一件事
14
+
15
+ - `auth_gate`:HTTP 层「无 Bearer 拒 / 有 Bearer 放行」门,缓存有界、键不可逆。
16
+ - `client`:Bearer 原样转发的上游客户端,错误按 kind 归类、凭据不落盘。
17
+ - `config`:环境驱动配置,前缀参数化(各线用自己的前缀,如 `WIRE_OPS_`)。
18
+
19
+ ## 消费方式
20
+
21
+ 各仓只保留自己的 `tools_<line>.py` 与 `server.py`(`create_server` 里注册工具),
22
+ 运行时部分 import 本模块。`line-ops-runtime-core` 的硬约束:升级前后各仓对外
23
+ `tools/list` 逐名不变——以「能启动」「测试通过」作为迁移完成判据不成立。
24
+ """
25
+ from __future__ import annotations
26
+
27
+ from .assemble import assemble
28
+ from .auth_gate import AuthGate, AuthGateMiddleware, bearer_from_scope
29
+ from .client import LineClient, LineError
30
+ from .config import LineSettings, make_settings_class
31
+ from .wellknown import WELL_KNOWN_PATH, manifest_response
32
+
33
+ __all__ = [
34
+ "assemble",
35
+ "AuthGate",
36
+ "AuthGateMiddleware",
37
+ "bearer_from_scope",
38
+ "LineClient",
39
+ "LineError",
40
+ "LineSettings",
41
+ "make_settings_class",
42
+ "WELL_KNOWN_PATH",
43
+ "manifest_response",
44
+ ]
@@ -0,0 +1,71 @@
1
+ """把「运行时 + 该线工具集」装配成完整 ASGI 应用。
2
+
3
+ 一个线服务 = 「FastMCP 实例(注册了这条线的工具)」+「鉴权门」+「/health」+
4
+ 「线自描述」。前三件事每个仓都写一遍且近乎相同;本模块把它们收成一次 `assemble()`。
5
+ 各仓只提供 `build_mcp`(建 FastMCP 并注册自己的工具)与 settings。
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from typing import Any, Callable
10
+
11
+ from .auth_gate import AuthGate, AuthGateMiddleware
12
+ from .wellknown import WELL_KNOWN_PATH, manifest_response
13
+
14
+ _HEALTH_OK = b'{"status":"ok"}'
15
+ _HEALTH_OK_REPORTED = b'{"status":"ok","last_surface_report":"ok"}'
16
+ _HEALTH_FAILED_REPORTED = b'{"status":"ok","last_surface_report":"failed"}'
17
+
18
+
19
+ def assemble(
20
+ build_mcp: Callable[[], Any],
21
+ *,
22
+ auth_cache_ttl_seconds: float = 60.0,
23
+ mcp_path: str = "/mcp",
24
+ enable_surface_report: bool = True,
25
+ ):
26
+ """返回完整 ASGI app:/health 与线自描述免门,其余走鉴权门(无 Bearer 拒)。
27
+
28
+ :param build_mcp: 无参可调用,返回一个 FastMCP 实例(工具已注册)
29
+ :param auth_cache_ttl_seconds: 鉴权缓存 TTL(来自该线 settings)
30
+ :param mcp_path: MCP 端点路径
31
+ :param enable_surface_report: 是否在首请求触发 `surface_report.ensure_started`。
32
+ 该机制要求服务对象带 `_surface_report` 属性;本模块会初始化它。
33
+ """
34
+ mcp = build_mcp()
35
+ if enable_surface_report and not hasattr(mcp, "_surface_report"):
36
+ mcp._surface_report = "not_configured"
37
+ mcp_app = mcp.http_app(path=mcp_path)
38
+ gate = AuthGateMiddleware(mcp_app, AuthGate(auth_cache_ttl_seconds))
39
+
40
+ if enable_surface_report:
41
+ from fd_open_data_protocol import surface_report as _sr
42
+ else:
43
+ _sr = None
44
+
45
+ async def app(scope, receive, send):
46
+ if scope.get("type") == "http":
47
+ if _sr is not None:
48
+ _sr.ensure_started(mcp) # 首请求触发:loop 已在跑
49
+ path = (scope.get("path") or "").rstrip("/")
50
+ if path == "/health":
51
+ state = getattr(mcp, "_surface_report", "not_configured")
52
+ body = {
53
+ "not_configured": _HEALTH_OK,
54
+ "ok": _HEALTH_OK_REPORTED,
55
+ "failed": _HEALTH_FAILED_REPORTED,
56
+ }.get(state, _HEALTH_OK)
57
+ await send({"type": "http.response.start", "status": 200,
58
+ "headers": [(b"content-type", b"application/json")]})
59
+ await send({"type": "http.response.body", "body": body})
60
+ return
61
+ # 线自描述:公开元数据,必须在鉴权门**之前**应答(与 /health 同理),
62
+ # 否则平台/客户在未持有本线凭据时连「这条线认哪些钥匙」都读不到。
63
+ if path == WELL_KNOWN_PATH.rstrip("/"):
64
+ status, body, headers = manifest_response()
65
+ await send({"type": "http.response.start", "status": status,
66
+ "headers": headers + [(b"content-length", str(len(body)).encode())]})
67
+ await send({"type": "http.response.body", "body": body})
68
+ return
69
+ await gate(scope, receive, send)
70
+
71
+ return app
@@ -0,0 +1,126 @@
1
+ """HTTP 层鉴权门(ASGI 中间件)——「无 Bearer 拒 / 有 Bearer 放行」。
2
+
3
+ 门不校验凭据真伪:有效性由上游权威判定,坏凭据的 401 在工具层原样透传。
4
+ 凭据永不落日志,缓存键是 sha256(token)。
5
+
6
+ 本实现对 5 个 ops-mcp 仓通用;线名只出现在错误文本里,由调用方传入。
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import time
12
+
13
+ #: 缓存条目上限。门的语义是「无 Bearer 拒 / 有 Bearer 放行」,**任意**非空 bearer
14
+ #: 都会写一条记录(有效性由上游权威判定),所以键的数量完全由入站流量决定——
15
+ #: 一个带随机 token 重试的坏客户端、或一批各自轮换 token 的 agent 就能把它灌满。
16
+ #: 键是 sha256(64 字符)加 tuple,每条约 150-200 字节;无上界时长跑进程的 RSS
17
+ #: 单调上升,最终 OOM 重启(并在重启后再走一遍启动退避)。
18
+ #: 2026-11-09 实测:灌 5000 个不同 bearer 后缓存留 5000 条。
19
+ DEFAULT_MAX_ENTRIES = 1024
20
+
21
+
22
+ class AuthGate:
23
+ def __init__(self, ttl_seconds: float = 60.0, max_entries: int = DEFAULT_MAX_ENTRIES):
24
+ self._ttl = ttl_seconds
25
+ self._max = max_entries
26
+ self._cache: dict[str, tuple[float, bool]] = {}
27
+
28
+ def _key(self, bearer: str) -> str:
29
+ return hashlib.sha256(bearer.encode()).hexdigest()
30
+
31
+ def _evict(self, now: float) -> None:
32
+ """先清过期,再按最旧写入淘汰到上界以内。
33
+
34
+ 过期清理不是可有可无的:只做容量淘汰的话,TTL 短的条目会把还不该走的
35
+ 条目挤出去,白丢一次上游往返。
36
+ """
37
+ if len(self._cache) < self._max:
38
+ for k in [k for k, (ts, _) in self._cache.items() if now - ts >= self._ttl]:
39
+ self._cache.pop(k, None)
40
+ return
41
+ for k in [k for k, (ts, _) in self._cache.items() if now - ts >= self._ttl]:
42
+ self._cache.pop(k, None)
43
+ overflow = len(self._cache) - self._max + 1
44
+ if overflow > 0:
45
+ for k, _ in sorted(self._cache.items(), key=lambda kv: kv[1][0])[:overflow]:
46
+ self._cache.pop(k, None)
47
+
48
+ async def check(self, bearer: str | None) -> bool:
49
+ if not bearer:
50
+ return False
51
+ key = self._key(bearer)
52
+ now = time.monotonic()
53
+ hit = self._cache.get(key)
54
+ if hit and now - hit[0] < self._ttl:
55
+ return hit[1]
56
+ self._evict(now)
57
+ self._cache[key] = (now, True)
58
+ return True
59
+
60
+ @property
61
+ def cache_size(self) -> int:
62
+ """当前缓存条目数(测试与可观测用)。"""
63
+ return len(self._cache)
64
+
65
+
66
+ class AuthGateMiddleware:
67
+ """薄 ASGI 包装:仅拦 POST /mcp*,其余原样放行(/health 无门)。"""
68
+
69
+ def __init__(self, app, gate: AuthGate):
70
+ self.app = app
71
+ self.gate = gate
72
+
73
+ async def __call__(self, scope, receive, send):
74
+ if scope.get("type") != "http" or scope.get("method") != "POST":
75
+ await self.app(scope, receive, send)
76
+ return
77
+ path = (scope.get("path") or "").lstrip("/")
78
+ if path != "mcp" and not path.endswith("/mcp"):
79
+ await self.app(scope, receive, send)
80
+ return
81
+ bearer = bearer_from_scope(scope)
82
+ if await self.gate.check(bearer):
83
+ await self.app(scope, receive, send)
84
+ return
85
+ # 消掉上行 body 再应答,防连接悬挂:读到完整 request 或对端断开即止
86
+ while True:
87
+ msg = await receive()
88
+ if msg.get("type") == "http.disconnect":
89
+ return
90
+ if msg.get("type") == "http.request" and not msg.get("more_body", False):
91
+ break
92
+ await send(
93
+ {
94
+ "type": "http.response.start",
95
+ "status": 401,
96
+ "headers": [(b"content-type", b"application/json")],
97
+ }
98
+ )
99
+ await send(
100
+ {
101
+ "type": "http.response.body",
102
+ "body": b'{"error": "Authentication required"}',
103
+ }
104
+ )
105
+
106
+
107
+ #: Headers a bearer may arrive in. `authorization` is the standard one; the MCP
108
+ #: gateway in front of us forwards the caller's token upstream as
109
+ #: `x-authorization` (mcpgw `_get_registry_headers`) and advertises support for
110
+ #: both. Reading only the standard header rejected EVERY proxied call with
111
+ #: `401 {"error": "Authentication required"}` while a direct request passed —
112
+ #: live 2026-11-09: the wire/lex servers were dark behind the gateway and 17
113
+ #: packs declaring their tools could not run.
114
+ _BEARER_HEADERS = (b"authorization", b"x-authorization")
115
+
116
+
117
+ def bearer_from_scope(scope) -> str | None:
118
+ for name, value in scope.get("headers", []):
119
+ if name not in _BEARER_HEADERS:
120
+ continue
121
+ text = value.decode("latin-1")
122
+ if text.lower().startswith("bearer "):
123
+ token = text[7:].strip()
124
+ if token:
125
+ return token
126
+ return None
@@ -0,0 +1,121 @@
1
+ """Bearer 原样转发的上游客户端(共享实现)。
2
+
3
+ 各线保留自己的错误类名(`LexError` / `WireError` / `RegistryError`)——那是已发布的
4
+ 内部契约:工具层与测试按名字捕获它,改名会牵动 5 仓的测试与工具层。本模块接受一个
5
+ `error_cls` 参数,把「建错」交给调用方,公共部分(httpx、超时、状态码归类、不可达)
6
+ 收在这里。
7
+
8
+ 凭据只经手不落盘;连接失败 / 5xx 归为 unreachable——不冒充业务错误。
9
+ """
10
+ from __future__ import annotations
11
+
12
+ from typing import Any, Callable
13
+
14
+
15
+ class LineError(Exception):
16
+ """默认错误类:kind + status + 上游 detail 原文。
17
+
18
+ 各线可传入自己的类(签名须同为 `(kind, status, detail)`)。
19
+ """
20
+
21
+ def __init__(self, kind: str, status: int | None, detail: str):
22
+ super().__init__(f"[{kind}] {detail}" + (f" (HTTP {status})" if status else ""))
23
+ self.kind = kind
24
+ self.status = status
25
+ self.detail = detail
26
+
27
+
28
+ class LineClient:
29
+ """Bearer 原样转发 + 诚实错误映射。
30
+
31
+ :param base_url: 上游根地址
32
+ :param timeout_seconds: 请求超时
33
+ :param error_cls: 抛出的错误类,签名 `(kind, status, detail)`
34
+ :param service_label: 错误文本里的服务名(如「柏讯」);不可达时用
35
+ :param transport: 测试注入(httpx transport)
36
+ :param missing_hint: 无凭据时的提示语;None 则用通用文案
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ base_url: str,
42
+ timeout_seconds: float = 20.0,
43
+ transport=None,
44
+ *,
45
+ error_cls: Callable[[str, int | None, str], Exception] = LineError,
46
+ service_label: str = "上游",
47
+ missing_hint: str | None = None,
48
+ ):
49
+ # httpx 只在真正用客户端时才需要(protocol 的主依赖不含它);
50
+ # 延迟到这里 import,使「只 import line_ops.auth_gate」的消费方不必装 httpx。
51
+ import httpx
52
+ self._httpx = httpx
53
+ self._client = httpx.AsyncClient(
54
+ base_url=base_url, timeout=timeout_seconds, transport=transport
55
+ )
56
+ self._error = error_cls
57
+ self._label = service_label
58
+ self._missing_hint = missing_hint or f"缺少凭据:{service_label}需要 Bearer"
59
+
60
+ async def aclose(self):
61
+ await self._client.aclose()
62
+
63
+ async def request(
64
+ self,
65
+ method: str,
66
+ path: str,
67
+ *,
68
+ bearer: str | None,
69
+ params: dict | None = None,
70
+ json_body: Any | None = None,
71
+ ) -> Any:
72
+ if not bearer:
73
+ raise self._error("missing_credential", 401, self._missing_hint)
74
+ try:
75
+ res = await self._client.request(
76
+ method,
77
+ path,
78
+ headers={"Authorization": f"Bearer {bearer}"},
79
+ params=params,
80
+ json=json_body,
81
+ )
82
+ except self._httpx.HTTPError as e:
83
+ raise self._error(
84
+ "unreachable", None, f"{self._label}服务不可达:{type(e).__name__}: {e}"
85
+ ) from e
86
+ if res.status_code == 401:
87
+ raise self._error("unauthorized", 401, _detail(res))
88
+ if res.status_code == 402:
89
+ raise self._error("billing", 402, _detail(res))
90
+ if res.status_code == 403:
91
+ raise self._error("forbidden", 403, _detail(res))
92
+ if res.status_code == 404:
93
+ raise self._error("not_found", 404, _detail(res))
94
+ if res.status_code == 409:
95
+ raise self._error("conflict", 409, _detail(res))
96
+ if res.status_code == 422:
97
+ raise self._error("invalid", 422, _detail(res))
98
+ if res.status_code == 429:
99
+ raise self._error("rate_limited", 429, _detail(res))
100
+ if res.status_code >= 500:
101
+ raise self._error("unreachable", res.status_code, f"{self._label}服务错误:{_detail(res)}")
102
+ if res.status_code >= 400:
103
+ raise self._error("invalid", res.status_code, _detail(res))
104
+ if not res.content:
105
+ return None
106
+ try:
107
+ return res.json()
108
+ except ValueError:
109
+ return {"_raw": res.text}
110
+
111
+
112
+ def _detail(res) -> str:
113
+ try:
114
+ body = res.json()
115
+ if isinstance(body, dict) and "detail" in body:
116
+ return str(body["detail"])[:800]
117
+ if isinstance(body, dict) and "error" in body:
118
+ return str(body["error"])[:800]
119
+ return str(body)[:800]
120
+ except Exception: # noqa: BLE001
121
+ return (res.text or "")[:800] or f"HTTP {res.status_code}(无 body)"
@@ -0,0 +1,59 @@
1
+ """环境驱动的线配置(共享实现,前缀参数化)。
2
+
3
+ 五个 ops-mcp 仓的 `config.py` 除前缀与默认 base_url 外逐行相同:
4
+
5
+ base_url=(env.get("WIRE_OPS_BASE_URL") or cls.base_url).rstrip("/")
6
+ timeout_seconds=float(env.get("WIRE_OPS_TIMEOUT_SECONDS") or 20.0)
7
+ auth_cache_ttl_seconds=float(env.get("WIRE_OPS_AUTH_CACHE_TTL") or 60.0)
8
+
9
+ 本模块把「前缀 + 默认 base_url」参数化,其余不变。各仓仍可用自己的类名与
10
+ `from_env()`,只需 `make_settings_class()` 一次。
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ from dataclasses import dataclass
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class LineSettings:
20
+ """一条线的上游配置。字段名与五仓现状一致,便于平滑迁移。"""
21
+
22
+ base_url: str
23
+ timeout_seconds: float = 20.0
24
+ auth_cache_ttl_seconds: float = 60.0
25
+
26
+ @classmethod
27
+ def from_env(cls, env=None) -> "LineSettings":
28
+ raise NotImplementedError(
29
+ "LineSettings 是基类形态;请用 make_settings_class() 生成带前缀的子类")
30
+
31
+
32
+ def make_settings_class(env_prefix: str, default_base_url: str):
33
+ """生成一个带环境前缀的 Settings 类(与各仓既有 `Settings` 同形)。
34
+
35
+ :param env_prefix: 环境变量前缀,如 `"WIRE_OPS"`(读 `WIRE_OPS_BASE_URL` 等)
36
+ :param default_base_url: 三个环境变量都没设时的上游地址
37
+
38
+ 返回的类是 dataclass(frozen),`from_env()` 可注入 `env`(测试用)。
39
+ """
40
+ _class_name = f"{env_prefix.title().replace('_', '')}Settings"
41
+
42
+ @dataclass(frozen=True)
43
+ class _Settings:
44
+ base_url: str = default_base_url
45
+ timeout_seconds: float = 20.0
46
+ auth_cache_ttl_seconds: float = 60.0
47
+
48
+ @classmethod
49
+ def from_env(cls, env=None) -> "_Settings":
50
+ env = env if env is not None else os.environ
51
+ return cls(
52
+ base_url=(env.get(f"{env_prefix}_BASE_URL") or cls.base_url).rstrip("/"),
53
+ timeout_seconds=float(env.get(f"{env_prefix}_TIMEOUT_SECONDS") or 20.0),
54
+ auth_cache_ttl_seconds=float(env.get(f"{env_prefix}_AUTH_CACHE_TTL") or 60.0),
55
+ )
56
+
57
+ _Settings.__name__ = _class_name
58
+ _Settings.__qualname__ = _class_name
59
+ return _Settings
@@ -0,0 +1,67 @@
1
+ """线自描述端点 `/.well-known/line-manifest.json`(公开、免鉴权、零网络)。
2
+
3
+ 为什么在鉴权门**之前**应答:平台/客户在未持有本线凭据时,也要能读到「这条线认哪些
4
+ 钥匙」。放在门后会让未开通的客户连自描述都拿不到。
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import os
10
+ from pathlib import Path
11
+
12
+ WELL_KNOWN_PATH = "/.well-known/line-manifest.json"
13
+ LINE_MANIFEST_ENV = "LINE_MANIFEST_PATH"
14
+ #: 清单是运行期契约:改一次要生效,但不能让边缘缓存长期撒谎。
15
+ MANIFEST_CACHE_CONTROL = "public, max-age=300"
16
+
17
+
18
+ def manifest_candidates() -> list[Path]:
19
+ """按优先级列出可能放清单的位置(`LINE_MANIFEST_PATH` 一项即封顶)。
20
+
21
+ 为什么要链而不是一条:**pip 装进去的包与源码树的 `__file__` 不同**。镜像是
22
+ console script 起的,`__file__` 落在 site-packages,`parents[1]` 根本不是仓根——
23
+ 清单就在 `/app/line-manifest.json` 却读不到(lex 线 2026-11-11 真机 404,
24
+ 源码运行验不出来)。所以源码树、CWD(镜像 WORKDIR)、与包同级三处依次找。
25
+ """
26
+ override = os.environ.get(LINE_MANIFEST_ENV)
27
+ if override:
28
+ return [Path(override)]
29
+ here = Path(__file__).resolve()
30
+ return [
31
+ here.parents[1] / "line-manifest.json", # 源码树 / 镜像里包与清单同根
32
+ Path.cwd() / "line-manifest.json", # pip 装的包:CWD 才是仓根
33
+ here.parent / "line-manifest.json", # 清单与包同级(兜底)
34
+ ]
35
+
36
+
37
+ def manifest_path() -> Path:
38
+ """实际取用的清单路径;都不存在时返回首选位置(让 404 能点名期望路径)。"""
39
+ candidates = manifest_candidates()
40
+ for candidate in candidates:
41
+ if candidate.exists():
42
+ return candidate
43
+ return candidates[0]
44
+
45
+
46
+ def manifest_response() -> tuple[int, bytes, list[tuple[bytes, bytes]]]:
47
+ """(status, body, extra_headers) —— 不读网络、不建会话。
48
+
49
+ 缺失=404(该线未发布清单,属配置事实);存在但不可解析=500(属缺陷,不能
50
+ 伪装成 404 让调用方以为「本来就没有」)。
51
+ """
52
+ json_headers = [(b"content-type", b"application/json; charset=utf-8")]
53
+ path = manifest_path()
54
+ try:
55
+ raw = path.read_bytes()
56
+ except FileNotFoundError:
57
+ return 404, b'{"detail":"line-manifest not published"}', json_headers
58
+ except OSError as exc:
59
+ return 500, json.dumps(
60
+ {"detail": f"line-manifest unreadable: {type(exc).__name__}"}).encode(), json_headers
61
+ try:
62
+ json.loads(raw)
63
+ except ValueError:
64
+ return 500, b'{"detail":"line-manifest is not valid JSON"}', json_headers
65
+ return 200, raw, json_headers + [
66
+ (b"cache-control", MANIFEST_CACHE_CONTROL.encode()),
67
+ ]
@@ -0,0 +1,242 @@
1
+ """tool-surface manifest 的共享 selfcheck(mcp-surface-contract / mcp-surface-truth)。
2
+
3
+ ## 为什么存在
4
+
5
+ `scripts/selfcheck_surface.py` 在各仓是 ~55 行的近同副本(17 份),差异只在「怎么把
6
+ 服务建起来」那一行。同时它们的判据覆盖面**不一致**:只有 `fd-open-data-mcp` 那一份
7
+ 检查了「commercial 集内是否只含只读工具」,其余 16 份只做 manifest↔运行时双向比对。
8
+ 多份复制必然漂移——这是本工作区反复踩过的同一形状(`surface_report.py` 从三份逐仓
9
+ 副本抽成共享实现是同一判断)。
10
+
11
+ ## 四臂判据(与 `mcp-surface-contract`「selfcheck 双向断言」逐条对应)
12
+
13
+ 1. **甲|双向一致**:manifest 声明的工具集 == 运行时注册的工具集。多声明/多注册都红。
14
+ 存量:已全绿(17 仓副本都做这一臂)。
15
+ 2. **乙|commercial 只读**:`commercial` 集内每个工具的 `readOnlyHint` 为 true,或在
16
+ `rules.commercial_exemptions` 里登记并附理由。存量:只有 1 仓达标——故本臂按仓
17
+ 用基线上限(`#: 上限 N`)承接,只许变短。
18
+ 3. **丙|行为属性齐备**:每个工具在 `tool_annotations` 里声明四个 hint。存量:8 仓零
19
+ 声明——同乙臂,按仓登记上限。
20
+ 4. **丁|级别合法**:每组 `level` ∈ {commercial, internal};同一工具不得在两组间级别
21
+ 冲突。无存量问题,恒判。
22
+
23
+ ## 三档退出码
24
+
25
+ `0` 通过 / `1` 有缺陷 / `2` 判不出。**判不出明确不是缺陷**:运行时入口导入失败(依赖
26
+ 未装、venv 版本低于声明)时,回落到 manifest 自述会让「运行时从未被验证」看起来像
27
+ 通过(`audit-gate-can-check-the-wrong-machine`),所以宁可报判不出。
28
+
29
+ ## 用法
30
+
31
+ from fd_open_data_protocol.surface_selfcheck import run_selfcheck
32
+ raise SystemExit(run_selfcheck(
33
+ manifest_path=Path("tool-surface.json"),
34
+ repo_root=Path("."),
35
+ build_server=lambda: make_server(), # 返回一个 FastMCP 实例
36
+ ceilings={"ying_commercial_nonreadonly": 12, "bing_undeclared": 87},
37
+ ))
38
+
39
+ 各仓可以继续用自己的 `scripts/selfcheck_surface.py` 包一层(保持既有调用方式),内部
40
+ 改成调本模块。
41
+ """
42
+ from __future__ import annotations
43
+
44
+ import asyncio
45
+ import json
46
+ import sys
47
+ from dataclasses import dataclass, field
48
+ from pathlib import Path
49
+ from typing import Any, Callable
50
+
51
+ HINTS = ("readOnlyHint", "destructiveHint", "idempotentHint", "openWorldHint")
52
+
53
+ #: 两个「存量上限」臂的键名。语义:当前有多少个不合规项,只许变短。
54
+ CEIL_COMMERCIAL_NONREADONLY = "commercial_nonreadonly"
55
+ CEIL_UNDECLARED = "undeclared_annotations"
56
+
57
+
58
+ @dataclass
59
+ class Report:
60
+ repo: str
61
+ problems: list[str] = field(default_factory=list)
62
+ undecidable: list[str] = field(default_factory=list)
63
+ info: list[str] = field(default_factory=list)
64
+ counts: dict[str, int] = field(default_factory=dict)
65
+ #: 甲臂因环境限制被跳过时置真:使 code 仍为 0(其余臂通过),
66
+ #: 但输出里保留「这一臂没验」的事实(不把「验不了」写成「通过」)。
67
+ runtime_unverified: bool = False
68
+
69
+ @property
70
+ def code(self) -> int:
71
+ if self.problems:
72
+ return 1
73
+ if self.undecidable:
74
+ return 2
75
+ return 0
76
+
77
+
78
+ def _levels(manifest: dict) -> tuple[dict[str, str], list[str]]:
79
+ """丁臂:级别合法 + 无组间冲突。返回 (tool→level, problems)。"""
80
+ levels: dict[str, str] = {}
81
+ problems: list[str] = []
82
+ for g in manifest.get("tool_groups", []) or []:
83
+ lv = g.get("level")
84
+ if lv not in ("commercial", "internal"):
85
+ problems.append(f"tool_groups.{g.get('group')} 的 level 非法:{lv!r}")
86
+ continue
87
+ for t in g.get("tools", []) or []:
88
+ if t in levels and levels[t] != lv:
89
+ problems.append(f"工具 {t} 在多个 group 中级别冲突({levels[t]} vs {lv})")
90
+ levels[t] = lv
91
+ return levels, problems
92
+
93
+
94
+ def _declared_fallback(manifest: dict) -> set[str]:
95
+ """旧形状 `tools: [{name}]` 的声明集(只有本模块的甲臂会用到,判不出时不使用)。"""
96
+ out = set()
97
+ for t in manifest.get("tools", []) or []:
98
+ if isinstance(t, dict) and t.get("name"):
99
+ out.add(t["name"])
100
+ return out
101
+
102
+
103
+ def _runtime_names(build_server: Callable[[], Any]) -> tuple[set[str] | None, str | None]:
104
+ try:
105
+ server = build_server()
106
+ tools = asyncio.run(server.list_tools()) if not asyncio.iscoroutine(server) else asyncio.run(server.list_tools())
107
+ return {t.name for t in tools}, None
108
+ except Exception as exc: # noqa: BLE001
109
+ return None, f"{type(exc).__name__}: {exc}"
110
+
111
+
112
+ def evaluate(
113
+ *,
114
+ repo: str,
115
+ manifest: dict,
116
+ runtime: set[str] | None,
117
+ runtime_error: str | None,
118
+ ceilings: dict[str, int] | None = None,
119
+ ) -> Report:
120
+ """纯函数:给 manifest + 运行时工具集,产出报告。便于单测,无需起服务。"""
121
+ ceilings = ceilings or {}
122
+ r = Report(repo=repo)
123
+
124
+ levels, level_problems = _levels(manifest)
125
+ r.problems.extend(level_problems)
126
+ declared = set(levels) or _declared_fallback(manifest)
127
+
128
+ # ── 甲:双向一致 ──
129
+ if runtime is None:
130
+ r.undecidable.append(
131
+ f"运行时入口不可用({runtime_error})——无法验证 manifest↔运行时一致,判不出而非通过")
132
+ else:
133
+ extra = declared - runtime
134
+ missing = runtime - declared
135
+ if extra:
136
+ r.problems.append(f"manifest 多声明(代码未注册):{sorted(extra)}")
137
+ if missing:
138
+ r.problems.append(f"代码多注册(manifest 未声明):{sorted(missing)}")
139
+ r.counts["runtime_tools"] = len(runtime)
140
+
141
+ annotations: dict[str, Any] = manifest.get("tool_annotations") or {}
142
+ commercial = {t for t, lv in levels.items() if lv == "commercial"}
143
+
144
+ # ── 乙:commercial 只读(或豁免) ──
145
+ rules = manifest.get("rules") or {}
146
+ exemptions = rules.get("commercial_exemptions") or []
147
+ # 豁免必须带理由(mcp-surface-contract:「登记在商用豁免台账中并附一句理由」)。
148
+ # 只记工具名不写理由的豁免等于无理由放行——与「整体豁免」同形,故判缺陷。
149
+ exempt: set[str] = set()
150
+ for e in exemptions:
151
+ t = e.get("tool") if isinstance(e, dict) else None
152
+ reason = (e.get("reason") or "").strip() if isinstance(e, dict) else ""
153
+ if not t:
154
+ r.problems.append(f"commercial_exemptions 有条目缺 tool:{e!r}")
155
+ continue
156
+ if not reason:
157
+ r.problems.append(f"豁免 {t} 缺理由(修法:补一句「为什么它虽写仍可商用」)")
158
+ exempt.add(t)
159
+ nonreadonly: list[str] = []
160
+ for t in sorted(commercial):
161
+ a = annotations.get(t)
162
+ if not isinstance(a, dict):
163
+ continue # 无属性由丙臂计,不在乙臂重复计
164
+ if a.get("readOnlyHint") is not True and t not in exempt:
165
+ nonreadonly.append(t)
166
+ # rules.commercial_tools 与组级 level 的一致性(有 rules 时才查)
167
+ if rules.get("commercial_tools") is not None:
168
+ if set(rules["commercial_tools"]) != commercial:
169
+ r.problems.append("rules.commercial_tools 与组级 level=commercial 的工具集不一致")
170
+ r.counts[CEIL_COMMERCIAL_NONREADONLY] = len(nonreadonly)
171
+ ceil = ceilings.get(CEIL_COMMERCIAL_NONREADONLY)
172
+ if nonreadonly:
173
+ if ceil is None:
174
+ r.problems.append(
175
+ f"commercial 集含 {len(nonreadonly)} 个非只读且未豁免的工具:{nonreadonly}"
176
+ "(修法:补 rules.commercial_exemptions 并写理由,或移出 commercial;"
177
+ "存量可登记 ceilings.commercial_nonreadonly)")
178
+ elif len(nonreadonly) > ceil:
179
+ r.problems.append(
180
+ f"commercial 非只读工具数 {len(nonreadonly)} > 基线上限 {ceil}(只许变短):{nonreadonly}")
181
+ else:
182
+ r.info.append(f"commercial 非只读 {len(nonreadonly)}/{ceil}(基线上限,只许变短)")
183
+
184
+ # ── 丙:行为属性齐备 ──
185
+ undeclared = sorted(t for t in declared if not isinstance(annotations.get(t), dict))
186
+ r.counts[CEIL_UNDECLARED] = len(undeclared)
187
+ ceil_c = ceilings.get(CEIL_UNDECLARED)
188
+ if undeclared:
189
+ if ceil_c is None:
190
+ r.problems.append(
191
+ f"{len(undeclared)} 个工具未声明行为属性(tool_annotations):{undeclared[:10]}"
192
+ + ("…" if len(undeclared) > 10 else "")
193
+ + "(存量可登记 ceilings.undeclared_annotations)")
194
+ elif len(undeclared) > ceil_c:
195
+ r.problems.append(
196
+ f"未声明行为属性的工具数 {len(undeclared)} > 基线上限 {ceil_c}(只许变短)")
197
+ else:
198
+ r.info.append(f"未声明行为属性 {len(undeclared)}/{ceil_c}(基线上限,只许变短)")
199
+
200
+ # ── 补充:已声明者的 hint 必须齐四个键 ──
201
+ for t, a in sorted(annotations.items()):
202
+ if isinstance(a, dict):
203
+ miss = [h for h in HINTS if h not in a]
204
+ if miss:
205
+ r.problems.append(f"{t}: tool_annotations 缺 hint {miss}")
206
+ return r
207
+
208
+
209
+ def run_selfcheck(
210
+ *,
211
+ manifest_path: Path,
212
+ repo_root: Path,
213
+ build_server: Callable[[], Any] | None,
214
+ ceilings: dict[str, int] | None = None,
215
+ repo: str | None = None,
216
+ ) -> int:
217
+ """走完整流程:读 manifest → 建服务枚举运行时 → evaluate → 打印 → 返回退出码。"""
218
+ name = repo or repo_root.resolve().name
219
+ if not manifest_path.is_file():
220
+ print(f"SELFCHECK FAIL [{name}]: manifest 缺失:{manifest_path}(契约:缺失即未上牌)")
221
+ return 1
222
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
223
+
224
+ runtime: set[str] | None = None
225
+ runtime_error: str | None = None
226
+ if build_server is not None:
227
+ if str(repo_root) not in sys.path:
228
+ sys.path.insert(0, str(repo_root))
229
+ runtime, runtime_error = _runtime_names(build_server)
230
+
231
+ r = evaluate(repo=name, manifest=manifest, runtime=runtime,
232
+ runtime_error=runtime_error, ceilings=ceilings)
233
+
234
+ tag = {0: "PASS", 1: "FAIL", 2: "UNDECIDABLE"}[r.code]
235
+ print(f"SELFCHECK {tag} [{name}]: {r.counts.get('runtime_tools', '?')} 运行时工具")
236
+ for p in r.problems:
237
+ print(f" ✗ {p}")
238
+ for p in r.undecidable:
239
+ print(f" ? {p}")
240
+ for p in r.info:
241
+ print(f" · {p}")
242
+ return r.code
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fd-open-data-protocol
3
- Version: 0.4.0
3
+ Version: 0.5.0
4
4
  Summary: The open-data datasource protocol: a manifest contract a datasource exposes to be ingested by fd-open-data-mcp (or any consumer).
5
5
  Author: FindDataOfficial
6
6
  License: MIT
@@ -13,6 +13,8 @@ Provides-Extra: dev
13
13
  Requires-Dist: pytest>=8.0; extra == "dev"
14
14
  Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
15
15
  Requires-Dist: httpx>=0.27; extra == "dev"
16
+ Provides-Extra: line-ops
17
+ Requires-Dist: httpx>=0.27; extra == "line-ops"
16
18
  Provides-Extra: registry
17
19
  Requires-Dist: psycopg[binary]>=3.1; extra == "registry"
18
20
  Dynamic: license-file
@@ -12,6 +12,7 @@ fd_open_data_protocol/registry_cli.py
12
12
  fd_open_data_protocol/registry_store.py
13
13
  fd_open_data_protocol/schema.py
14
14
  fd_open_data_protocol/surface_report.py
15
+ fd_open_data_protocol/surface_selfcheck.py
15
16
  fd_open_data_protocol/vocabulary.py
16
17
  fd_open_data_protocol.egg-info/PKG-INFO
17
18
  fd_open_data_protocol.egg-info/SOURCES.txt
@@ -19,6 +20,12 @@ fd_open_data_protocol.egg-info/dependency_links.txt
19
20
  fd_open_data_protocol.egg-info/entry_points.txt
20
21
  fd_open_data_protocol.egg-info/requires.txt
21
22
  fd_open_data_protocol.egg-info/top_level.txt
23
+ fd_open_data_protocol/line_ops/__init__.py
24
+ fd_open_data_protocol/line_ops/assemble.py
25
+ fd_open_data_protocol/line_ops/auth_gate.py
26
+ fd_open_data_protocol/line_ops/client.py
27
+ fd_open_data_protocol/line_ops/config.py
28
+ fd_open_data_protocol/line_ops/wellknown.py
22
29
  fd_open_data_protocol/vocabulary/concepts.yaml
23
30
  fd_open_data_protocol/vocabulary/entity_types.yaml
24
31
  fd_open_data_protocol/vocabulary/event_types.yaml
@@ -27,11 +34,13 @@ fd_open_data_protocol/vocabulary/relation_types.yaml
27
34
  fd_open_data_protocol/vocabulary/units.yaml
28
35
  fd_open_data_protocol/vocabulary/alignment/foundation.yaml
29
36
  fd_open_data_protocol/vocabulary/crosswalks/datacommons-worldbank.yaml
37
+ tests/test_line_ops.py
30
38
  tests/test_loader.py
31
39
  tests/test_openalex_provider.py
32
40
  tests/test_registry_pipeline.py
33
41
  tests/test_registry_schema.py
34
42
  tests/test_schema_vocabulary.py
35
43
  tests/test_surface_report.py
44
+ tests/test_surface_selfcheck.py
36
45
  tests/test_vocabulary.py
37
46
  tests/test_vocabulary_additive.py
@@ -6,5 +6,8 @@ pytest>=8.0
6
6
  pytest-asyncio>=0.23
7
7
  httpx>=0.27
8
8
 
9
+ [line-ops]
10
+ httpx>=0.27
11
+
9
12
  [registry]
10
13
  psycopg[binary]>=3.1
@@ -17,6 +17,9 @@ dependencies = [
17
17
 
18
18
  [project.optional-dependencies]
19
19
  dev = ["pytest>=8.0", "pytest-asyncio>=0.23", "httpx>=0.27"]
20
+ # 线操作 MCP 的共享运行时(fd_open_data_protocol.line_ops.client)需要 httpx;
21
+ # auth_gate / config / wellknown 不需要。消费仓装上这个 extra 即可。
22
+ line-ops = ["httpx>=0.27"]
20
23
  registry = ["psycopg[binary]>=3.1"]
21
24
 
22
25
  [tool.pytest.ini_options]
@@ -0,0 +1,132 @@
1
+ """line_ops 共享运行时的测试(line-ops-runtime-core 的四条要求)。"""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+
6
+ from fd_open_data_protocol.line_ops import (
7
+ AuthGate,
8
+ AuthGateMiddleware,
9
+ bearer_from_scope,
10
+ make_settings_class,
11
+ )
12
+
13
+
14
+ # ── 有界缓存 ──────────────────────────────────────────────────────────────
15
+
16
+ def test_cache_is_bounded_under_many_bearers():
17
+ """灌远超上界的 bearer,缓存条目数不超过上界(这是 wire-ops 2026-11-09 的实测缺陷)。"""
18
+ gate = AuthGate(ttl_seconds=60.0, max_entries=100)
19
+ for i in range(5000):
20
+ asyncio.run(gate.check(f"token-{i}"))
21
+ assert gate.cache_size <= 100, gate.cache_size
22
+
23
+
24
+ def test_expired_entries_evicted_before_live_ones():
25
+ gate = AuthGate(ttl_seconds=0.0001, max_entries=10)
26
+ asyncio.run(gate.check("old"))
27
+ import time
28
+ time.sleep(0.01) # 让它过期
29
+ for i in range(9):
30
+ asyncio.run(gate.check(f"live-{i}"))
31
+ # 过期条目应被清掉,live 的仍在
32
+ assert gate.cache_size <= 9
33
+
34
+
35
+ def test_cache_key_is_irreversible():
36
+ gate = AuthGate()
37
+ key = gate._key("secret-token-value")
38
+ assert "secret-token-value" not in key
39
+ assert len(key) == 64 # sha256 hex
40
+
41
+
42
+ # ── 门的语义 ──────────────────────────────────────────────────────────────
43
+
44
+ def test_no_bearer_is_rejected():
45
+ gate = AuthGate()
46
+ assert asyncio.run(gate.check(None)) is False
47
+ assert asyncio.run(gate.check("")) is False
48
+
49
+
50
+ def test_any_bearer_passes_gate():
51
+ """门的语义:有 Bearer 放行(真伪由上游权威判)。"""
52
+ gate = AuthGate()
53
+ assert asyncio.run(gate.check("anything")) is True
54
+
55
+
56
+ def test_bearer_from_x_authorization_header():
57
+ """网关把调用方 token 以 x-authorization 转发;只读标准头会让全部代理调用 401。"""
58
+ scope = {"headers": [(b"x-authorization", b"Bearer proxied-token")]}
59
+ assert bearer_from_scope(scope) == "proxied-token"
60
+
61
+
62
+ def test_bearer_from_standard_header():
63
+ scope = {"headers": [(b"authorization", b"Bearer direct-token")]}
64
+ assert bearer_from_scope(scope) == "direct-token"
65
+
66
+
67
+ def test_401_response_does_not_echo_credential():
68
+ """错误响应体内不出现凭据任何部分(line-ops-runtime-core「凭据不落日志」)。"""
69
+ sent = []
70
+
71
+ async def app(scope, receive, send):
72
+ raise AssertionError("不该放行")
73
+
74
+ async def receive():
75
+ return {"type": "http.request", "more_body": False}
76
+
77
+ async def send(msg):
78
+ sent.append(msg)
79
+
80
+ mw = AuthGateMiddleware(app, AuthGate())
81
+ scope = {"type": "http", "method": "POST", "path": "/mcp",
82
+ "headers": [(b"authorization", b"Bearer ")]} # 空 token ⇒ 拒
83
+ asyncio.run(mw(scope, receive, send))
84
+ body = b"".join(m.get("body", b"") for m in sent)
85
+ assert b"Authentication required" in body
86
+ assert b"Bearer" not in body
87
+
88
+
89
+ def test_health_path_bypasses_gate():
90
+ """非 /mcp 路径不走门(/health 无门)。"""
91
+ calls = []
92
+
93
+ async def app(scope, receive, send):
94
+ calls.append(scope.get("path"))
95
+
96
+ async def receive():
97
+ return {"type": "http.request"}
98
+
99
+ async def send(msg):
100
+ pass
101
+
102
+ mw = AuthGateMiddleware(app, AuthGate())
103
+ asyncio.run(mw({"type": "http", "method": "POST", "path": "/health", "headers": []},
104
+ receive, send))
105
+ assert calls == ["/health"]
106
+
107
+
108
+ # ── 配置 ──────────────────────────────────────────────────────────────────
109
+
110
+ def test_settings_prefix_and_defaults():
111
+ S = make_settings_class("WIRE_OPS", "https://wire.finddatatech.cloud")
112
+ s = S.from_env({})
113
+ assert s.base_url == "https://wire.finddatatech.cloud"
114
+ assert s.timeout_seconds == 20.0
115
+ assert s.auth_cache_ttl_seconds == 60.0
116
+
117
+
118
+ def test_settings_reads_prefixed_env_and_strips_slash():
119
+ S = make_settings_class("LEX_OPS", "https://lex.finddatatech.cloud")
120
+ s = S.from_env({"LEX_OPS_BASE_URL": "http://127.0.0.1:8000/",
121
+ "LEX_OPS_TIMEOUT_SECONDS": "5",
122
+ "LEX_OPS_AUTH_CACHE_TTL": "30"})
123
+ assert s.base_url == "http://127.0.0.1:8000" # 尾斜杠去掉
124
+ assert s.timeout_seconds == 5.0
125
+ assert s.auth_cache_ttl_seconds == 30.0
126
+
127
+
128
+ def test_two_lines_dont_share_env():
129
+ W = make_settings_class("WIRE_OPS", "https://wire.example")
130
+ L = make_settings_class("LEX_OPS", "https://lex.example")
131
+ assert W.from_env({"LEX_OPS_BASE_URL": "https://lex.example"}).base_url == "https://wire.example"
132
+ assert L.from_env({"WIRE_OPS_BASE_URL": "https://wire.example"}).base_url == "https://lex.example"
@@ -0,0 +1,129 @@
1
+ """surface_selfcheck 四臂判据的单测(纯 evaluate,不起服务)。"""
2
+ from __future__ import annotations
3
+
4
+ from fd_open_data_protocol.surface_selfcheck import evaluate
5
+
6
+ RO = {"readOnlyHint": True, "destructiveHint": False, "idempotentHint": True, "openWorldHint": False}
7
+ RW = {"readOnlyHint": False, "destructiveHint": False, "idempotentHint": True, "openWorldHint": False}
8
+
9
+
10
+ def _m(groups, annotations=None, rules=None):
11
+ m = {"tool_groups": groups}
12
+ if annotations is not None:
13
+ m["tool_annotations"] = annotations
14
+ if rules is not None:
15
+ m["rules"] = rules
16
+ return m
17
+
18
+
19
+ def test_clean_manifest_passes():
20
+ m = _m([{"group": "read", "level": "commercial", "tools": ["a"]}], {"a": RO})
21
+ r = evaluate(repo="x", manifest=m, runtime={"a"}, runtime_error=None)
22
+ assert r.code == 0, r.problems
23
+
24
+
25
+ def test_jia_multi_declared_and_multi_registered():
26
+ m = _m([{"group": "read", "level": "commercial", "tools": ["a", "b"]}], {"a": RO, "b": RO})
27
+ r = evaluate(repo="x", manifest=m, runtime={"a", "c"}, runtime_error=None)
28
+ assert r.code == 1
29
+ assert any("多声明" in p and "b" in p for p in r.problems)
30
+ assert any("多注册" in p and "c" in p for p in r.problems)
31
+
32
+
33
+ def test_jia_undecidable_is_not_a_defect():
34
+ m = _m([{"group": "read", "level": "commercial", "tools": ["a"]}], {"a": RO})
35
+ r = evaluate(repo="x", manifest=m, runtime=None, runtime_error="ModuleNotFoundError: fastmcp")
36
+ assert r.code == 2, "判不出必须与缺陷分档"
37
+ assert not r.problems
38
+ assert any("fastmcp" in u for u in r.undecidable)
39
+
40
+
41
+ def test_yi_commercial_nonreadonly_without_ceiling_fails():
42
+ m = _m([{"group": "w", "level": "commercial", "tools": ["w"]}], {"w": RW})
43
+ r = evaluate(repo="x", manifest=m, runtime={"w"}, runtime_error=None)
44
+ assert r.code == 1
45
+ assert any("非只读" in p for p in r.problems)
46
+
47
+
48
+ def test_yi_exemption_allows_write_tool():
49
+ m = _m([{"group": "w", "level": "commercial", "tools": ["w"]}], {"w": RW},
50
+ rules={"commercial_exemptions": [{"tool": "w", "reason": "缓存写,不改数据"}]})
51
+ r = evaluate(repo="x", manifest=m, runtime={"w"}, runtime_error=None)
52
+ assert r.code == 0, r.problems
53
+
54
+
55
+ def test_yi_ceiling_lets_legacy_through_but_caps_growth():
56
+ m = _m([{"group": "w", "level": "commercial", "tools": ["w", "v"]}], {"w": RW, "v": RW})
57
+ ok = evaluate(repo="x", manifest=m, runtime={"w", "v"}, runtime_error=None,
58
+ ceilings={"commercial_nonreadonly": 2})
59
+ assert ok.code == 0, ok.problems
60
+ assert any("2/2" in i for i in ok.info)
61
+ # 上限 1 而实际 2 ⇒ 红(该臂只许变短)
62
+ bad = evaluate(repo="x", manifest=m, runtime={"w", "v"}, runtime_error=None,
63
+ ceilings={"commercial_nonreadonly": 1})
64
+ assert bad.code == 1
65
+
66
+
67
+ def test_bing_undeclared_annotations_ceiling():
68
+ m = _m([{"group": "read", "level": "commercial", "tools": ["a", "b"]}], None)
69
+ # 无 tool_annotations 字段 ⇒ 两个都未声明
70
+ r = evaluate(repo="x", manifest=m, runtime={"a", "b"}, runtime_error=None)
71
+ assert r.code == 1 and r.counts["undeclared_annotations"] == 2
72
+ ok = evaluate(repo="x", manifest=m, runtime={"a", "b"}, runtime_error=None,
73
+ ceilings={"undeclared_annotations": 2})
74
+ assert ok.code == 0, ok.problems
75
+
76
+
77
+ def test_partial_hint_set_fails():
78
+ m = _m([{"group": "read", "level": "commercial", "tools": ["a"]}],
79
+ {"a": {"readOnlyHint": True, "destructiveHint": False}})
80
+ r = evaluate(repo="x", manifest=m, runtime={"a"}, runtime_error=None)
81
+ assert r.code == 1
82
+ assert any("缺 hint" in p for p in r.problems)
83
+
84
+
85
+ def test_ding_illegal_level_and_group_conflict():
86
+ m = _m([
87
+ {"group": "a", "level": "bogus", "tools": ["x"]},
88
+ {"group": "b", "level": "commercial", "tools": ["y"]},
89
+ {"group": "c", "level": "internal", "tools": ["y"]},
90
+ ], {"x": RO, "y": RO})
91
+ r = evaluate(repo="x", manifest=m, runtime={"x", "y"}, runtime_error=None)
92
+ assert any("level 非法" in p for p in r.problems)
93
+ assert any("级别冲突" in p for p in r.problems)
94
+
95
+
96
+ def test_rules_commercial_tools_must_match_groups():
97
+ m = _m([{"group": "read", "level": "commercial", "tools": ["a"]}], {"a": RO},
98
+ rules={"commercial_tools": ["a", "zzz"]})
99
+ r = evaluate(repo="x", manifest=m, runtime={"a"}, runtime_error=None)
100
+ assert any("rules.commercial_tools" in p for p in r.problems)
101
+
102
+
103
+ def test_legacy_tools_shape_is_read():
104
+ m = {"tools": [{"name": "a"}, {"name": "b"}], "tool_annotations": {"a": RO, "b": RO}}
105
+ r = evaluate(repo="x", manifest=m, runtime={"a", "b"}, runtime_error=None)
106
+ # 旧形状无 tool_groups ⇒ 无 commercial 集;甲臂仍应通过
107
+ assert r.code == 0, r.problems
108
+
109
+
110
+ def test_exemption_without_reason_fails():
111
+ """豁免必须带理由——只记工具名的豁免等于无理由放行。"""
112
+ m = _m([{"group": "w", "level": "commercial", "tools": ["w"]}], {"w": RW},
113
+ rules={"commercial_exemptions": [{"tool": "w"}]})
114
+ r = evaluate(repo="x", manifest=m, runtime={"w"}, runtime_error=None)
115
+ assert r.code == 1
116
+ assert any("缺理由" in p for p in r.problems)
117
+
118
+
119
+ def test_internal_write_tool_not_in_commercial_arm():
120
+ m = _m([{"group": "adm", "level": "internal", "tools": ["del"]}], {"del": RW})
121
+ r = evaluate(repo="x", manifest=m, runtime={"del"}, runtime_error=None)
122
+ assert r.code == 0, r.problems
123
+
124
+
125
+ def test_ceiling_breach_fails():
126
+ m = _m([{"group": "w", "level": "commercial", "tools": ["a", "b"]}], {"a": RW, "b": RW})
127
+ r = evaluate(repo="x", manifest=m, runtime={"a", "b"}, runtime_error=None,
128
+ ceilings={"commercial_nonreadonly": 1})
129
+ assert r.code == 1 and any("基线上限" in p for p in r.problems)