scientific-data-mcp 0.6.1__py3-none-any.whl
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.
- scientific_data_mcp/__init__.py +12 -0
- scientific_data_mcp/__main__.py +34 -0
- scientific_data_mcp/config.py +73 -0
- scientific_data_mcp/errors.py +76 -0
- scientific_data_mcp/http.py +220 -0
- scientific_data_mcp/providers/__init__.py +5 -0
- scientific_data_mcp/providers/base.py +23 -0
- scientific_data_mcp/providers/biogrid.py +80 -0
- scientific_data_mcp/providers/chembl.py +172 -0
- scientific_data_mcp/providers/clinicaltrials.py +72 -0
- scientific_data_mcp/providers/materials_project.py +87 -0
- scientific_data_mcp/providers/openfda.py +52 -0
- scientific_data_mcp/providers/pubchem.py +171 -0
- scientific_data_mcp/providers/pubmed.py +131 -0
- scientific_data_mcp/providers/rcsb.py +97 -0
- scientific_data_mcp/providers/string_db.py +60 -0
- scientific_data_mcp/providers/uniprot.py +208 -0
- scientific_data_mcp/providers/who.py +70 -0
- scientific_data_mcp/runtime.py +55 -0
- scientific_data_mcp/server.py +35 -0
- scientific_data_mcp/tools/__init__.py +30 -0
- scientific_data_mcp/tools/_guard.py +58 -0
- scientific_data_mcp/tools/chemistry.py +199 -0
- scientific_data_mcp/tools/clinical.py +113 -0
- scientific_data_mcp/tools/interactions.py +105 -0
- scientific_data_mcp/tools/literature.py +44 -0
- scientific_data_mcp/tools/materials.py +81 -0
- scientific_data_mcp/tools/protein.py +178 -0
- scientific_data_mcp/tools/who.py +78 -0
- scientific_data_mcp-0.6.1.dist-info/METADATA +173 -0
- scientific_data_mcp-0.6.1.dist-info/RECORD +34 -0
- scientific_data_mcp-0.6.1.dist-info/WHEEL +4 -0
- scientific_data_mcp-0.6.1.dist-info/entry_points.txt +2 -0
- scientific_data_mcp-0.6.1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""scientific-data-mcp — free, keyless scientific entity data over MCP."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = ["__version__"]
|
|
6
|
+
|
|
7
|
+
try: # installed package metadata (hatch-vcs derives it from the git tag)
|
|
8
|
+
from importlib.metadata import version as _version
|
|
9
|
+
|
|
10
|
+
__version__ = _version("scientific-data-mcp")
|
|
11
|
+
except Exception: # pragma: no cover - source checkout without install
|
|
12
|
+
__version__ = "0.0.0"
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""CLI entry point: stdio MCP by default, streamable HTTP with --http."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
|
|
7
|
+
from .server import build_server
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def main(argv: list[str] | None = None) -> None:
|
|
11
|
+
parser = argparse.ArgumentParser(
|
|
12
|
+
prog="scientific-data-mcp",
|
|
13
|
+
description="Free, keyless MCP server for scientific entity data.",
|
|
14
|
+
)
|
|
15
|
+
parser.add_argument(
|
|
16
|
+
"--http",
|
|
17
|
+
action="store_true",
|
|
18
|
+
help="serve streamable HTTP instead of stdio (for mcpo/remote clients)",
|
|
19
|
+
)
|
|
20
|
+
parser.add_argument("--host", default="127.0.0.1", help="HTTP bind host")
|
|
21
|
+
parser.add_argument("--port", type=int, default=8000, help="HTTP bind port")
|
|
22
|
+
args = parser.parse_args(argv)
|
|
23
|
+
|
|
24
|
+
mcp = build_server()
|
|
25
|
+
if args.http:
|
|
26
|
+
mcp.settings.host = args.host
|
|
27
|
+
mcp.settings.port = args.port
|
|
28
|
+
mcp.run(transport="streamable-http")
|
|
29
|
+
else:
|
|
30
|
+
mcp.run()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
if __name__ == "__main__":
|
|
34
|
+
main()
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Runtime settings.
|
|
2
|
+
|
|
3
|
+
The nine base upstream sources work without configuration; ``NCBI_API_KEY``
|
|
4
|
+
and ``OPENFDA_API_KEY`` are optional and only lift rate limits. Materials
|
|
5
|
+
Project and BioGRID are key-gated: their providers are only created when
|
|
6
|
+
their keys are present (the ``material`` tool appears only with MP; the
|
|
7
|
+
shared ``protein_interactions`` tool stays available for STRING).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
|
|
15
|
+
DEFAULT_USER_AGENT = (
|
|
16
|
+
"scientific-data-mcp/0.1 (+https://github.com/xyonium/scientific-data-mcp)"
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
# Per-host minimum gap between requests. Values follow each API's published
|
|
20
|
+
# politeness guidance (NCBI 3/s without a key, PubChem <=5/s, ChEMBL moderate).
|
|
21
|
+
HOST_DELAYS: dict[str, float] = {
|
|
22
|
+
"pubchem.ncbi.nlm.nih.gov": 0.2,
|
|
23
|
+
"www.ebi.ac.uk": 0.5,
|
|
24
|
+
"rest.uniprot.org": 0.2,
|
|
25
|
+
"data.rcsb.org": 0.2,
|
|
26
|
+
"search.rcsb.org": 0.5,
|
|
27
|
+
"eutils.ncbi.nlm.nih.gov": 0.34,
|
|
28
|
+
"www.ncbi.nlm.nih.gov": 0.34,
|
|
29
|
+
"api.materialsproject.org": 1.0,
|
|
30
|
+
"ghoapi.azureedge.net": 0.5,
|
|
31
|
+
"webservice.thebiogrid.org": 1.0,
|
|
32
|
+
"string-db.org": 0.5,
|
|
33
|
+
"api.fda.gov": 0.5,
|
|
34
|
+
"clinicaltrials.gov": 0.5,
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class Settings:
|
|
40
|
+
ncbi_api_key: str | None = None
|
|
41
|
+
ncbi_email: str | None = None
|
|
42
|
+
materials_project_api_key: str | None = None
|
|
43
|
+
biogrid_access_key: str | None = None
|
|
44
|
+
openfda_api_key: str | None = None
|
|
45
|
+
timeout: float = 30.0
|
|
46
|
+
max_retries: int = 4
|
|
47
|
+
retry_budget: float = 45.0
|
|
48
|
+
user_agent: str = DEFAULT_USER_AGENT
|
|
49
|
+
host_delays: dict[str, float] = field(default_factory=lambda: dict(HOST_DELAYS))
|
|
50
|
+
|
|
51
|
+
def __post_init__(self) -> None:
|
|
52
|
+
# NCBI allows 10 req/s with a registered key, 3 req/s without.
|
|
53
|
+
if self.ncbi_api_key:
|
|
54
|
+
self.host_delays["eutils.ncbi.nlm.nih.gov"] = 0.1
|
|
55
|
+
self.host_delays["www.ncbi.nlm.nih.gov"] = 0.1
|
|
56
|
+
|
|
57
|
+
def host_delay(self, host: str) -> float:
|
|
58
|
+
return self.host_delays.get(host, 0.1)
|
|
59
|
+
|
|
60
|
+
@classmethod
|
|
61
|
+
def from_env(cls) -> Settings:
|
|
62
|
+
key = os.environ.get("NCBI_API_KEY", "").strip() or None
|
|
63
|
+
email = os.environ.get("NCBI_EMAIL", "").strip() or None
|
|
64
|
+
mp_key = os.environ.get("MATERIALS_PROJECT_API_KEY", "").strip() or None
|
|
65
|
+
bg_key = os.environ.get("BIOGRID_ACCESS_KEY", "").strip() or None
|
|
66
|
+
fda_key = os.environ.get("OPENFDA_API_KEY", "").strip() or None
|
|
67
|
+
return cls(
|
|
68
|
+
ncbi_api_key=key,
|
|
69
|
+
ncbi_email=email,
|
|
70
|
+
materials_project_api_key=mp_key,
|
|
71
|
+
biogrid_access_key=bg_key,
|
|
72
|
+
openfda_api_key=fda_key,
|
|
73
|
+
)
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Error taxonomy and the never-raise tool-error dict.
|
|
2
|
+
|
|
3
|
+
Tools never raise: every provider failure is translated here into
|
|
4
|
+
``{"error": ..., "source": ..., "hint"?: ...}`` so one bad upstream call
|
|
5
|
+
cannot abort an agent turn.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ProviderError(Exception):
|
|
12
|
+
kind = "error"
|
|
13
|
+
retryable = False
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class RateLimited(ProviderError):
|
|
17
|
+
kind = "rate_limited"
|
|
18
|
+
retryable = True
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AuthError(ProviderError):
|
|
22
|
+
kind = "auth"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class NotFound(ProviderError):
|
|
26
|
+
kind = "not_found"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class UpstreamError(ProviderError):
|
|
30
|
+
kind = "unavailable"
|
|
31
|
+
retryable = True
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class UpstreamDrift(ProviderError):
|
|
35
|
+
"""The upstream response no longer matches this adapter's contract.
|
|
36
|
+
|
|
37
|
+
Not retryable: repeating the same request will not help. Tools surface it
|
|
38
|
+
with ``suspect_drift`` so the model tells the user to contact the
|
|
39
|
+
administrator instead of retrying blindly.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
kind = "upstream_drift"
|
|
43
|
+
retryable = False
|
|
44
|
+
contact_admin = True
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
DRIFT_HINT = (
|
|
48
|
+
"上游返回与适配器预期不一致(接口可能已漂移)。不要用相同参数重试;"
|
|
49
|
+
"请告知用户联系管理员更新对应 provider。"
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def tool_error(
|
|
54
|
+
msg: object,
|
|
55
|
+
hint: str | None = None,
|
|
56
|
+
*,
|
|
57
|
+
suspect_drift: bool = False,
|
|
58
|
+
**extra: object,
|
|
59
|
+
) -> dict:
|
|
60
|
+
"""Build the single error shape every tool returns."""
|
|
61
|
+
out: dict = {"error": str(msg)}
|
|
62
|
+
if hint:
|
|
63
|
+
out["hint"] = hint
|
|
64
|
+
if suspect_drift:
|
|
65
|
+
out["suspect_drift"] = True
|
|
66
|
+
out["action"] = "contact_admin"
|
|
67
|
+
out.update(extra)
|
|
68
|
+
return out
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def scrub(text: str, *secrets: str) -> str:
|
|
72
|
+
"""Remove known secrets from a message before it reaches the model."""
|
|
73
|
+
for secret in secrets:
|
|
74
|
+
if secret:
|
|
75
|
+
text = text.replace(secret, "***")
|
|
76
|
+
return text
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""Shared async HTTP client: per-host pacing, bounded retry, error translation.
|
|
2
|
+
|
|
3
|
+
Every provider goes through this client. It paces requests per host, honours
|
|
4
|
+
``Retry-After`` on 429/503, retries transient network errors, and maps HTTP
|
|
5
|
+
status codes onto the taxonomy in :mod:`scientific_data_mcp.errors`.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import time
|
|
12
|
+
from typing import Any
|
|
13
|
+
from urllib.parse import urlparse
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
from .config import Settings
|
|
18
|
+
from .errors import AuthError, NotFound, RateLimited, UpstreamDrift, UpstreamError
|
|
19
|
+
|
|
20
|
+
_MAX_RETRY_AFTER = 10.0
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class PoliteClient:
|
|
24
|
+
def __init__(self, settings: Settings):
|
|
25
|
+
self._settings = settings
|
|
26
|
+
self._client = httpx.AsyncClient(
|
|
27
|
+
timeout=settings.timeout,
|
|
28
|
+
headers={"User-Agent": settings.user_agent},
|
|
29
|
+
follow_redirects=True,
|
|
30
|
+
)
|
|
31
|
+
self._max_retries = settings.max_retries
|
|
32
|
+
self._last: dict[str, float] = {}
|
|
33
|
+
self._lock = asyncio.Lock()
|
|
34
|
+
|
|
35
|
+
async def __aenter__(self) -> PoliteClient:
|
|
36
|
+
return self
|
|
37
|
+
|
|
38
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
39
|
+
await self.aclose()
|
|
40
|
+
|
|
41
|
+
async def aclose(self) -> None:
|
|
42
|
+
await self._client.aclose()
|
|
43
|
+
|
|
44
|
+
async def _pace(self, host: str) -> None:
|
|
45
|
+
gap = self._settings.host_delay(host)
|
|
46
|
+
async with self._lock:
|
|
47
|
+
elapsed = time.monotonic() - self._last.get(host, 0.0)
|
|
48
|
+
if elapsed < gap:
|
|
49
|
+
await asyncio.sleep(gap - elapsed)
|
|
50
|
+
self._last[host] = time.monotonic()
|
|
51
|
+
|
|
52
|
+
@staticmethod
|
|
53
|
+
def _retry_after(resp: httpx.Response, attempt: int) -> float:
|
|
54
|
+
raw = resp.headers.get("Retry-After", "")
|
|
55
|
+
if raw.replace(".", "", 1).isdigit():
|
|
56
|
+
return min(float(raw), _MAX_RETRY_AFTER)
|
|
57
|
+
return 0.5 * (2**attempt)
|
|
58
|
+
|
|
59
|
+
async def _request(
|
|
60
|
+
self,
|
|
61
|
+
method: str,
|
|
62
|
+
url: str,
|
|
63
|
+
*,
|
|
64
|
+
params: dict | None = None,
|
|
65
|
+
json_body: dict | None = None,
|
|
66
|
+
form: dict | None = None,
|
|
67
|
+
headers: dict | None = None,
|
|
68
|
+
follow_redirects: bool = True,
|
|
69
|
+
retry: bool = True,
|
|
70
|
+
allow_status: tuple[int, ...] = (),
|
|
71
|
+
) -> httpx.Response:
|
|
72
|
+
host = urlparse(url).netloc
|
|
73
|
+
last: Exception | None = None
|
|
74
|
+
attempts = self._max_retries + 1 if retry else 1
|
|
75
|
+
started = time.monotonic()
|
|
76
|
+
for attempt in range(attempts):
|
|
77
|
+
await self._pace(host)
|
|
78
|
+
try:
|
|
79
|
+
resp = await self._client.request(
|
|
80
|
+
method,
|
|
81
|
+
url,
|
|
82
|
+
params=params,
|
|
83
|
+
json=json_body,
|
|
84
|
+
data=form,
|
|
85
|
+
headers=headers,
|
|
86
|
+
follow_redirects=follow_redirects,
|
|
87
|
+
)
|
|
88
|
+
except httpx.HTTPError as exc:
|
|
89
|
+
last = UpstreamError(f"network error from {host}: {exc}")
|
|
90
|
+
if not retry:
|
|
91
|
+
raise last from exc
|
|
92
|
+
delay = 0.5 * (2**attempt)
|
|
93
|
+
if time.monotonic() - started + delay > self._settings.retry_budget:
|
|
94
|
+
raise last from exc
|
|
95
|
+
await asyncio.sleep(delay)
|
|
96
|
+
continue
|
|
97
|
+
if resp.status_code in (429, 503):
|
|
98
|
+
last = RateLimited(f"HTTP {resp.status_code} from {host}")
|
|
99
|
+
if not retry:
|
|
100
|
+
raise last
|
|
101
|
+
delay = self._retry_after(resp, attempt)
|
|
102
|
+
if time.monotonic() - started + delay > self._settings.retry_budget:
|
|
103
|
+
raise last
|
|
104
|
+
await asyncio.sleep(delay)
|
|
105
|
+
continue
|
|
106
|
+
if resp.status_code in (500, 502, 504):
|
|
107
|
+
# Transient upstream failures: ChEMBL and UniProt both return
|
|
108
|
+
# sporadic 5xx under load, and the same call succeeds on retry.
|
|
109
|
+
last = UpstreamError(f"HTTP {resp.status_code} from {host}")
|
|
110
|
+
if not retry:
|
|
111
|
+
raise last
|
|
112
|
+
delay = 0.5 * (2**attempt)
|
|
113
|
+
if time.monotonic() - started + delay > self._settings.retry_budget:
|
|
114
|
+
raise last
|
|
115
|
+
await asyncio.sleep(delay)
|
|
116
|
+
continue
|
|
117
|
+
if resp.status_code in allow_status:
|
|
118
|
+
return resp
|
|
119
|
+
if resp.status_code in (401, 403):
|
|
120
|
+
raise AuthError(f"HTTP {resp.status_code} from {host}")
|
|
121
|
+
if resp.status_code == 404:
|
|
122
|
+
raise NotFound(f"HTTP 404 from {host}")
|
|
123
|
+
if resp.status_code in (400, 405, 406, 422):
|
|
124
|
+
# Our request no longer matches the documented contract.
|
|
125
|
+
raise UpstreamDrift(
|
|
126
|
+
f"HTTP {resp.status_code} from {host}: request contract mismatch"
|
|
127
|
+
)
|
|
128
|
+
if resp.status_code >= 400:
|
|
129
|
+
raise UpstreamError(f"HTTP {resp.status_code} from {host}")
|
|
130
|
+
return resp
|
|
131
|
+
raise last if last is not None else UpstreamError(f"request to {host} failed")
|
|
132
|
+
|
|
133
|
+
async def get_response(
|
|
134
|
+
self,
|
|
135
|
+
url: str,
|
|
136
|
+
params: dict | None = None,
|
|
137
|
+
headers: dict | None = None,
|
|
138
|
+
follow_redirects: bool = True,
|
|
139
|
+
allow_status: tuple[int, ...] = (),
|
|
140
|
+
) -> httpx.Response:
|
|
141
|
+
return await self._request(
|
|
142
|
+
"GET",
|
|
143
|
+
url,
|
|
144
|
+
params=params,
|
|
145
|
+
headers=headers,
|
|
146
|
+
follow_redirects=follow_redirects,
|
|
147
|
+
allow_status=allow_status,
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
async def get_json(
|
|
151
|
+
self,
|
|
152
|
+
url: str,
|
|
153
|
+
params: dict | None = None,
|
|
154
|
+
headers: dict | None = None,
|
|
155
|
+
follow_redirects: bool = True,
|
|
156
|
+
) -> Any:
|
|
157
|
+
resp = await self.get_response(
|
|
158
|
+
url, params=params, headers=headers, follow_redirects=follow_redirects
|
|
159
|
+
)
|
|
160
|
+
if resp.status_code == 204:
|
|
161
|
+
return None
|
|
162
|
+
try:
|
|
163
|
+
return resp.json()
|
|
164
|
+
except ValueError as exc:
|
|
165
|
+
raise UpstreamDrift(
|
|
166
|
+
f"non-JSON response from {urlparse(url).netloc}: {exc}"
|
|
167
|
+
) from exc
|
|
168
|
+
|
|
169
|
+
async def get_text(
|
|
170
|
+
self,
|
|
171
|
+
url: str,
|
|
172
|
+
params: dict | None = None,
|
|
173
|
+
headers: dict | None = None,
|
|
174
|
+
) -> str:
|
|
175
|
+
resp = await self.get_response(url, params=params, headers=headers)
|
|
176
|
+
return resp.text
|
|
177
|
+
|
|
178
|
+
async def post_response(
|
|
179
|
+
self,
|
|
180
|
+
url: str,
|
|
181
|
+
json_body: dict,
|
|
182
|
+
headers: dict | None = None,
|
|
183
|
+
retry: bool = True,
|
|
184
|
+
) -> httpx.Response:
|
|
185
|
+
"""POST and return the raw response (for 204/3xx handling by callers)."""
|
|
186
|
+
return await self._request(
|
|
187
|
+
"POST", url, json_body=json_body, headers=headers, retry=retry
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
async def post_json(
|
|
191
|
+
self,
|
|
192
|
+
url: str,
|
|
193
|
+
json_body: dict,
|
|
194
|
+
headers: dict | None = None,
|
|
195
|
+
retry: bool = True,
|
|
196
|
+
) -> Any:
|
|
197
|
+
resp = await self._request(
|
|
198
|
+
"POST", url, json_body=json_body, headers=headers, retry=retry
|
|
199
|
+
)
|
|
200
|
+
if resp.status_code == 204:
|
|
201
|
+
return None
|
|
202
|
+
try:
|
|
203
|
+
return resp.json()
|
|
204
|
+
except ValueError as exc:
|
|
205
|
+
raise UpstreamDrift(
|
|
206
|
+
f"non-JSON response from {urlparse(url).netloc}: {exc}"
|
|
207
|
+
) from exc
|
|
208
|
+
|
|
209
|
+
async def post_form(
|
|
210
|
+
self,
|
|
211
|
+
url: str,
|
|
212
|
+
fields: dict,
|
|
213
|
+
headers: dict | None = None,
|
|
214
|
+
retry: bool = True,
|
|
215
|
+
) -> Any:
|
|
216
|
+
resp = await self._request("POST", url, form=fields, headers=headers, retry=retry)
|
|
217
|
+
try:
|
|
218
|
+
return resp.json()
|
|
219
|
+
except ValueError as exc:
|
|
220
|
+
raise UpstreamError(f"non-JSON response from {urlparse(url).netloc}: {exc}") from exc
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Provider protocol: one instance per upstream source."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from ..config import Settings
|
|
6
|
+
from ..http import PoliteClient
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Provider:
|
|
10
|
+
name: str = "base"
|
|
11
|
+
base_url: str = ""
|
|
12
|
+
|
|
13
|
+
def __init__(self, http: PoliteClient, settings: Settings):
|
|
14
|
+
self.http = http
|
|
15
|
+
self.settings = settings
|
|
16
|
+
|
|
17
|
+
def available(self) -> bool:
|
|
18
|
+
return True
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def omit_none(data: dict) -> dict:
|
|
22
|
+
"""Drop only None values; keep real empty lists, 0 and False."""
|
|
23
|
+
return {key: value for key, value in data.items() if value is not None}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""BioGRID provider (key-gated).
|
|
2
|
+
|
|
3
|
+
The REST API needs a free access key as a query parameter. The provider is
|
|
4
|
+
only constructed when ``BIOGRID_ACCESS_KEY`` is set, so a keyless install
|
|
5
|
+
keeps the base tool surface.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from ..config import Settings
|
|
11
|
+
from ..errors import UpstreamDrift
|
|
12
|
+
from ..http import PoliteClient
|
|
13
|
+
from .base import Provider, omit_none
|
|
14
|
+
|
|
15
|
+
_BASE = "https://webservice.thebiogrid.org"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class BioGridProvider(Provider):
|
|
19
|
+
name = "biogrid"
|
|
20
|
+
base_url = _BASE
|
|
21
|
+
|
|
22
|
+
def __init__(self, http: PoliteClient, settings: Settings):
|
|
23
|
+
super().__init__(http, settings)
|
|
24
|
+
self._key = settings.biogrid_access_key or ""
|
|
25
|
+
|
|
26
|
+
async def interactions(
|
|
27
|
+
self,
|
|
28
|
+
genes: str,
|
|
29
|
+
organism: int = 9606,
|
|
30
|
+
limit: int = 100,
|
|
31
|
+
offset: int = 0,
|
|
32
|
+
) -> dict:
|
|
33
|
+
payload = await self.http.get_json(
|
|
34
|
+
f"{self.base_url}/interactions/",
|
|
35
|
+
params={
|
|
36
|
+
"accesskey": self._key,
|
|
37
|
+
"format": "json",
|
|
38
|
+
"searchNames": "true",
|
|
39
|
+
"geneList": genes,
|
|
40
|
+
"taxId": organism,
|
|
41
|
+
"max": limit,
|
|
42
|
+
"start": offset,
|
|
43
|
+
},
|
|
44
|
+
)
|
|
45
|
+
if not isinstance(payload, dict):
|
|
46
|
+
raise UpstreamDrift(
|
|
47
|
+
f"BioGRID interactions response is {type(payload).__name__}, expected object"
|
|
48
|
+
)
|
|
49
|
+
rows = [_normalize(key, row) for key, row in payload.items()]
|
|
50
|
+
rows.sort(key=lambda row: row.get("interaction_id") or 0)
|
|
51
|
+
return {
|
|
52
|
+
"items": rows,
|
|
53
|
+
"next_offset": offset + len(rows) if len(rows) >= limit else None,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _normalize(key: str, row: dict) -> dict:
|
|
58
|
+
return omit_none(
|
|
59
|
+
{
|
|
60
|
+
"interaction_id": row.get("BIOGRID_INTERACTION_ID") or _maybe_int(key),
|
|
61
|
+
"gene_a": row.get("OFFICIAL_SYMBOL_A"),
|
|
62
|
+
"gene_b": row.get("OFFICIAL_SYMBOL_B"),
|
|
63
|
+
"entrez_a": row.get("ENTREZ_GENE_A"),
|
|
64
|
+
"entrez_b": row.get("ENTREZ_GENE_B"),
|
|
65
|
+
"organism_a": row.get("ORGANISM_A"),
|
|
66
|
+
"organism_b": row.get("ORGANISM_B"),
|
|
67
|
+
"experimental_system": row.get("EXPERIMENTAL_SYSTEM"),
|
|
68
|
+
"system_type": row.get("EXPERIMENTAL_SYSTEM_TYPE"),
|
|
69
|
+
"pubmed_id": row.get("PUBMED_ID"),
|
|
70
|
+
"throughput": row.get("THROUGHPUT"),
|
|
71
|
+
"score": row.get("SCORE"),
|
|
72
|
+
}
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _maybe_int(value: str) -> int | None:
|
|
77
|
+
try:
|
|
78
|
+
return int(value)
|
|
79
|
+
except (TypeError, ValueError):
|
|
80
|
+
return None
|