bitcoindatalabs-mcp 0.1.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.
- bitcoindatalabs_mcp-0.1.0/LICENSE +21 -0
- bitcoindatalabs_mcp-0.1.0/PKG-INFO +108 -0
- bitcoindatalabs_mcp-0.1.0/README.md +79 -0
- bitcoindatalabs_mcp-0.1.0/pyproject.toml +64 -0
- bitcoindatalabs_mcp-0.1.0/setup.cfg +4 -0
- bitcoindatalabs_mcp-0.1.0/src/bitcoindatalabs_mcp/__init__.py +4 -0
- bitcoindatalabs_mcp-0.1.0/src/bitcoindatalabs_mcp/data_client.py +174 -0
- bitcoindatalabs_mcp-0.1.0/src/bitcoindatalabs_mcp/queries.py +671 -0
- bitcoindatalabs_mcp-0.1.0/src/bitcoindatalabs_mcp/server.py +221 -0
- bitcoindatalabs_mcp-0.1.0/src/bitcoindatalabs_mcp.egg-info/PKG-INFO +108 -0
- bitcoindatalabs_mcp-0.1.0/src/bitcoindatalabs_mcp.egg-info/SOURCES.txt +16 -0
- bitcoindatalabs_mcp-0.1.0/src/bitcoindatalabs_mcp.egg-info/dependency_links.txt +1 -0
- bitcoindatalabs_mcp-0.1.0/src/bitcoindatalabs_mcp.egg-info/entry_points.txt +3 -0
- bitcoindatalabs_mcp-0.1.0/src/bitcoindatalabs_mcp.egg-info/requires.txt +6 -0
- bitcoindatalabs_mcp-0.1.0/src/bitcoindatalabs_mcp.egg-info/top_level.txt +1 -0
- bitcoindatalabs_mcp-0.1.0/tests/test_mcp_stdio.py +58 -0
- bitcoindatalabs_mcp-0.1.0/tests/test_offline_ci.py +107 -0
- bitcoindatalabs_mcp-0.1.0/tests/test_queries.py +85 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bitcoin Data Labs (Saurabh Kumar)
|
|
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.
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bitcoindatalabs-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Zero-clone Model Context Protocol (MCP) server for Bitcoin Data Labs open telemetry: Bitcoin Core governance, BIPs, OSS ecosystem security posture (1,009 repos), Lightning security research, mining concentration, and on-chain forensic aggregates.
|
|
5
|
+
Author: Saurabh Kumar
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://bitcoindatalabs.org
|
|
8
|
+
Project-URL: Repository, https://github.com/bitcoindatalabs/bitcoindatalabs-mcp
|
|
9
|
+
Project-URL: Research, https://bitcoindatalabs.org/research.html
|
|
10
|
+
Project-URL: Data Catalog, https://bitcoindatalabs.org/work.html
|
|
11
|
+
Keywords: mcp,model-context-protocol,bitcoin,lightning-network,bitcoin-data-labs,open-source-software,supply-chain-security,security-research,duckdb,parquet
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Requires-Dist: mcp>=2.0.0
|
|
24
|
+
Requires-Dist: duckdb>=1.1.0
|
|
25
|
+
Requires-Dist: httpx>=0.27.0
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
<!-- mcp-name: io.github.bitcoindatalabs/bitcoindatalabs-mcp -->
|
|
31
|
+
|
|
32
|
+
# bitcoindatalabs-mcp
|
|
33
|
+
|
|
34
|
+
[](https://pypi.org/project/bitcoindatalabs-mcp/)
|
|
35
|
+
[](https://glama.ai/mcp/servers/bitcoindatalabs/bitcoindatalabs-mcp)
|
|
36
|
+
[](LICENSE)
|
|
37
|
+
[](pyproject.toml)
|
|
38
|
+
[](https://bitcoindatalabs.org)
|
|
39
|
+
|
|
40
|
+
Zero-clone **Model Context Protocol (MCP)** server for [Bitcoin Data Labs](https://bitcoindatalabs.org) open telemetry, open-source ecosystem security metrics, and reproducible empirical research.
|
|
41
|
+
|
|
42
|
+
Query **1,009 ecosystem OSS repositories**, **Bitcoin Core governance & BIPs**, **developer funding**, **three peer-cited Lightning Network security studies (`arXiv:2610.20952`, `2610.30350`, `2611.16311`)**, **mining pool HHI concentration**, and **aggregate on-chain forensics** inside Claude, Cursor, Antigravity, or VS Code — without cloning any data repositories.
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
## Quick Start (Zero Clone)
|
|
47
|
+
|
|
48
|
+
`bitcoindatalabs-mcp` lazily fetches only the JSON and Parquet files your query needs from `github.com/bitcoindatalabs/*` and caches them in `~/.cache/bitcoindatalabs-mcp/` (DuckDB queries Parquet slices in memory).
|
|
49
|
+
|
|
50
|
+
### Claude Desktop / Cursor / Antigravity (`mcpServers`)
|
|
51
|
+
|
|
52
|
+
```json
|
|
53
|
+
{
|
|
54
|
+
"mcpServers": {
|
|
55
|
+
"bitcoindatalabs-mcp": {
|
|
56
|
+
"command": "uvx",
|
|
57
|
+
"args": ["bitcoindatalabs-mcp"]
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### Local Python Install (also installs the `bdl-mcp` CLI alias)
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
pip install bitcoindatalabs-mcp
|
|
67
|
+
bitcoindatalabs-mcp # or CLI alias: bdl-mcp
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
For local development against cloned `bitcoindatalabs/*` repositories, set `BDL_GITHUB_ROOT` to avoid HTTPS requests:
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
export BDL_GITHUB_ROOT=/path/to/github/checkouts
|
|
74
|
+
pip install -e ".[dev]"
|
|
75
|
+
pytest -v
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
---
|
|
79
|
+
|
|
80
|
+
## Datasets, Tools & Resources (`11` Repositories, `13` Tools, `7` Resources)
|
|
81
|
+
|
|
82
|
+
| Repository | MCP Tool | Empirical Coverage |
|
|
83
|
+
| :--- | :--- | :--- |
|
|
84
|
+
| Meta / Papers | `list_datasets`, `get_research_papers` | Full catalog + summaries, arXiv DOIs & BibTeX for the 3 Lightning security papers |
|
|
85
|
+
| [`ln-client-diversity`](https://github.com/bitcoindatalabs/ln-client-diversity) | `get_ln_client_diversity` | 857 gossip snapshots, 132,360 closes, 2026 CLN shutdown metrics (`arXiv:2610.20952`) |
|
|
86
|
+
| [`ln-upgrade-dynamics`](https://github.com/bitcoindatalabs/ln-upgrade-dynamics) | `get_ln_upgrade_dynamics` | 814 usable daily snapshots, 12 disclosures, release-line patch lag (`arXiv:2610.30350`) |
|
|
87
|
+
| [`ln-force-close-costs`](https://github.com/bitcoindatalabs/ln-force-close-costs) | `get_ln_force_close_costs` | 973,581 channel closes (523,815 force closes) through block 974,041 (`arXiv:2611.16311`) |
|
|
88
|
+
| [`lightning-data`](https://github.com/bitcoindatalabs/lightning-data) | `get_ln_network_snapshot` | Weekly network snapshot + DuckDB PlebRank top-node leaderboard (`node_rank.parquet`) |
|
|
89
|
+
| [`orange-dev-tracker`](https://github.com/bitcoindatalabs/orange-dev-tracker) | `get_core_dev_health` | Monthly *State of Bitcoin Core* engineering KPIs, review health & maintainer footprints |
|
|
90
|
+
| [`orange-dev-data`](https://github.com/bitcoindatalabs/orange-dev-data) | `get_core_dev_health`, `get_bip_status` | Maintainer footprints + DuckDB search over 218 BIPs (`Deployed`, `Draft`, `Closed`, `Complete`) |
|
|
91
|
+
| [`orange-funding-data`](https://github.com/bitcoindatalabs/orange-funding-data) | `get_ecosystem_funding` | 20 funding organizations & 277 sponsored open-source developers |
|
|
92
|
+
| [`oss-app-stats`](https://github.com/bitcoindatalabs/oss-app-stats) | `get_oss_app_stats` | Release cadence, GitHub stars & download counts across 29 core OSS projects |
|
|
93
|
+
| [`orange-eco-data`](https://github.com/bitcoindatalabs/orange-eco-data) | `get_oss_ecosystem_health` | 1,009 ecosystem repos & 109 curated projects across 14 layers: security maturity tiers, `SECURITY.md` coverage, and issue health |
|
|
94
|
+
| [`coldcard-rng-tracker`](https://github.com/bitcoindatalabs/coldcard-rng-tracker) | `get_coldcard_forensics_summary` | Aggregate Coldcard weak-RNG sweep metrics, 10 attack waves & timeline (aggregates only) |
|
|
95
|
+
| [`mining-pools-data`](https://github.com/bitcoindatalabs/mining-pools-data) | `get_mining_pool_concentration` | 167 mining pools tracked with per-year HHI and top-3 share across `2009`–`2026` |
|
|
96
|
+
|
|
97
|
+
### Read-Only MCP Resources & Prompts
|
|
98
|
+
|
|
99
|
+
- **Resources:** `bdl://attribution`, `bdl://overview`, `bdl://papers`, `bdl://lightning/snapshot`, `bdl://core-dev/latest`, `bdl://ecosystem`, `bdl://coldcard/summary`
|
|
100
|
+
- **Prompts:** `lightning_security_brief`, `core_governance_brief`, `regulatory_data_brief`
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
## Data Ethics & Attribution
|
|
105
|
+
|
|
106
|
+
- Security outputs are **aggregates only** (no per-node vulnerability rankings or victim PII).
|
|
107
|
+
- Server code is **MIT**-licensed; underlying Bitcoin Data Labs datasets are published under **CC BY 4.0**.
|
|
108
|
+
- Attribution: `Source: Bitcoin Data Labs (bitcoindatalabs.org)` — ORCID [`0009-0004-7944-3492`](https://orcid.org/0009-0004-7944-3492).
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
<!-- mcp-name: io.github.bitcoindatalabs/bitcoindatalabs-mcp -->
|
|
2
|
+
|
|
3
|
+
# bitcoindatalabs-mcp
|
|
4
|
+
|
|
5
|
+
[](https://pypi.org/project/bitcoindatalabs-mcp/)
|
|
6
|
+
[](https://glama.ai/mcp/servers/bitcoindatalabs/bitcoindatalabs-mcp)
|
|
7
|
+
[](LICENSE)
|
|
8
|
+
[](pyproject.toml)
|
|
9
|
+
[](https://bitcoindatalabs.org)
|
|
10
|
+
|
|
11
|
+
Zero-clone **Model Context Protocol (MCP)** server for [Bitcoin Data Labs](https://bitcoindatalabs.org) open telemetry, open-source ecosystem security metrics, and reproducible empirical research.
|
|
12
|
+
|
|
13
|
+
Query **1,009 ecosystem OSS repositories**, **Bitcoin Core governance & BIPs**, **developer funding**, **three peer-cited Lightning Network security studies (`arXiv:2610.20952`, `2610.30350`, `2611.16311`)**, **mining pool HHI concentration**, and **aggregate on-chain forensics** inside Claude, Cursor, Antigravity, or VS Code — without cloning any data repositories.
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## Quick Start (Zero Clone)
|
|
18
|
+
|
|
19
|
+
`bitcoindatalabs-mcp` lazily fetches only the JSON and Parquet files your query needs from `github.com/bitcoindatalabs/*` and caches them in `~/.cache/bitcoindatalabs-mcp/` (DuckDB queries Parquet slices in memory).
|
|
20
|
+
|
|
21
|
+
### Claude Desktop / Cursor / Antigravity (`mcpServers`)
|
|
22
|
+
|
|
23
|
+
```json
|
|
24
|
+
{
|
|
25
|
+
"mcpServers": {
|
|
26
|
+
"bitcoindatalabs-mcp": {
|
|
27
|
+
"command": "uvx",
|
|
28
|
+
"args": ["bitcoindatalabs-mcp"]
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### Local Python Install (also installs the `bdl-mcp` CLI alias)
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install bitcoindatalabs-mcp
|
|
38
|
+
bitcoindatalabs-mcp # or CLI alias: bdl-mcp
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
For local development against cloned `bitcoindatalabs/*` repositories, set `BDL_GITHUB_ROOT` to avoid HTTPS requests:
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
export BDL_GITHUB_ROOT=/path/to/github/checkouts
|
|
45
|
+
pip install -e ".[dev]"
|
|
46
|
+
pytest -v
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
## Datasets, Tools & Resources (`11` Repositories, `13` Tools, `7` Resources)
|
|
52
|
+
|
|
53
|
+
| Repository | MCP Tool | Empirical Coverage |
|
|
54
|
+
| :--- | :--- | :--- |
|
|
55
|
+
| Meta / Papers | `list_datasets`, `get_research_papers` | Full catalog + summaries, arXiv DOIs & BibTeX for the 3 Lightning security papers |
|
|
56
|
+
| [`ln-client-diversity`](https://github.com/bitcoindatalabs/ln-client-diversity) | `get_ln_client_diversity` | 857 gossip snapshots, 132,360 closes, 2026 CLN shutdown metrics (`arXiv:2610.20952`) |
|
|
57
|
+
| [`ln-upgrade-dynamics`](https://github.com/bitcoindatalabs/ln-upgrade-dynamics) | `get_ln_upgrade_dynamics` | 814 usable daily snapshots, 12 disclosures, release-line patch lag (`arXiv:2610.30350`) |
|
|
58
|
+
| [`ln-force-close-costs`](https://github.com/bitcoindatalabs/ln-force-close-costs) | `get_ln_force_close_costs` | 973,581 channel closes (523,815 force closes) through block 974,041 (`arXiv:2611.16311`) |
|
|
59
|
+
| [`lightning-data`](https://github.com/bitcoindatalabs/lightning-data) | `get_ln_network_snapshot` | Weekly network snapshot + DuckDB PlebRank top-node leaderboard (`node_rank.parquet`) |
|
|
60
|
+
| [`orange-dev-tracker`](https://github.com/bitcoindatalabs/orange-dev-tracker) | `get_core_dev_health` | Monthly *State of Bitcoin Core* engineering KPIs, review health & maintainer footprints |
|
|
61
|
+
| [`orange-dev-data`](https://github.com/bitcoindatalabs/orange-dev-data) | `get_core_dev_health`, `get_bip_status` | Maintainer footprints + DuckDB search over 218 BIPs (`Deployed`, `Draft`, `Closed`, `Complete`) |
|
|
62
|
+
| [`orange-funding-data`](https://github.com/bitcoindatalabs/orange-funding-data) | `get_ecosystem_funding` | 20 funding organizations & 277 sponsored open-source developers |
|
|
63
|
+
| [`oss-app-stats`](https://github.com/bitcoindatalabs/oss-app-stats) | `get_oss_app_stats` | Release cadence, GitHub stars & download counts across 29 core OSS projects |
|
|
64
|
+
| [`orange-eco-data`](https://github.com/bitcoindatalabs/orange-eco-data) | `get_oss_ecosystem_health` | 1,009 ecosystem repos & 109 curated projects across 14 layers: security maturity tiers, `SECURITY.md` coverage, and issue health |
|
|
65
|
+
| [`coldcard-rng-tracker`](https://github.com/bitcoindatalabs/coldcard-rng-tracker) | `get_coldcard_forensics_summary` | Aggregate Coldcard weak-RNG sweep metrics, 10 attack waves & timeline (aggregates only) |
|
|
66
|
+
| [`mining-pools-data`](https://github.com/bitcoindatalabs/mining-pools-data) | `get_mining_pool_concentration` | 167 mining pools tracked with per-year HHI and top-3 share across `2009`–`2026` |
|
|
67
|
+
|
|
68
|
+
### Read-Only MCP Resources & Prompts
|
|
69
|
+
|
|
70
|
+
- **Resources:** `bdl://attribution`, `bdl://overview`, `bdl://papers`, `bdl://lightning/snapshot`, `bdl://core-dev/latest`, `bdl://ecosystem`, `bdl://coldcard/summary`
|
|
71
|
+
- **Prompts:** `lightning_security_brief`, `core_governance_brief`, `regulatory_data_brief`
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
|
|
75
|
+
## Data Ethics & Attribution
|
|
76
|
+
|
|
77
|
+
- Security outputs are **aggregates only** (no per-node vulnerability rankings or victim PII).
|
|
78
|
+
- Server code is **MIT**-licensed; underlying Bitcoin Data Labs datasets are published under **CC BY 4.0**.
|
|
79
|
+
- Attribution: `Source: Bitcoin Data Labs (bitcoindatalabs.org)` — ORCID [`0009-0004-7944-3492`](https://orcid.org/0009-0004-7944-3492).
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
|
|
2
|
+
[build-system]
|
|
3
|
+
requires = ["setuptools>=68.0"]
|
|
4
|
+
build-backend = "setuptools.build_meta"
|
|
5
|
+
|
|
6
|
+
[project]
|
|
7
|
+
name = "bitcoindatalabs-mcp"
|
|
8
|
+
version = "0.1.0"
|
|
9
|
+
description = "Zero-clone Model Context Protocol (MCP) server for Bitcoin Data Labs open telemetry: Bitcoin Core governance, BIPs, OSS ecosystem security posture (1,009 repos), Lightning security research, mining concentration, and on-chain forensic aggregates."
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
requires-python = ">=3.11"
|
|
13
|
+
authors = [
|
|
14
|
+
{ name = "Saurabh Kumar" },
|
|
15
|
+
]
|
|
16
|
+
keywords = [
|
|
17
|
+
"mcp",
|
|
18
|
+
"model-context-protocol",
|
|
19
|
+
"bitcoin",
|
|
20
|
+
"lightning-network",
|
|
21
|
+
"bitcoin-data-labs",
|
|
22
|
+
"open-source-software",
|
|
23
|
+
"supply-chain-security",
|
|
24
|
+
"security-research",
|
|
25
|
+
"duckdb",
|
|
26
|
+
"parquet",
|
|
27
|
+
]
|
|
28
|
+
classifiers = [
|
|
29
|
+
"Development Status :: 4 - Beta",
|
|
30
|
+
"Intended Audience :: Developers",
|
|
31
|
+
"Intended Audience :: Science/Research",
|
|
32
|
+
"Programming Language :: Python :: 3",
|
|
33
|
+
"Programming Language :: Python :: 3.11",
|
|
34
|
+
"Programming Language :: Python :: 3.12",
|
|
35
|
+
"Programming Language :: Python :: 3.13",
|
|
36
|
+
"Topic :: Scientific/Engineering :: Information Analysis",
|
|
37
|
+
]
|
|
38
|
+
dependencies = [
|
|
39
|
+
"mcp>=2.0.0",
|
|
40
|
+
"duckdb>=1.1.0",
|
|
41
|
+
"httpx>=0.27.0",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
[project.optional-dependencies]
|
|
45
|
+
dev = [
|
|
46
|
+
"pytest>=8.0",
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
[project.scripts]
|
|
50
|
+
bitcoindatalabs-mcp = "bitcoindatalabs_mcp.server:main"
|
|
51
|
+
bdl-mcp = "bitcoindatalabs_mcp.server:main"
|
|
52
|
+
|
|
53
|
+
[project.urls]
|
|
54
|
+
Homepage = "https://bitcoindatalabs.org"
|
|
55
|
+
Repository = "https://github.com/bitcoindatalabs/bitcoindatalabs-mcp"
|
|
56
|
+
"Research" = "https://bitcoindatalabs.org/research.html"
|
|
57
|
+
"Data Catalog" = "https://bitcoindatalabs.org/work.html"
|
|
58
|
+
|
|
59
|
+
[tool.setuptools.packages.find]
|
|
60
|
+
where = ["src"]
|
|
61
|
+
|
|
62
|
+
[tool.pytest.ini_options]
|
|
63
|
+
testpaths = ["tests"]
|
|
64
|
+
pythonpath = ["src"]
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
|
|
2
|
+
"""Zero-clone data resolver and DuckDB Parquet reader for Bitcoin Data Labs repos."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
import tempfile
|
|
10
|
+
import time
|
|
11
|
+
from datetime import date, datetime
|
|
12
|
+
from decimal import Decimal
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
import duckdb
|
|
17
|
+
import httpx
|
|
18
|
+
|
|
19
|
+
DEFAULT_GITHUB_ORG = "bitcoindatalabs"
|
|
20
|
+
DEFAULT_BRANCH = "main"
|
|
21
|
+
DEFAULT_CACHE_TTL_HOURS = 24.0
|
|
22
|
+
|
|
23
|
+
_JSON_MEM_CACHE: dict[tuple[str, float], Any] = {}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def get_github_org() -> str:
|
|
27
|
+
return os.environ.get("BDL_GITHUB_ORG", DEFAULT_GITHUB_ORG).strip() or DEFAULT_GITHUB_ORG
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def get_cache_dir() -> Path:
|
|
31
|
+
env_dir = os.environ.get("BDL_MCP_CACHE_DIR")
|
|
32
|
+
if env_dir:
|
|
33
|
+
return Path(env_dir).expanduser().resolve()
|
|
34
|
+
return Path.home() / ".cache" / "bitcoindatalabs-mcp"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def get_cache_ttl_seconds() -> float:
|
|
38
|
+
raw = os.environ.get("BDL_MCP_CACHE_TTL_HOURS", str(DEFAULT_CACHE_TTL_HOURS))
|
|
39
|
+
try:
|
|
40
|
+
return max(0.0, float(raw) * 3600.0)
|
|
41
|
+
except ValueError:
|
|
42
|
+
return DEFAULT_CACHE_TTL_HOURS * 3600.0
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _normalize_rel_path(rel_path: str) -> str:
|
|
46
|
+
clean = rel_path.lstrip("/")
|
|
47
|
+
if ".." in Path(clean).parts:
|
|
48
|
+
raise ValueError(f"Invalid relative data path: {rel_path!r}")
|
|
49
|
+
return clean
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _find_local_file(repo: str, rel_path: str) -> Path | None:
|
|
53
|
+
"""Resolve against BDL_GITHUB_ROOT (or default local github checkout dir if present)."""
|
|
54
|
+
if os.environ.get("BDL_FORCE_REMOTE", "").lower() in {"1", "true", "yes"}:
|
|
55
|
+
return None
|
|
56
|
+
root_env = os.environ.get("BDL_GITHUB_ROOT")
|
|
57
|
+
candidates_roots: list[Path] = []
|
|
58
|
+
if root_env:
|
|
59
|
+
candidates_roots.append(Path(root_env).expanduser().resolve())
|
|
60
|
+
else:
|
|
61
|
+
default_root = Path("/home/sorukumar/dev/github")
|
|
62
|
+
if default_root.is_dir():
|
|
63
|
+
candidates_roots.append(default_root)
|
|
64
|
+
for root in candidates_roots:
|
|
65
|
+
candidate = root / repo / rel_path
|
|
66
|
+
if candidate.is_file():
|
|
67
|
+
return candidate
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _is_fresh(path: Path, ttl_seconds: float) -> bool:
|
|
72
|
+
if not path.is_file() or path.stat().st_size == 0 or ttl_seconds <= 0:
|
|
73
|
+
return False
|
|
74
|
+
return (time.time() - path.stat().st_mtime) <= ttl_seconds
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def resolve_file(repo: str, rel_path: str) -> Path:
|
|
78
|
+
"""
|
|
79
|
+
Resolve a Bitcoin Data Labs dataset file locally or lazily cache it from GitHub Raw.
|
|
80
|
+
|
|
81
|
+
Order:
|
|
82
|
+
1. Local checkout under BDL_GITHUB_ROOT (or /home/sorukumar/dev/github).
|
|
83
|
+
2. Fresh cached copy under ~/.cache/bitcoindatalabs-mcp/<repo>/<rel_path>.
|
|
84
|
+
3. Atomic HTTPS download from raw.githubusercontent.com/<org>/<repo>/main/<rel_path>.
|
|
85
|
+
"""
|
|
86
|
+
clean = _normalize_rel_path(rel_path)
|
|
87
|
+
local_path = _find_local_file(repo, clean)
|
|
88
|
+
if local_path is not None:
|
|
89
|
+
return local_path
|
|
90
|
+
|
|
91
|
+
cache_path = get_cache_dir() / repo / clean
|
|
92
|
+
if _is_fresh(cache_path, get_cache_ttl_seconds()):
|
|
93
|
+
return cache_path
|
|
94
|
+
|
|
95
|
+
org = get_github_org()
|
|
96
|
+
url = f"https://raw.githubusercontent.com/{org}/{repo}/{DEFAULT_BRANCH}/{clean}"
|
|
97
|
+
cache_path.parent.mkdir(parents=True, exist_ok=True)
|
|
98
|
+
tmp_fd, tmp_name = tempfile.mkstemp(
|
|
99
|
+
prefix=".tmp_", suffix=cache_path.suffix or ".tmp", dir=str(cache_path.parent)
|
|
100
|
+
)
|
|
101
|
+
tmp_path = Path(tmp_name)
|
|
102
|
+
try:
|
|
103
|
+
os.close(tmp_fd)
|
|
104
|
+
with httpx.Client(timeout=60.0, follow_redirects=True) as client:
|
|
105
|
+
with client.stream("GET", url) as resp:
|
|
106
|
+
resp.raise_for_status()
|
|
107
|
+
with tmp_path.open("wb") as out:
|
|
108
|
+
for chunk in resp.iter_bytes(chunk_size=65536):
|
|
109
|
+
out.write(chunk)
|
|
110
|
+
os.replace(tmp_path, cache_path)
|
|
111
|
+
return cache_path
|
|
112
|
+
except Exception:
|
|
113
|
+
if tmp_path.exists():
|
|
114
|
+
tmp_path.unlink(missing_ok=True)
|
|
115
|
+
if cache_path.is_file() and cache_path.stat().st_size > 0:
|
|
116
|
+
return cache_path
|
|
117
|
+
raise
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def load_json(repo: str, rel_path: str) -> Any:
|
|
121
|
+
"""Load and memoize a JSON dataset by resolved path + mtime."""
|
|
122
|
+
resolved = resolve_file(repo, rel_path)
|
|
123
|
+
key = (str(resolved), resolved.stat().st_mtime)
|
|
124
|
+
if key in _JSON_MEM_CACHE:
|
|
125
|
+
return _JSON_MEM_CACHE[key]
|
|
126
|
+
data = json.loads(resolved.read_text(encoding="utf-8"))
|
|
127
|
+
if len(_JSON_MEM_CACHE) > 64:
|
|
128
|
+
_JSON_MEM_CACHE.clear()
|
|
129
|
+
_JSON_MEM_CACHE[key] = data
|
|
130
|
+
return data
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def clean_value(val: Any) -> Any:
|
|
134
|
+
"""Normalize DuckDB/Decimal/datetime/NaN scalars into strict JSON values."""
|
|
135
|
+
if val is None:
|
|
136
|
+
return None
|
|
137
|
+
if isinstance(val, float) and (math.isnan(val) or math.isinf(val)):
|
|
138
|
+
return None
|
|
139
|
+
if isinstance(val, Decimal):
|
|
140
|
+
return float(val)
|
|
141
|
+
if isinstance(val, (datetime, date)):
|
|
142
|
+
return val.isoformat()
|
|
143
|
+
if hasattr(val, "item") and callable(val.item):
|
|
144
|
+
return clean_value(val.item())
|
|
145
|
+
if isinstance(val, dict):
|
|
146
|
+
return {str(k): clean_value(v) for k, v in val.items()}
|
|
147
|
+
if isinstance(val, (list, tuple)):
|
|
148
|
+
return [clean_value(v) for v in val]
|
|
149
|
+
return val
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def query_parquet(
|
|
153
|
+
tables: dict[str, tuple[str, str]],
|
|
154
|
+
sql: str,
|
|
155
|
+
params: list[Any] | tuple[Any, ...] = (),
|
|
156
|
+
) -> list[dict[str, Any]]:
|
|
157
|
+
"""
|
|
158
|
+
Execute parameterized SQL in an ephemeral in-memory DuckDB connection.
|
|
159
|
+
|
|
160
|
+
`tables` maps SQL view name -> (repo_name, rel_path).
|
|
161
|
+
"""
|
|
162
|
+
con = duckdb.connect(database=":memory:")
|
|
163
|
+
try:
|
|
164
|
+
for alias, (repo, rel_path) in tables.items():
|
|
165
|
+
resolved = resolve_file(repo, rel_path)
|
|
166
|
+
con.read_parquet(str(resolved)).create_view(alias)
|
|
167
|
+
cursor = con.execute(sql, list(params))
|
|
168
|
+
cols = [desc[0] for desc in (cursor.description or [])]
|
|
169
|
+
return [
|
|
170
|
+
{col: clean_value(val) for col, val in zip(cols, row)}
|
|
171
|
+
for row in cursor.fetchall()
|
|
172
|
+
]
|
|
173
|
+
finally:
|
|
174
|
+
con.close()
|