fd-open-data-protocol 0.3.1__tar.gz → 0.4.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.
- fd_open_data_protocol-0.4.0/LICENSE +21 -0
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/PKG-INFO +5 -1
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/__init__.py +1 -1
- fd_open_data_protocol-0.4.0/fd_open_data_protocol/conformance_adapter.py +115 -0
- fd_open_data_protocol-0.4.0/fd_open_data_protocol/openalex_provider.py +213 -0
- fd_open_data_protocol-0.4.0/fd_open_data_protocol/surface_report.py +167 -0
- fd_open_data_protocol-0.4.0/fd_open_data_protocol/vocabulary/alignment/foundation.yaml +65 -0
- fd_open_data_protocol-0.4.0/fd_open_data_protocol/vocabulary/concepts.yaml +426 -0
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/vocabulary/crosswalks/datacommons-worldbank.yaml +1 -1
- fd_open_data_protocol-0.4.0/fd_open_data_protocol/vocabulary/entity_types.yaml +221 -0
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/vocabulary/event_types.yaml +1 -1
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/vocabulary/qualifiers.yaml +1 -1
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/vocabulary/relation_types.yaml +46 -1
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/vocabulary/units.yaml +8 -1
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/vocabulary.py +145 -3
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol.egg-info/PKG-INFO +5 -1
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol.egg-info/SOURCES.txt +9 -1
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol.egg-info/requires.txt +2 -0
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/pyproject.toml +12 -2
- fd_open_data_protocol-0.4.0/tests/test_openalex_provider.py +170 -0
- fd_open_data_protocol-0.4.0/tests/test_surface_report.py +209 -0
- fd_open_data_protocol-0.4.0/tests/test_vocabulary_additive.py +184 -0
- fd_open_data_protocol-0.3.1/fd_open_data_protocol/vocabulary/concepts.yaml +0 -230
- fd_open_data_protocol-0.3.1/fd_open_data_protocol/vocabulary/entity_types.yaml +0 -99
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/README.md +0 -0
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/constants.py +0 -0
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/loader.py +0 -0
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/provider.py +0 -0
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/registry.py +0 -0
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/registry_cli.py +0 -0
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/registry_store.py +0 -0
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/schema.py +0 -0
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol.egg-info/dependency_links.txt +0 -0
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol.egg-info/entry_points.txt +0 -0
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol.egg-info/top_level.txt +0 -0
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/setup.cfg +0 -0
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/tests/test_loader.py +0 -0
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/tests/test_registry_pipeline.py +0 -0
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/tests/test_registry_schema.py +0 -0
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.0}/tests/test_schema_vocabulary.py +0 -0
- {fd_open_data_protocol-0.3.1 → fd_open_data_protocol-0.4.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,21 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: fd-open-data-protocol
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.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"
|
|
13
16
|
Provides-Extra: registry
|
|
14
17
|
Requires-Dist: psycopg[binary]>=3.1; extra == "registry"
|
|
18
|
+
Dynamic: license-file
|
|
15
19
|
|
|
16
20
|
# fd-open-data-protocol
|
|
17
21
|
|
|
@@ -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,213 @@
|
|
|
1
|
+
"""OpenAlex 学术图谱数据源 provider(CC0,免费)。
|
|
2
|
+
|
|
3
|
+
契约要点(对应 academic-graph-connector spec):
|
|
4
|
+
- 礼貌调用:请求带含 mail 的 User-Agent(免费档 1000 credits/次级)
|
|
5
|
+
- 失败显式:配额/限流/不可达分别报错,**禁止返回空结果冒充无数据**
|
|
6
|
+
- 收录偏差:未收录如实标注,不断言「不存在引用」
|
|
7
|
+
- 引用图是增益,不替代既有 papers 检索
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import urllib.error
|
|
14
|
+
import urllib.parse
|
|
15
|
+
import urllib.request
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from .provider import BaseDataProvider
|
|
19
|
+
|
|
20
|
+
API = "https://api.openalex.org"
|
|
21
|
+
DEFAULT_MAILTO = os.environ.get("OPENALEX_MAILTO", "ops@finddata.dev")
|
|
22
|
+
TIMEOUT = float(os.environ.get("OPENALEX_TIMEOUT", "25"))
|
|
23
|
+
|
|
24
|
+
# 礼貌调用:OpenAlex 要求可识别的 User-Agent(含 mail),否则可能被限流
|
|
25
|
+
UA = f"finddata-academic-connector/1.0 (mailto:{DEFAULT_MAILTO})"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class OpenAlexUnavailable(RuntimeError):
|
|
29
|
+
"""上游不可用/不可达——显式失败,不静默返回空。"""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class OpenAlexQuotaExceeded(RuntimeError):
|
|
33
|
+
"""配额/限流——显式失败,不冒充「无数据」。"""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class OpenAlexProvider(BaseDataProvider):
|
|
37
|
+
name = "academic-openalex"
|
|
38
|
+
|
|
39
|
+
def registry(self) -> dict:
|
|
40
|
+
return {"manifest": "academic_openalex.yaml"}
|
|
41
|
+
|
|
42
|
+
def run(self, command: str, params: dict) -> Any:
|
|
43
|
+
handlers = {
|
|
44
|
+
"get_work": self.get_work,
|
|
45
|
+
"search_works": self.search_works,
|
|
46
|
+
"get_references": self.get_references,
|
|
47
|
+
"get_citations": self.get_citations,
|
|
48
|
+
}
|
|
49
|
+
if command not in handlers:
|
|
50
|
+
raise ValueError(f"unknown command {command!r}")
|
|
51
|
+
return handlers[command](params or {})
|
|
52
|
+
|
|
53
|
+
# ------------------------------------------------------------------ HTTP
|
|
54
|
+
|
|
55
|
+
def _get(self, path: str, params: dict[str, Any] | None = None) -> tuple[dict, dict]:
|
|
56
|
+
"""GET 并返回 (payload, quota_headers)。失败显式抛错。"""
|
|
57
|
+
url = f"{API}/{path}"
|
|
58
|
+
if params:
|
|
59
|
+
url += "?" + urllib.parse.urlencode(params)
|
|
60
|
+
req = urllib.request.Request(
|
|
61
|
+
url, headers={"User-Agent": UA, "Accept": "application/json"}
|
|
62
|
+
)
|
|
63
|
+
try:
|
|
64
|
+
with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
|
|
65
|
+
raw = json.loads(resp.read().decode("utf-8", "replace"))
|
|
66
|
+
headers = dict(resp.headers.items())
|
|
67
|
+
except urllib.error.HTTPError as exc:
|
|
68
|
+
# 429 或 5xx 都要区分清楚:前者是配额,后者是上游故障
|
|
69
|
+
if exc.code == 429:
|
|
70
|
+
raise OpenAlexQuotaExceeded(
|
|
71
|
+
f"OpenAlex rate limit / quota exceeded (HTTP 429): {exc.read()[:200]!r}"
|
|
72
|
+
) from exc
|
|
73
|
+
if 500 <= exc.code < 600:
|
|
74
|
+
raise OpenAlexUnavailable(
|
|
75
|
+
f"OpenAlex upstream unavailable (HTTP {exc.code})"
|
|
76
|
+
) from exc
|
|
77
|
+
raise OpenAlexUnavailable(
|
|
78
|
+
f"OpenAlex request failed (HTTP {exc.code}): {exc.read()[:200]!r}"
|
|
79
|
+
) from exc
|
|
80
|
+
except (urllib.error.URLError, TimeoutError, OSError) as exc:
|
|
81
|
+
raise OpenAlexUnavailable(f"OpenAlex unreachable: {exc}") from exc
|
|
82
|
+
quota = {
|
|
83
|
+
k.lower(): v
|
|
84
|
+
for k, v in headers.items()
|
|
85
|
+
if k.lower().startswith("x-ratelimit") or k.lower() == "retry-after"
|
|
86
|
+
}
|
|
87
|
+
return raw, quota
|
|
88
|
+
|
|
89
|
+
def _resolve_work_id(self, params: dict) -> str:
|
|
90
|
+
"""按 work_id 或 doi 定位作品。两者皆缺则报错(不猜)。"""
|
|
91
|
+
work_id = (params.get("work_id") or "").strip()
|
|
92
|
+
doi = (params.get("doi") or "").strip()
|
|
93
|
+
if not work_id and not doi:
|
|
94
|
+
raise ValueError("get_references/get_citations requires `work_id` or `doi`")
|
|
95
|
+
if work_id:
|
|
96
|
+
# 允许传完整 URL,统一取末段
|
|
97
|
+
return work_id.rstrip("/").split("/")[-1]
|
|
98
|
+
payload, _ = self._get(
|
|
99
|
+
"works",
|
|
100
|
+
{"filter": f"doi:{doi}", "select": "id", "per-page": "1"},
|
|
101
|
+
)
|
|
102
|
+
results = payload.get("results") or []
|
|
103
|
+
if not results:
|
|
104
|
+
raise ValueError(
|
|
105
|
+
f"work not found in OpenAlex for doi={doi!r} "
|
|
106
|
+
f"(未收录,不等于该作品不存在)"
|
|
107
|
+
)
|
|
108
|
+
return str(results[0]["id"]).rstrip("/").split("/")[-1]
|
|
109
|
+
|
|
110
|
+
# ------------------------------------------------------------- commands
|
|
111
|
+
|
|
112
|
+
def get_work(self, params: dict) -> dict:
|
|
113
|
+
doi = (params.get("doi") or "").strip()
|
|
114
|
+
if not doi:
|
|
115
|
+
raise ValueError("get_work requires `doi`")
|
|
116
|
+
payload, quota = self._get(
|
|
117
|
+
"works", {"filter": f"doi:{doi}", "per-page": "1"}
|
|
118
|
+
)
|
|
119
|
+
results = payload.get("results") or []
|
|
120
|
+
if not results:
|
|
121
|
+
# 未收录 ≠ 不存在:如实说明
|
|
122
|
+
raise ValueError(
|
|
123
|
+
f"work not found in OpenAlex for doi={doi!r} (未收录,不等于该作品不存在)"
|
|
124
|
+
)
|
|
125
|
+
w = results[0]
|
|
126
|
+
return {
|
|
127
|
+
"work_id": str(w.get("id", "")).rstrip("/").split("/")[-1],
|
|
128
|
+
"title": w.get("title"),
|
|
129
|
+
"year": w.get("publication_year"),
|
|
130
|
+
"venue": (w.get("primary_location") or {}).get("source", {}).get("display_name")
|
|
131
|
+
if isinstance(w.get("primary_location"), dict)
|
|
132
|
+
else None,
|
|
133
|
+
"cited_by_count": w.get("cited_by_count"),
|
|
134
|
+
"doi": w.get("doi"),
|
|
135
|
+
"source": "openalex",
|
|
136
|
+
"license": "CC0",
|
|
137
|
+
"quota": quota,
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
def search_works(self, params: dict) -> dict:
|
|
141
|
+
query = (params.get("query") or "").strip()
|
|
142
|
+
if not query:
|
|
143
|
+
raise ValueError("search_works requires `query`")
|
|
144
|
+
limit = int(params.get("limit") or 10)
|
|
145
|
+
payload, quota = self._get(
|
|
146
|
+
"works",
|
|
147
|
+
{
|
|
148
|
+
"search": query,
|
|
149
|
+
"per-page": str(min(limit, 200)),
|
|
150
|
+
"select": "id,title,publication_year,cited_by_count",
|
|
151
|
+
},
|
|
152
|
+
)
|
|
153
|
+
rows = []
|
|
154
|
+
for w in payload.get("results") or []:
|
|
155
|
+
rows.append(
|
|
156
|
+
{
|
|
157
|
+
"work_id": str(w.get("id", "")).rstrip("/").split("/")[-1],
|
|
158
|
+
"title": w.get("title"),
|
|
159
|
+
"year": w.get("publication_year"),
|
|
160
|
+
"cited_by_count": w.get("cited_by_count"),
|
|
161
|
+
}
|
|
162
|
+
)
|
|
163
|
+
return {
|
|
164
|
+
"total": (payload.get("meta") or {}).get("count"),
|
|
165
|
+
"results": rows,
|
|
166
|
+
"source": "openalex",
|
|
167
|
+
"license": "CC0",
|
|
168
|
+
"quota": quota,
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
def get_references(self, params: dict) -> dict:
|
|
172
|
+
work_id = self._resolve_work_id(params)
|
|
173
|
+
payload, quota = self._get(
|
|
174
|
+
f"works/{work_id}", {"select": "id,referenced_works_count,referenced_works"}
|
|
175
|
+
)
|
|
176
|
+
refs = payload.get("referenced_works") or []
|
|
177
|
+
return {
|
|
178
|
+
"work_id": work_id,
|
|
179
|
+
"reference_count": payload.get("referenced_works_count"),
|
|
180
|
+
"reference_ids": [str(r).rstrip("/").split("/")[-1] for r in refs],
|
|
181
|
+
"source": "openalex",
|
|
182
|
+
"license": "CC0",
|
|
183
|
+
"quota": quota,
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
def get_citations(self, params: dict) -> dict:
|
|
187
|
+
work_id = self._resolve_work_id(params)
|
|
188
|
+
limit = int(params.get("limit") or 10)
|
|
189
|
+
payload, quota = self._get(
|
|
190
|
+
"works",
|
|
191
|
+
{
|
|
192
|
+
"filter": f"cites:{work_id}",
|
|
193
|
+
"per-page": str(min(limit, 200)),
|
|
194
|
+
"select": "id,title,publication_year",
|
|
195
|
+
},
|
|
196
|
+
)
|
|
197
|
+
rows = []
|
|
198
|
+
for w in payload.get("results") or []:
|
|
199
|
+
rows.append(
|
|
200
|
+
{
|
|
201
|
+
"citing_work_id": str(w.get("id", "")).rstrip("/").split("/")[-1],
|
|
202
|
+
"title": w.get("title"),
|
|
203
|
+
"year": w.get("publication_year"),
|
|
204
|
+
}
|
|
205
|
+
)
|
|
206
|
+
return {
|
|
207
|
+
"work_id": work_id,
|
|
208
|
+
"total_count": (payload.get("meta") or {}).get("count"),
|
|
209
|
+
"results": rows,
|
|
210
|
+
"source": "openalex",
|
|
211
|
+
"license": "CC0",
|
|
212
|
+
"quota": quota,
|
|
213
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""启动时向 registry 自报工具面(共享实现,openspec: mcp-surface-self-report)。
|
|
2
|
+
|
|
3
|
+
逐用户凭据服务的 HTTP 层匿名一律 401,registry 探针永远探不到——工具面变更后
|
|
4
|
+
快照停旧值,发布门把合法新工具名判 unresolved。本模块在服务启动、工具注册完成
|
|
5
|
+
后,把**运行时枚举**的工具名清单报给 registry 的内部自报路由(path 绑定 token)。
|
|
6
|
+
|
|
7
|
+
从三份逐仓副本(wire-ops / wanxing-ops / fd-paper-trading,各 160 行近同)抽成单一
|
|
8
|
+
共享实现(openspec: stabilize-mcp-lifecycle D1)——多份复制必然漂移,一处修复到不了
|
|
9
|
+
另两处。
|
|
10
|
+
|
|
11
|
+
纪律:
|
|
12
|
+
- 失败**不阻塞启动**——registry 不可达时服务照常提供能力;
|
|
13
|
+
- 有界重试 15s/1m/5m/30m ×4(`REGISTRY_SURFACE_BACKOFF` 可覆盖),成功即停——不是心跳;
|
|
14
|
+
- 未配置时**静默跳过**(本地开发/未上牌形态,零行为变化)。
|
|
15
|
+
|
|
16
|
+
env(按 `prefix` 派生,默认 `WIRE`;各服务用自己前缀,见 `ensure_started(prefix=...)`):
|
|
17
|
+
- `REGISTRY_INTERNAL_URL` registry 内网入口(全局,非按线)
|
|
18
|
+
- `<PREFIX>_SURFACE_TOKEN` 该服务 path 绑定的 srf_ token
|
|
19
|
+
- `<PREFIX>_SURFACE_ENTRY_PATH` 注册路径(如 `/wire-ops-mcp`)
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import asyncio
|
|
25
|
+
import logging
|
|
26
|
+
import os
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
#: 退避序列(秒)。REGISTRY_SURFACE_BACKOFF 可整体覆盖(逗号分隔)。
|
|
31
|
+
_DEFAULT_BACKOFF = (15, 60, 300, 1800)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _backoff_sequence() -> tuple[float, ...]:
|
|
35
|
+
raw = os.environ.get("REGISTRY_SURFACE_BACKOFF")
|
|
36
|
+
if not raw:
|
|
37
|
+
return _DEFAULT_BACKOFF
|
|
38
|
+
try:
|
|
39
|
+
values = tuple(float(x) for x in raw.split(",") if x.strip())
|
|
40
|
+
return values or _DEFAULT_BACKOFF
|
|
41
|
+
except ValueError:
|
|
42
|
+
logger.warning("REGISTRY_SURFACE_BACKOFF unparsable; using default")
|
|
43
|
+
return _DEFAULT_BACKOFF
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _configured(prefix: str) -> tuple[str, str, str] | None:
|
|
47
|
+
"""(internal_url, entry_path, token) 或 None(未配置 → 静默跳过)。"""
|
|
48
|
+
base = os.environ.get("REGISTRY_INTERNAL_URL", "").rstrip("/")
|
|
49
|
+
token = os.environ.get(f"{prefix}_SURFACE_TOKEN", "")
|
|
50
|
+
path = os.environ.get(f"{prefix}_SURFACE_ENTRY_PATH", "").strip()
|
|
51
|
+
if not base or not token or not path:
|
|
52
|
+
return None
|
|
53
|
+
if not path.startswith("/"):
|
|
54
|
+
path = "/" + path
|
|
55
|
+
return base, path.rstrip("/"), token
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
async def _tool_names(mcp) -> list[str]:
|
|
59
|
+
"""运行时枚举:真源是注册进 FastMCP 的工具,不是 tool-surface.json。
|
|
60
|
+
|
|
61
|
+
`fastmcp` 版本区间横跨两代枚举 API:4.x 只有 ``list_tools()``(Tool 对象/字典序列),
|
|
62
|
+
更高版本另提供 ``get_tools()``({name: tool} 映射)。按可用性分派——只认其中一个
|
|
63
|
+
API 会在另一代的镜像里 AttributeError(2026-10-24 生产实证:启动自报因此一次都没
|
|
64
|
+
发出去,fire-and-forget 边界吞成 failed)。
|
|
65
|
+
"""
|
|
66
|
+
get_tools = getattr(mcp, "get_tools", None)
|
|
67
|
+
if get_tools is not None:
|
|
68
|
+
return sorted((await get_tools()).keys())
|
|
69
|
+
items = await mcp.list_tools()
|
|
70
|
+
return sorted(t["name"] if isinstance(t, dict) else t.name for t in items)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _surface_version() -> str | None:
|
|
74
|
+
"""tool-surface.json 的 sha 摘要(存在才带)——把自报与构建期清单对上版。
|
|
75
|
+
|
|
76
|
+
wheel 里它随包走(package-data);editable/源码树里它在仓库根,
|
|
77
|
+
importlib.resources 找不到——回落逐级父目录找。
|
|
78
|
+
"""
|
|
79
|
+
try:
|
|
80
|
+
import hashlib
|
|
81
|
+
from pathlib import Path
|
|
82
|
+
|
|
83
|
+
here = Path(__file__).resolve().parent
|
|
84
|
+
for cand in (here, *here.parents[:5]):
|
|
85
|
+
if (cand / "tool-surface.json").is_file():
|
|
86
|
+
return hashlib.sha256((cand / "tool-surface.json").read_bytes()).hexdigest()[:12]
|
|
87
|
+
except Exception as exc: # noqa: BLE001 — 版本标注是可选元数据
|
|
88
|
+
logger.warning("surface_version unavailable: %s", exc)
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
async def report_surface(mcp, *, prefix: str = "WIRE", httpx=None) -> bool:
|
|
93
|
+
"""报一次;成功 True。所有失败都被吞掉并记日志——启动不受阻。"""
|
|
94
|
+
cfg = _configured(prefix)
|
|
95
|
+
if cfg is None:
|
|
96
|
+
logger.info("surface report: not configured (%s_SURFACE_*), skipping", prefix)
|
|
97
|
+
return False
|
|
98
|
+
base, path, token = cfg
|
|
99
|
+
|
|
100
|
+
if httpx is None:
|
|
101
|
+
import httpx as httpx_mod
|
|
102
|
+
httpx = httpx_mod
|
|
103
|
+
|
|
104
|
+
payload = {
|
|
105
|
+
"tools": [{"name": name} for name in await _tool_names(mcp)],
|
|
106
|
+
"surface_version": _surface_version(),
|
|
107
|
+
}
|
|
108
|
+
url = f"{base}/api/surface-report/servers{path}/tool-list"
|
|
109
|
+
|
|
110
|
+
for attempt, delay in enumerate((0.0,) + _backoff_sequence(), start=1):
|
|
111
|
+
if delay:
|
|
112
|
+
await asyncio.sleep(delay)
|
|
113
|
+
try:
|
|
114
|
+
async with httpx.AsyncClient(timeout=15) as client:
|
|
115
|
+
resp = await client.post(
|
|
116
|
+
url, json=payload,
|
|
117
|
+
headers={"Authorization": f"Bearer {token}"},
|
|
118
|
+
)
|
|
119
|
+
if resp.status_code == 200:
|
|
120
|
+
body = resp.json()
|
|
121
|
+
logger.info(
|
|
122
|
+
"surface report: ok (%s tool(s), updated=%s reason=%s)",
|
|
123
|
+
body.get("num_tools"), body.get("updated"), body.get("reason"),
|
|
124
|
+
)
|
|
125
|
+
return True
|
|
126
|
+
logger.warning(
|
|
127
|
+
"surface report: HTTP %s (attempt %s) — %s",
|
|
128
|
+
resp.status_code, attempt, resp.text[:160],
|
|
129
|
+
)
|
|
130
|
+
except Exception as exc: # noqa: BLE001 — 网络层任何异常都不上抛
|
|
131
|
+
logger.warning(
|
|
132
|
+
"surface report: %s: %s (attempt %s)",
|
|
133
|
+
type(exc).__name__, str(exc)[:120], attempt,
|
|
134
|
+
)
|
|
135
|
+
logger.error("surface report: giving up after %s attempts", len(_backoff_sequence()) + 1)
|
|
136
|
+
return False
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def report_state(ok: bool, configured: bool) -> str:
|
|
140
|
+
"""/health 的 last_surface_report 口径。"""
|
|
141
|
+
if not configured:
|
|
142
|
+
return "not_configured"
|
|
143
|
+
return "ok" if ok else "failed"
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def start_background(mcp, *, prefix: str = "WIRE") -> asyncio.Task | None:
|
|
147
|
+
"""fire-and-forget 自报任务;未配置时返回 None(零行为变化)。"""
|
|
148
|
+
if _configured(prefix) is None:
|
|
149
|
+
return None
|
|
150
|
+
|
|
151
|
+
async def _runner():
|
|
152
|
+
# 吞掉一切异常:网络层失败 report_surface 自己消化,但代码层缺陷
|
|
153
|
+
# (参数错、序列化炸)也不能把后台任务变成未处理异常——状态置 failed。
|
|
154
|
+
try:
|
|
155
|
+
ok = await report_surface(mcp, prefix=prefix)
|
|
156
|
+
mcp._surface_report = report_state(ok, configured=True)
|
|
157
|
+
except Exception: # noqa: BLE001 — fire-and-forget 边界
|
|
158
|
+
mcp._surface_report = report_state(False, configured=True)
|
|
159
|
+
|
|
160
|
+
return asyncio.create_task(_runner())
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def ensure_started(mcp, *, prefix: str = "WIRE") -> None:
|
|
164
|
+
"""首请求触发点:此时事件循环已在跑;只触发一次;未配置置 False 封口。"""
|
|
165
|
+
if getattr(mcp, "_surface_task", None) is not None:
|
|
166
|
+
return
|
|
167
|
+
mcp._surface_task = start_background(mcp, prefix=prefix) or False
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# FindData vocabulary — cross-layer alignment with the ontology foundation.
|
|
2
|
+
#
|
|
3
|
+
# The observation layer (this package: country/stock/GDP/…) and the platform's
|
|
4
|
+
# business-ontology foundation (`organization`/`person`/`place`/…) describe the
|
|
5
|
+
# same referents from different lifecycles. `company` here is an *object being
|
|
6
|
+
# observed* — it has tickers and an identifiers table; `organization` there is a
|
|
7
|
+
# *party to transactions* — it has customers and contracts. They must NOT be
|
|
8
|
+
# merged: merging forces one side to accept the other's release cycle, and both
|
|
9
|
+
# sides can name a counterexample.
|
|
10
|
+
#
|
|
11
|
+
# So this file declares equivalence and nothing else. It is **not** consumed by
|
|
12
|
+
# the vocabulary loader (whose six YAML files are pinned by golden digests and
|
|
13
|
+
# must not change); it is read by the platform's template importer
|
|
14
|
+
# (`law-bench-internal/scripts/import_protocol_ontology.py`), which turns each
|
|
15
|
+
# entry into an `aligned_with` block on the observation-layer template.
|
|
16
|
+
#
|
|
17
|
+
# Adding an entry here never changes an entity type, a concept, or a digest. It
|
|
18
|
+
# only tells a reader "these two words point at one thing".
|
|
19
|
+
version: "2026.11"
|
|
20
|
+
kind: alignment
|
|
21
|
+
target:
|
|
22
|
+
template: foundation-v1
|
|
23
|
+
layer: foundation
|
|
24
|
+
alignments:
|
|
25
|
+
# --- organizations ---------------------------------------------------------
|
|
26
|
+
- from: company
|
|
27
|
+
to: organization
|
|
28
|
+
note: >-
|
|
29
|
+
A listed company is an organization that is also an observed object. The
|
|
30
|
+
observation layer keys it by exchange-suffixed ticker; the foundation keys
|
|
31
|
+
it by a business identity. Same referent, two lifecycles.
|
|
32
|
+
- from: organization
|
|
33
|
+
to: organization
|
|
34
|
+
note: Identical word both sides; declared so the mapping is explicit, not inferred.
|
|
35
|
+
- from: institution
|
|
36
|
+
to: organization
|
|
37
|
+
note: Universities, hospitals, agencies — an organization with a different role.
|
|
38
|
+
|
|
39
|
+
# --- places ----------------------------------------------------------------
|
|
40
|
+
- from: city
|
|
41
|
+
to: place
|
|
42
|
+
note: Keyed by DCID or GeoNames id here; by admin hierarchy there.
|
|
43
|
+
- from: port
|
|
44
|
+
to: place
|
|
45
|
+
note: >-
|
|
46
|
+
A port is a place with an operational role. It stays its own observation
|
|
47
|
+
type (trade statistics key on it) but lands on `place` in the foundation.
|
|
48
|
+
- from: venue
|
|
49
|
+
to: place
|
|
50
|
+
note: Exchange venues are places in the physical sense only when they have one.
|
|
51
|
+
|
|
52
|
+
# --- people ----------------------------------------------------------------
|
|
53
|
+
- from: person
|
|
54
|
+
to: person
|
|
55
|
+
note: Identical word both sides.
|
|
56
|
+
- from: author
|
|
57
|
+
to: person
|
|
58
|
+
note: An author is a person in a role; the role is the relationship, not a type.
|
|
59
|
+
|
|
60
|
+
# Deliberately NOT aligned (recorded so a later reader does not "fix" them):
|
|
61
|
+
# stock / fund / bond / index / future / commodity / currency_pair
|
|
62
|
+
# — these are *instruments*, not organizations. `instrument` is an industry-
|
|
63
|
+
# layer type; the alignment belongs there, not on the foundation.
|
|
64
|
+
# industry / topic / policy / approval
|
|
65
|
+
# — classification axes with no foundation counterpart.
|