fd-open-data-protocol 0.3.2__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.5.0/LICENSE +21 -0
  2. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/PKG-INFO +7 -1
  3. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/__init__.py +1 -1
  4. fd_open_data_protocol-0.5.0/fd_open_data_protocol/conformance_adapter.py +115 -0
  5. fd_open_data_protocol-0.5.0/fd_open_data_protocol/line_ops/__init__.py +44 -0
  6. fd_open_data_protocol-0.5.0/fd_open_data_protocol/line_ops/assemble.py +71 -0
  7. fd_open_data_protocol-0.5.0/fd_open_data_protocol/line_ops/auth_gate.py +126 -0
  8. fd_open_data_protocol-0.5.0/fd_open_data_protocol/line_ops/client.py +121 -0
  9. fd_open_data_protocol-0.5.0/fd_open_data_protocol/line_ops/config.py +59 -0
  10. fd_open_data_protocol-0.5.0/fd_open_data_protocol/line_ops/wellknown.py +67 -0
  11. fd_open_data_protocol-0.5.0/fd_open_data_protocol/surface_report.py +167 -0
  12. fd_open_data_protocol-0.5.0/fd_open_data_protocol/surface_selfcheck.py +242 -0
  13. fd_open_data_protocol-0.5.0/fd_open_data_protocol/vocabulary/alignment/foundation.yaml +65 -0
  14. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/vocabulary/concepts.yaml +135 -0
  15. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/vocabulary/entity_types.yaml +45 -0
  16. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/vocabulary.py +145 -3
  17. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol.egg-info/PKG-INFO +7 -1
  18. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol.egg-info/SOURCES.txt +16 -1
  19. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol.egg-info/requires.txt +5 -0
  20. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/pyproject.toml +15 -2
  21. fd_open_data_protocol-0.5.0/tests/test_line_ops.py +132 -0
  22. fd_open_data_protocol-0.5.0/tests/test_surface_report.py +209 -0
  23. fd_open_data_protocol-0.5.0/tests/test_surface_selfcheck.py +129 -0
  24. fd_open_data_protocol-0.5.0/tests/test_vocabulary_additive.py +184 -0
  25. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/README.md +0 -0
  26. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/constants.py +0 -0
  27. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/loader.py +0 -0
  28. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/openalex_provider.py +0 -0
  29. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/provider.py +0 -0
  30. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/registry.py +0 -0
  31. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/registry_cli.py +0 -0
  32. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/registry_store.py +0 -0
  33. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/schema.py +0 -0
  34. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/vocabulary/crosswalks/datacommons-worldbank.yaml +0 -0
  35. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/vocabulary/event_types.yaml +0 -0
  36. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/vocabulary/qualifiers.yaml +0 -0
  37. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/vocabulary/relation_types.yaml +0 -0
  38. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol/vocabulary/units.yaml +0 -0
  39. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol.egg-info/dependency_links.txt +0 -0
  40. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol.egg-info/entry_points.txt +0 -0
  41. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/fd_open_data_protocol.egg-info/top_level.txt +0 -0
  42. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/setup.cfg +0 -0
  43. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/tests/test_loader.py +0 -0
  44. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/tests/test_openalex_provider.py +0 -0
  45. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/tests/test_registry_pipeline.py +0 -0
  46. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/tests/test_registry_schema.py +0 -0
  47. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/tests/test_schema_vocabulary.py +0 -0
  48. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.5.0}/tests/test_vocabulary.py +0 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 FindData Technology
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,17 +1,23 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fd-open-data-protocol
3
- Version: 0.3.2
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
7
7
  Requires-Python: >=3.10
8
8
  Description-Content-Type: text/markdown
9
+ License-File: LICENSE
9
10
  Requires-Dist: pydantic>=2.0
10
11
  Requires-Dist: pyyaml>=6.0
11
12
  Provides-Extra: dev
12
13
  Requires-Dist: pytest>=8.0; extra == "dev"
14
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
15
+ Requires-Dist: httpx>=0.27; extra == "dev"
16
+ Provides-Extra: line-ops
17
+ Requires-Dist: httpx>=0.27; extra == "line-ops"
13
18
  Provides-Extra: registry
14
19
  Requires-Dist: psycopg[binary]>=3.1; extra == "registry"
20
+ Dynamic: license-file
15
21
 
16
22
  # fd-open-data-protocol
17
23
 
@@ -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.3.2"
8
+ __version__ = "0.5.0"
@@ -0,0 +1,115 @@
1
+ """Conformance adapter for the open-data vocabulary (task 7.3).
2
+
3
+ The protocol library has no storage of its own — its "ontology" is a versioned
4
+ YAML vocabulary — so the sandbox wires the kernel to an in-memory store whose
5
+ closed vocabulary *is* the shipped release. That is enough to run every check
6
+ that does not need a database, and it exercises the parts this library actually
7
+ owns: closed sets, additive releases and stable URIs.
8
+
9
+ The adapter lives here (not in the library's runtime path) because it needs the
10
+ kernel: the library itself keeps the kernel optional so it still installs in
11
+ environments that never see this workspace.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from fd_ontology_kernel.contracts import Unit
17
+ from fd_ontology_kernel.kernel import AdapterDeclaration, Kernel
18
+ from fd_ontology_kernel.memory import (
19
+ MemoryJournal,
20
+ MemoryProposalBox,
21
+ MemoryPublicationStore,
22
+ MemoryRegistry,
23
+ MemoryUnitStore,
24
+ )
25
+ from fd_ontology_kernel.vocab import Entry, Vocabulary, VocabularySet
26
+
27
+ from .vocabulary import load_vocabulary, to_kernel_vocabulary
28
+
29
+ DECLARATION = AdapterDeclaration(
30
+ system="fd-open-data-protocol",
31
+ kernel_contract="1.0",
32
+ manifest_shape=2,
33
+ )
34
+
35
+
36
+ def _contract_vocabulary() -> Vocabulary:
37
+ """The shipped release, renamed onto the kernel's two contract set names.
38
+
39
+ The kernel contract asks every surface for ``entity_types`` and
40
+ ``relationship_kinds``; this registry calls them ``entity-type`` and
41
+ ``relation-type``. Renaming here (rather than special-casing the kernel) keeps
42
+ one vocabulary and one closed-set rule.
43
+ """
44
+ registry = load_vocabulary()
45
+ base = to_kernel_vocabulary(registry)
46
+ sets = dict(base.sets)
47
+
48
+ def _renamed(source: str, target: str) -> VocabularySet | None:
49
+ hold = sets.get(source)
50
+ if hold is None:
51
+ return None
52
+ return VocabularySet(
53
+ name=target,
54
+ values=hold.values,
55
+ entries={
56
+ entry_id: Entry(
57
+ id=entry_id,
58
+ set_name=target,
59
+ label_en=entry.label_en,
60
+ label_zh=entry.label_zh,
61
+ description=entry.description,
62
+ superseded_by=entry.superseded_by,
63
+ )
64
+ for entry_id, entry in hold.entries.items()
65
+ },
66
+ )
67
+
68
+ entity_types = _renamed("entity-type", "entity_types")
69
+ relationship_kinds = _renamed("relation-type", "relationship_kinds")
70
+ if entity_types is not None:
71
+ sets["entity_types"] = entity_types
72
+ if relationship_kinds is not None:
73
+ sets["relationship_kinds"] = relationship_kinds
74
+
75
+ return Vocabulary(release=base.release, sets=sets)
76
+
77
+
78
+ class _VocabularySource:
79
+ def __init__(self, vocabulary: Vocabulary) -> None:
80
+ self._vocabulary = vocabulary
81
+
82
+ def load(self, *, scope_id: str) -> Vocabulary:
83
+ return self._vocabulary
84
+
85
+
86
+ def _sandbox() -> Kernel:
87
+ vocabulary = _contract_vocabulary()
88
+ relationship_hold = vocabulary.sets.get("relationship_kinds")
89
+ return Kernel(
90
+ units=MemoryUnitStore(),
91
+ events=MemoryJournal(),
92
+ vocabulary=_VocabularySource(vocabulary),
93
+ proposals=MemoryProposalBox(),
94
+ publications=MemoryPublicationStore(),
95
+ distribution=MemoryRegistry(),
96
+ relationship_kinds=tuple(relationship_hold.values) if relationship_hold else (),
97
+ # This vocabulary has no clause concept; the clause-parent rule is
98
+ # vacuous here and the suite reports it as skipped, not as passed.
99
+ clause_kinds=(),
100
+ manifest_shape=DECLARATION.manifest_shape,
101
+ declaration=DECLARATION,
102
+ )
103
+
104
+
105
+ def build():
106
+ """Factory named by ``adapters.json``."""
107
+ from fd_ontology_kernel.conformance.spec import AdapterSpec
108
+
109
+ return AdapterSpec(
110
+ name="fd-open-data-protocol",
111
+ system=DECLARATION.system,
112
+ declaration=DECLARATION,
113
+ sandbox=_sandbox,
114
+ notes="YAML vocabulary surface; sandbox is an in-memory store over the shipped release",
115
+ )
@@ -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
+ ]