eolas-data 1.9.1__tar.gz → 1.10.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 (53) hide show
  1. {eolas_data-1.9.1 → eolas_data-1.10.0}/.github/workflows/publish.yml +7 -1
  2. {eolas_data-1.9.1 → eolas_data-1.10.0}/.github/workflows/smoke.yml +3 -3
  3. {eolas_data-1.9.1 → eolas_data-1.10.0}/.github/workflows/test.yml +4 -4
  4. {eolas_data-1.9.1 → eolas_data-1.10.0}/CHANGELOG.md +22 -0
  5. {eolas_data-1.9.1 → eolas_data-1.10.0}/PKG-INFO +1 -1
  6. {eolas_data-1.9.1 → eolas_data-1.10.0}/eolas_data/__init__.py +1 -1
  7. eolas_data-1.10.0/eolas_data/mcp_server.py +283 -0
  8. {eolas_data-1.9.1 → eolas_data-1.10.0}/pyproject.toml +1 -1
  9. {eolas_data-1.9.1 → eolas_data-1.10.0}/scripts/check_client_contract.py +12 -0
  10. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_geometry_param.py +88 -0
  11. eolas_data-1.10.0/tests/test_mcp_integration.py +68 -0
  12. eolas_data-1.10.0/tests/test_mcp_protocol.py +89 -0
  13. eolas_data-1.10.0/tests/test_mcp_server.py +267 -0
  14. {eolas_data-1.9.1 → eolas_data-1.10.0}/.github/workflows/catalog-drift.yml +0 -0
  15. {eolas_data-1.9.1 → eolas_data-1.10.0}/.github/workflows/pre-release.yml +0 -0
  16. {eolas_data-1.9.1 → eolas_data-1.10.0}/.gitignore +0 -0
  17. {eolas_data-1.9.1 → eolas_data-1.10.0}/LICENSE +0 -0
  18. {eolas_data-1.9.1 → eolas_data-1.10.0}/README.md +0 -0
  19. {eolas_data-1.9.1 → eolas_data-1.10.0}/eolas_data/_dataset_names.py +0 -0
  20. {eolas_data-1.9.1 → eolas_data-1.10.0}/eolas_data/_regen_names.py +0 -0
  21. {eolas_data-1.9.1 → eolas_data-1.10.0}/eolas_data/cdc.py +0 -0
  22. {eolas_data-1.9.1 → eolas_data-1.10.0}/eolas_data/cli.py +0 -0
  23. {eolas_data-1.9.1 → eolas_data-1.10.0}/eolas_data/client.py +0 -0
  24. {eolas_data-1.9.1 → eolas_data-1.10.0}/eolas_data/console.py +0 -0
  25. {eolas_data-1.9.1 → eolas_data-1.10.0}/eolas_data/dataset.py +0 -0
  26. {eolas_data-1.9.1 → eolas_data-1.10.0}/eolas_data/exceptions.py +0 -0
  27. {eolas_data-1.9.1 → eolas_data-1.10.0}/eolas_data/library.py +0 -0
  28. {eolas_data-1.9.1 → eolas_data-1.10.0}/eolas_data/meta.py +0 -0
  29. {eolas_data-1.9.1 → eolas_data-1.10.0}/eolas_data/rows.py +0 -0
  30. {eolas_data-1.9.1 → eolas_data-1.10.0}/eolas_data/schedule.py +0 -0
  31. {eolas_data-1.9.1 → eolas_data-1.10.0}/eolas_data/search.py +0 -0
  32. {eolas_data-1.9.1 → eolas_data-1.10.0}/scripts/preflight.sh +0 -0
  33. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/fixtures/source_helpers.json +0 -0
  34. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_as_arrow.py +0 -0
  35. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_cdc_roundtrip.py +0 -0
  36. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_changes_http.py +0 -0
  37. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_cli.py +0 -0
  38. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_client.py +0 -0
  39. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_date_filter.py +0 -0
  40. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_get_local.py +0 -0
  41. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_keyring.py +0 -0
  42. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_library.py +0 -0
  43. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_meta.py +0 -0
  44. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_preview_dimensions.py +0 -0
  45. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_progress.py +0 -0
  46. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_resilience.py +0 -0
  47. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_rows.py +0 -0
  48. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_schedule.py +0 -0
  49. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_search.py +0 -0
  50. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_smoke_live.py +0 -0
  51. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_source_helpers.py +0 -0
  52. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_sync_bulk.py +0 -0
  53. {eolas_data-1.9.1 → eolas_data-1.10.0}/tests/test_sync_changes.py +0 -0
@@ -69,7 +69,13 @@ jobs:
69
69
  - name: Install wheel + test deps
70
70
  run: |
71
71
  WHL=$(ls -1 dist/*.whl | head -1)
72
- pip install "$WHL"
72
+ # Install the wheel WITH its [mcp] extra, so this gate actually
73
+ # resolves and imports the optional surface it ships. Installing the
74
+ # bare wheel let the mcp test files fail to collect (No module named
75
+ # 'mcp') on the 1.10.0 tag — and, more importantly, would have let the
76
+ # [mcp] extra ship broken (declared entry point, missing module) on
77
+ # every release from 1.3.22 to 1.9.1 without this gate noticing.
78
+ pip install "$WHL[mcp]"
73
79
  pip install pytest responses geopandas shapely pandas pyarrow typer rich keyring
74
80
 
75
81
  - name: Version self-report parity (REL-1)
@@ -25,8 +25,8 @@ jobs:
25
25
  exit 1
26
26
  fi
27
27
 
28
- - name: Install package + dev/geo deps (as users would)
29
- run: pip install ".[dev,geo]"
28
+ - name: Install package + dev/geo/mcp deps (as users would)
29
+ run: pip install ".[dev,geo,mcp]"
30
30
 
31
31
  - name: Live smoke tests
32
32
  env:
@@ -36,4 +36,4 @@ jobs:
36
36
  echo "EOLAS_API_KEY secret not configured — skipping scheduled smoke tests."
37
37
  exit 0
38
38
  fi
39
- pytest -q -m integration tests/test_smoke_live.py
39
+ pytest -q -m integration tests/test_smoke_live.py tests/test_mcp_integration.py
@@ -32,8 +32,8 @@ jobs:
32
32
  with:
33
33
  python-version: ${{ matrix.python-version }}
34
34
 
35
- - name: Install package + dev + geo + secure (editable)
36
- run: pip install -e ".[dev,geo,secure]"
35
+ - name: Install package + dev + geo + secure + mcp (editable)
36
+ run: pip install -e ".[dev,geo,secure,mcp]"
37
37
 
38
38
  - name: pytest (unit suite)
39
39
  run: pytest -q -m "not integration"
@@ -57,7 +57,7 @@ jobs:
57
57
  run: |
58
58
  WHL=$(ls -1 dist/*.whl | head -1)
59
59
  pip install "$WHL"
60
- pip install pytest responses geopandas shapely pandas pyarrow typer rich keyring
60
+ pip install pytest responses geopandas shapely pandas pyarrow typer rich keyring "mcp>=1.0"
61
61
 
62
62
  - name: pytest on installed package
63
63
  run: pytest -q -m "not integration"
@@ -74,7 +74,7 @@ jobs:
74
74
  - uses: actions/setup-python@v5
75
75
  with:
76
76
  python-version: "3.12"
77
- - run: pip install -e ".[dev,geo,secure]" pytest-cov
77
+ - run: pip install -e ".[dev,geo,secure,mcp]" pytest-cov
78
78
  - run: pytest -q -m "not integration" --cov=eolas_data --cov-report=xml
79
79
  - name: Upload coverage
80
80
  uses: codecov/codecov-action@v5
@@ -3,6 +3,28 @@
3
3
  All notable changes to `eolas-data` are recorded here. This project follows
4
4
  [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## 1.10.0
7
+
8
+ ### Added
9
+
10
+ - **MCP server (`eolas-mcp`) — now actually present.** `eolas_data/mcp_server.py`
11
+ exposes the client as Model Context Protocol tools over stdio for agent hosts
12
+ (Claude Desktop, Cursor, Grok): `eolas_health`, `eolas_search`, `eolas_info`,
13
+ `eolas_get`, `eolas_download`, `eolas_sync`. A thin wrapper — all HTTP, auth,
14
+ CDC routing and error mapping stay in `Client`. Agent-safe caps: `eolas_get`
15
+ is hard-limited to 500 rows and `eolas_search` to 50, so nothing streams a
16
+ multi-million-row table into a model's context. Install with
17
+ `pip install eolas-data[mcp]`; run `eolas-mcp` or `python -m eolas_data.mcp_server`.
18
+
19
+ ### Fixed
20
+
21
+ - **The `[mcp]` extra and `eolas-mcp` entry point have been broken since 1.3.22.**
22
+ `pyproject.toml` declared both, but the `eolas_data.mcp_server` module was never
23
+ committed — so `pip install eolas-data[mcp]` created an `eolas-mcp` command that
24
+ failed with `ModuleNotFoundError` on every release from 1.3.22 to 1.9.1.
25
+ Verified against a clean install of the published 1.9.1 wheel. This release
26
+ ships the module the packaging has been promising.
27
+
6
28
  ## 1.9.1
7
29
 
8
30
  ### Changed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: eolas-data
3
- Version: 1.9.1
3
+ Version: 1.10.0
4
4
  Summary: Python client for the eolas.fyi statistical data API (NZ + OECD; Australia on roadmap)
5
5
  Project-URL: Homepage, https://eolas.fyi
6
6
  Project-URL: Documentation, https://docs.eolas.fyi/
@@ -26,7 +26,7 @@ from .exceptions import (
26
26
  try:
27
27
  __version__ = _pkg_version("eolas-data")
28
28
  except PackageNotFoundError: # pragma: no cover - uninstalled source checkout
29
- __version__ = "1.9.1"
29
+ __version__ = "1.10.0"
30
30
 
31
31
  __all__ = [
32
32
  "Client",
@@ -0,0 +1,283 @@
1
+ """eolas MCP server — stdio transport for Claude Desktop, Cursor, Grok, etc.
2
+
3
+ Thin wrapper over :class:`eolas_data.Client`. All HTTP, auth, CDC routing, and
4
+ error mapping stay in the Python client; this module only exposes typed tools
5
+ for agent hosts.
6
+
7
+ Run::
8
+
9
+ eolas-mcp # after pip install eolas-data[mcp]
10
+ python -m eolas_data.mcp_server
11
+
12
+ Auth resolves the same way as the CLI: ``EOLAS_API_KEY`` env var, OS keyring
13
+ (``pip install eolas-data[secure]``), or ``~/.eolas/config.json``.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ from pathlib import Path
19
+ from typing import Any, Optional
20
+
21
+ from mcp.server.fastmcp import FastMCP
22
+
23
+ from .client import Client, SyncResult
24
+ from .exceptions import EolasError
25
+ from .meta import _TABLE_META_KEYS
26
+
27
+ # Hard caps — never stream multi-million-row tables into model context.
28
+ _MCP_GET_ROW_CAP = 500
29
+ _MCP_SEARCH_CAP = 50
30
+
31
+ mcp = FastMCP(
32
+ "eolas",
33
+ instructions=(
34
+ "Tools for the eolas.fyi statistical & geospatial data API (NZ + OECD). "
35
+ "Use eolas_search then eolas_info before fetching unknown dataset names. "
36
+ "For whole datasets prefer eolas_sync (keeps a local file current) or "
37
+ "eolas_download (one-shot bulk file). Use eolas_get only for small slices."
38
+ ),
39
+ )
40
+
41
+ _client: Optional[Client] = None
42
+
43
+
44
+ def _get_client() -> Client:
45
+ global _client
46
+ if _client is None:
47
+ _client = Client()
48
+ return _client
49
+
50
+
51
+ def _set_client(client: Optional[Client]) -> None:
52
+ """Test hook — inject a mock client."""
53
+ global _client
54
+ _client = client
55
+
56
+
57
+ def _json_safe(value: Any) -> Any:
58
+ if value is None or isinstance(value, (bool, int, float, str)):
59
+ return value
60
+ if isinstance(value, Path):
61
+ return str(value)
62
+ if isinstance(value, dict):
63
+ return {str(k): _json_safe(v) for k, v in value.items()}
64
+ if isinstance(value, (list, tuple)):
65
+ return [_json_safe(v) for v in value]
66
+ return str(value)
67
+
68
+
69
+ def _df_records(df, *, max_rows: int) -> list[dict]:
70
+ import pandas as pd
71
+
72
+ if df is None or (hasattr(df, "empty") and df.empty):
73
+ return []
74
+ subset = df.head(max_rows)
75
+ records = json.loads(
76
+ subset.to_json(orient="records", date_format="iso", default_handler=str)
77
+ )
78
+ return records
79
+
80
+
81
+ def _compact_info(meta: dict) -> dict:
82
+ out = {k: meta[k] for k in _TABLE_META_KEYS if k in meta}
83
+ for extra in ("table", "replication_mode", "cdc_serving_tier", "pk_columns"):
84
+ if extra in meta and extra not in out:
85
+ out[extra] = meta[extra]
86
+ return _json_safe(out)
87
+
88
+
89
+ def _sync_payload(result: SyncResult, *, freshness: str, fmt: str) -> dict:
90
+ payload: dict[str, Any] = {
91
+ "status": result.status,
92
+ "path": str(result.path),
93
+ "bytes_downloaded": result.bytes_downloaded,
94
+ "sync_mode": result.sync_mode or "snapshot",
95
+ "format": fmt,
96
+ "freshness": freshness,
97
+ "previous_snapshot_id": result.previous_snapshot_id,
98
+ "current_snapshot_id": result.current_snapshot_id,
99
+ }
100
+ if result.sync_mode == "changelog":
101
+ payload["previous_seq"] = result.previous_seq
102
+ payload["current_seq"] = result.current_seq
103
+ payload["ops_applied"] = result.ops_applied
104
+ return _json_safe(payload)
105
+
106
+
107
+ def _map_error(exc: Exception) -> str:
108
+ if isinstance(exc, EolasError):
109
+ return str(exc)
110
+ return f"{type(exc).__name__}: {exc}"
111
+
112
+
113
+ @mcp.tool()
114
+ def eolas_health() -> dict:
115
+ """Check api.eolas.fyi reachability (no API key required)."""
116
+ import requests
117
+
118
+ try:
119
+ r = requests.get("https://api.eolas.fyi/health", timeout=10)
120
+ r.raise_for_status()
121
+ body = r.json()
122
+ return {"ok": True, "status_code": r.status_code, "body": _json_safe(body)}
123
+ except Exception as exc:
124
+ return {"ok": False, "error": _map_error(exc)}
125
+
126
+
127
+ @mcp.tool()
128
+ def eolas_search(
129
+ query: str,
130
+ source: Optional[str] = None,
131
+ limit: int = 25,
132
+ ) -> dict:
133
+ """Search datasets by name, title, or description (alias-aware).
134
+
135
+ Returns compact rows: name, title, source. Use eolas_info for full metadata.
136
+ """
137
+ limit = max(1, min(int(limit), _MCP_SEARCH_CAP))
138
+ try:
139
+ df = _get_client().search(query, source=source)
140
+ except EolasError as exc:
141
+ return {"error": _map_error(exc), "datasets": []}
142
+
143
+ cols = [c for c in ("name", "title", "source", "namespace") if c in df.columns]
144
+ if cols:
145
+ df = df[cols]
146
+ return {
147
+ "query": query,
148
+ "count": int(len(df)),
149
+ "datasets": _df_records(df, max_rows=limit),
150
+ "truncated": len(df) > limit,
151
+ }
152
+
153
+
154
+ @mcp.tool()
155
+ def eolas_info(name: str) -> dict:
156
+ """Dataset metadata — includes cdc_serving_tier, bulk_export_class, row counts."""
157
+ try:
158
+ meta = _get_client().info(name)
159
+ except EolasError as exc:
160
+ return {"error": _map_error(exc), "name": name}
161
+ return {"name": name, **_compact_info(meta)}
162
+
163
+
164
+ @mcp.tool()
165
+ def eolas_get(
166
+ name: str,
167
+ start: Optional[str] = None,
168
+ end: Optional[str] = None,
169
+ limit: int = 100,
170
+ ) -> dict:
171
+ """Fetch a small row slice via the live /data API.
172
+
173
+ Hard-capped at 500 rows. For whole datasets use eolas_download or eolas_sync.
174
+ """
175
+ cap = max(1, min(int(limit), _MCP_GET_ROW_CAP))
176
+ try:
177
+ df = _get_client().get(name, start=start, end=end, limit=cap)
178
+ except EolasError as exc:
179
+ return {"error": _map_error(exc), "name": name, "rows": []}
180
+
181
+ # Client.get returns a Dataset (DataFrame subclass).
182
+ row_count = len(df)
183
+ return {
184
+ "name": name,
185
+ "row_count": row_count,
186
+ "limit_applied": cap,
187
+ "truncated": row_count >= cap,
188
+ "rows": _df_records(df, max_rows=cap),
189
+ }
190
+
191
+
192
+ @mcp.tool()
193
+ def eolas_download(
194
+ name: str,
195
+ path: str,
196
+ format: str = "parquet",
197
+ freshness: str = "auto",
198
+ ) -> dict:
199
+ """One-shot bulk download to a local file (returns path + bytes, not file contents).
200
+
201
+ format: parquet | csv_gz | geoparquet. freshness: auto | monthly | current.
202
+ """
203
+ fmt = format.lower()
204
+ if fmt == "csv":
205
+ fmt = "csv_gz"
206
+ allowed = {"parquet", "csv_gz", "geoparquet"}
207
+ if fmt not in allowed:
208
+ return {
209
+ "error": f"unsupported format {format!r}; expected parquet, csv, or geoparquet",
210
+ "name": name,
211
+ }
212
+
213
+ out = Path(path).expanduser().resolve()
214
+ try:
215
+ result_path = _get_client().download_bulk(
216
+ name,
217
+ path=out,
218
+ format=fmt,
219
+ freshness=freshness,
220
+ progress=False,
221
+ )
222
+ except EolasError as exc:
223
+ return {"error": _map_error(exc), "name": name, "path": str(out)}
224
+
225
+ size = out.stat().st_size if out.exists() else 0
226
+ return _json_safe({
227
+ "name": name,
228
+ "path": str(result_path),
229
+ "bytes": size,
230
+ "format": fmt,
231
+ "freshness": freshness,
232
+ })
233
+
234
+
235
+ @mcp.tool()
236
+ def eolas_sync(
237
+ name: str,
238
+ path: str,
239
+ format: str = "parquet",
240
+ freshness: str = "auto",
241
+ ) -> dict:
242
+ """Keep a local file current — routes on cdc_serving_tier (snapshot or changelog CDC).
243
+
244
+ First call downloads; later calls are cheap (HEAD check or incremental /changes).
245
+ """
246
+ fmt = format.lower()
247
+ if fmt == "csv":
248
+ fmt = "csv_gz"
249
+ if fmt != "parquet":
250
+ meta = {}
251
+ try:
252
+ meta = _get_client().info(name)
253
+ except EolasError:
254
+ pass
255
+ tier = (meta.get("cdc_serving_tier") or "snapshot") if meta else "snapshot"
256
+ if tier == "changelog":
257
+ return {
258
+ "error": "changelog-tier datasets only support format='parquet'",
259
+ "name": name,
260
+ }
261
+
262
+ out = Path(path).expanduser().resolve()
263
+ try:
264
+ result = _get_client().sync(
265
+ name,
266
+ path=out,
267
+ format=fmt,
268
+ freshness=freshness,
269
+ progress=False,
270
+ )
271
+ except (EolasError, ValueError) as exc:
272
+ return {"error": _map_error(exc), "name": name, "path": str(out)}
273
+
274
+ return _sync_payload(result, freshness=freshness, fmt=fmt)
275
+
276
+
277
+ def main() -> None:
278
+ """Console entry point — stdio transport for MCP hosts."""
279
+ mcp.run(transport="stdio")
280
+
281
+
282
+ if __name__ == "__main__":
283
+ main()
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "eolas-data"
7
- version = "1.9.1"
7
+ version = "1.10.0"
8
8
  description = "Python client for the eolas.fyi statistical data API (NZ + OECD; Australia on roadmap)"
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -32,6 +32,18 @@ REQUIRED: dict[str, list[str]] = {
32
32
  "test_linz_nz_addresses_bulk_route_and_head",
33
33
  "test_client_exports_cache_clear",
34
34
  ],
35
+ "test_mcp_server.py": [
36
+ "test_eolas_sync_changelog_mode",
37
+ "test_eolas_get_caps_rows",
38
+ ],
39
+ "test_mcp_protocol.py": [
40
+ "test_stdio_lists_six_tools",
41
+ "test_stdio_eolas_health_over_wire",
42
+ ],
43
+ "test_mcp_integration.py": [
44
+ "test_mcp_info_nz_cpi_live",
45
+ "test_mcp_get_nz_cpi_slice_live",
46
+ ],
35
47
  }
36
48
 
37
49
 
@@ -297,3 +297,91 @@ def test_get_local_geometry_false_does_not_return_geodataframe(
297
297
  )
298
298
  assert type(out).__name__ != "GeoDataFrame"
299
299
  assert not hasattr(out, "crs")
300
+
301
+
302
+ # ---- format branches ---------------------------------------------------------
303
+ # These paths existed but had never been executed by any test: the csv_gz reader
304
+ # (which is also the OSError fallback when a Parquet read fails), the as_arrow
305
+ # reader, and GeoParquet's WKB `geometry` column — a DIFFERENT name from the
306
+ # `geometry_wkt` convention, excluded only because _GEOMETRY_COLUMNS lists both.
307
+
308
+
309
+ def _client_reading(monkeypatch, path):
310
+ c = Client("eolas_testkey123", base_url=BASE)
311
+ monkeypatch.setattr(c, "sync_bulk", lambda *a, **k: path)
312
+ return c
313
+
314
+
315
+ def test_csv_gz_read_honours_geometry_false(tmp_path, monkeypatch):
316
+ import pandas as pd
317
+
318
+ p = tmp_path / "x.csv.gz"
319
+ pd.DataFrame(
320
+ {"a": [1, 2], "b": ["x", "y"], "geometry_wkt": ["POINT(1 1)", "POINT(2 2)"]}
321
+ ).to_csv(p, index=False, compression="gzip")
322
+ c = _client_reading(monkeypatch, p)
323
+ out = c.get_local(
324
+ "x", cache_dir=tmp_path, format="csv_gz", meta=False, geometry=False
325
+ )
326
+ assert list(out.columns) == ["a", "b"]
327
+ assert len(out) == 2
328
+
329
+
330
+ def test_csv_gz_read_keeps_geometry_by_default(tmp_path, monkeypatch):
331
+ import pandas as pd
332
+
333
+ p = tmp_path / "x.csv.gz"
334
+ pd.DataFrame({"a": [1], "geometry_wkt": ["POINT(1 1)"]}).to_csv(
335
+ p, index=False, compression="gzip"
336
+ )
337
+ c = _client_reading(monkeypatch, p)
338
+ out = c.get_local(
339
+ "x", cache_dir=tmp_path, format="csv_gz", meta=False, as_geo=False
340
+ )
341
+ assert "geometry_wkt" in out.columns
342
+
343
+
344
+ def test_as_arrow_honours_geometry_false(tmp_path, monkeypatch):
345
+ import pandas as pd
346
+
347
+ p = tmp_path / "y.parquet"
348
+ pd.DataFrame({"a": [1, 2], "geometry_wkt": ["P1", "P2"]}).to_parquet(p, index=False)
349
+ c = _client_reading(monkeypatch, p)
350
+ tbl = c.get_local(
351
+ "y",
352
+ cache_dir=tmp_path,
353
+ format="parquet",
354
+ meta=False,
355
+ geometry=False,
356
+ as_arrow=True,
357
+ )
358
+ assert tbl.column_names == ["a"]
359
+
360
+
361
+ def test_as_arrow_keeps_geometry_by_default(tmp_path, monkeypatch):
362
+ import pandas as pd
363
+
364
+ p = tmp_path / "y.parquet"
365
+ pd.DataFrame({"a": [1], "geometry_wkt": ["P1"]}).to_parquet(p, index=False)
366
+ c = _client_reading(monkeypatch, p)
367
+ tbl = c.get_local(
368
+ "y", cache_dir=tmp_path, format="parquet", meta=False, as_arrow=True
369
+ )
370
+ assert "geometry_wkt" in tbl.column_names
371
+
372
+
373
+ def test_geoparquet_wkb_geometry_column_is_excluded(tmp_path, monkeypatch):
374
+ """GeoParquet's geometry column is named `geometry`, not `geometry_wkt`."""
375
+ gpd = pytest.importorskip("geopandas")
376
+ import shapely.geometry as sg
377
+
378
+ p = tmp_path / "z.geo.parquet"
379
+ gpd.GeoDataFrame(
380
+ {"a": [1, 2]}, geometry=[sg.Point(1, 1), sg.Point(2, 2)], crs="EPSG:4326"
381
+ ).to_parquet(p, index=False)
382
+ c = _client_reading(monkeypatch, p)
383
+ out = c.get_local(
384
+ "z", cache_dir=tmp_path, format="geoparquet", meta=False, geometry=False
385
+ )
386
+ assert list(out.columns) == ["a"]
387
+ assert type(out).__name__ != "GeoDataFrame"
@@ -0,0 +1,68 @@
1
+ """Live MCP integration — stdio session against api.eolas.fyi with a real API key.
2
+
3
+ Skipped in the default unit CI job (``pytest -m 'not integration'``).
4
+ Enable locally or in the weekly smoke workflow::
5
+
6
+ EOLAS_API_KEY=vs_... pytest -m integration tests/test_mcp_integration.py -q
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import json
12
+ import os
13
+ import shutil
14
+ import sys
15
+
16
+ import pytest
17
+ from mcp import ClientSession, StdioServerParameters
18
+ from mcp.client.stdio import stdio_client
19
+
20
+ pytestmark = pytest.mark.integration
21
+
22
+ _SKIP = not os.environ.get("EOLAS_API_KEY")
23
+
24
+
25
+ def _server_params() -> StdioServerParameters:
26
+ exe = shutil.which("eolas-mcp")
27
+ if exe:
28
+ return StdioServerParameters(command=exe, args=[], env=os.environ.copy())
29
+ return StdioServerParameters(
30
+ command=sys.executable,
31
+ args=["-m", "eolas_data.mcp_server"],
32
+ env=os.environ.copy(),
33
+ )
34
+
35
+
36
+ async def _call_tool(name: str, arguments: dict) -> dict:
37
+ if _SKIP:
38
+ pytest.skip("EOLAS_API_KEY not set — live MCP integration skipped")
39
+
40
+ params = _server_params()
41
+ async with stdio_client(params) as (read, write):
42
+ async with ClientSession(read, write) as session:
43
+ await session.initialize()
44
+ result = await session.call_tool(name, arguments)
45
+ text = result.content[0].text
46
+ return json.loads(text)
47
+
48
+
49
+ def test_mcp_search_cpi_live():
50
+ payload = asyncio.run(_call_tool("eolas_search", {"query": "cpi", "limit": 10}))
51
+ assert "error" not in payload
52
+ assert payload["count"] >= 1
53
+ names = {row["name"] for row in payload["datasets"]}
54
+ assert "nz_cpi" in names or "rbnz_m1_prices" in names
55
+
56
+
57
+ def test_mcp_info_nz_cpi_live():
58
+ payload = asyncio.run(_call_tool("eolas_info", {"name": "nz_cpi"}))
59
+ assert "error" not in payload
60
+ assert payload["name"] == "nz_cpi"
61
+ assert payload.get("source")
62
+
63
+
64
+ def test_mcp_get_nz_cpi_slice_live():
65
+ payload = asyncio.run(_call_tool("eolas_get", {"name": "nz_cpi", "limit": 5}))
66
+ assert "error" not in payload
67
+ assert payload["row_count"] >= 1
68
+ assert len(payload["rows"]) >= 1
@@ -0,0 +1,89 @@
1
+ """MCP protocol tests — spawn eolas-mcp over stdio and exercise the wire format.
2
+
3
+ These run in the default unit CI job (no EOLAS_API_KEY required).
4
+ ``eolas_health`` hits the public /health endpoint only.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import importlib.util
11
+ import json
12
+ import shutil
13
+ import sys
14
+ from typing import Any
15
+
16
+ import pytest
17
+ from mcp import ClientSession, StdioServerParameters
18
+ from mcp.client.stdio import stdio_client
19
+
20
+
21
+ def _server_params() -> StdioServerParameters:
22
+ """Spawn the server hermetically as ``<this interpreter> -m eolas_data.mcp_server``.
23
+
24
+ Deliberately does NOT use ``shutil.which("eolas-mcp")``: the console script
25
+ resolves against PATH, which on a dev box (or a machine with a global
26
+ anaconda install) can pick up an ``eolas-mcp`` from a *different*, older
27
+ eolas-data — one that predates this module — and the subprocess then dies with
28
+ ``ModuleNotFoundError: No module named 'eolas_data.mcp_server'``, failing these
29
+ tests for a reason that has nothing to do with the code under test.
30
+
31
+ ``sys.executable -m`` always runs the interpreter these tests are running
32
+ under (the venv/tox env with the code being tested), and exercises the exact
33
+ same ``main()`` the console script calls. Entry-point wiring is covered
34
+ separately by the wheel-install CI job.
35
+ """
36
+ return StdioServerParameters(
37
+ command=sys.executable,
38
+ args=["-m", "eolas_data.mcp_server"],
39
+ )
40
+
41
+
42
+ async def _with_session(coro):
43
+ params = _server_params()
44
+ async with stdio_client(params) as (read, write):
45
+ async with ClientSession(read, write) as session:
46
+ await session.initialize()
47
+ return await coro(session)
48
+
49
+
50
+ def _tool_json(result) -> Any:
51
+ assert result.content, "tool result must include content"
52
+ block = result.content[0]
53
+ text = getattr(block, "text", None)
54
+ assert text is not None, f"expected text content block, got {type(block)}"
55
+ return json.loads(text)
56
+
57
+
58
+ def test_stdio_lists_six_tools():
59
+ async def _run(session: ClientSession):
60
+ listed = await session.list_tools()
61
+ names = {t.name for t in listed.tools}
62
+ assert names == {
63
+ "eolas_health",
64
+ "eolas_search",
65
+ "eolas_info",
66
+ "eolas_get",
67
+ "eolas_download",
68
+ "eolas_sync",
69
+ }
70
+
71
+ asyncio.run(_with_session(_run))
72
+
73
+
74
+ def test_stdio_eolas_health_over_wire():
75
+ async def _run(session: ClientSession):
76
+ result = await session.call_tool("eolas_health", {})
77
+ payload = _tool_json(result)
78
+ assert payload["ok"] is True
79
+ assert payload["status_code"] == 200
80
+ assert payload["body"]["status"] == "ok"
81
+
82
+ asyncio.run(_with_session(_run))
83
+
84
+
85
+ def test_eolas_mcp_entry_point_installed():
86
+ """Console script from pyproject [project.scripts] must be on PATH in dev/CI."""
87
+ assert shutil.which("eolas-mcp") or importlib.util.find_spec(
88
+ "eolas_data.mcp_server"
89
+ )
@@ -0,0 +1,267 @@
1
+ """Tests for the eolas MCP server tool implementations."""
2
+ from __future__ import annotations
3
+
4
+ import pathlib
5
+ from unittest.mock import MagicMock
6
+
7
+ import pandas as pd
8
+ import pytest
9
+
10
+ from eolas_data import SyncResult
11
+ from eolas_data.exceptions import NotFoundError
12
+ from eolas_data.exceptions import BulkUpgradeRequired
13
+ from eolas_data.mcp_server import (
14
+ _MCP_GET_ROW_CAP,
15
+ _MCP_SEARCH_CAP,
16
+ _set_client,
17
+ eolas_download,
18
+ eolas_get,
19
+ eolas_health,
20
+ eolas_info,
21
+ eolas_search,
22
+ eolas_sync,
23
+ mcp,
24
+ )
25
+
26
+
27
+ @pytest.fixture(autouse=True)
28
+ def _reset_client():
29
+ _set_client(None)
30
+ yield
31
+ _set_client(None)
32
+
33
+
34
+ def _mock_client(**methods):
35
+ client = MagicMock()
36
+ for name, value in methods.items():
37
+ setattr(client, name, value)
38
+ _set_client(client)
39
+ return client
40
+
41
+
42
+ def test_mcp_registers_expected_tools():
43
+ """Smoke: FastMCP exposes all six eolas tools to MCP hosts."""
44
+ import asyncio
45
+
46
+ async def _tool_names():
47
+ tools = await mcp.list_tools()
48
+ return {t.name for t in tools}
49
+
50
+ names = asyncio.run(_tool_names())
51
+ assert names == {
52
+ "eolas_health",
53
+ "eolas_search",
54
+ "eolas_info",
55
+ "eolas_get",
56
+ "eolas_download",
57
+ "eolas_sync",
58
+ }
59
+
60
+
61
+ def test_eolas_health_ok(monkeypatch):
62
+ class Resp:
63
+ status_code = 200
64
+
65
+ def raise_for_status(self):
66
+ return None
67
+
68
+ def json(self):
69
+ return {"status": "ok"}
70
+
71
+ import requests
72
+
73
+ monkeypatch.setattr(requests, "get", lambda *a, **k: Resp())
74
+ out = eolas_health()
75
+ assert out["ok"] is True
76
+ assert out["body"]["status"] == "ok"
77
+
78
+
79
+ def test_eolas_health_failure(monkeypatch):
80
+ import requests
81
+
82
+ def _boom(*a, **k):
83
+ raise requests.ConnectionError("timeout")
84
+
85
+ monkeypatch.setattr(requests, "get", _boom)
86
+ out = eolas_health()
87
+ assert out["ok"] is False
88
+ assert "error" in out
89
+
90
+
91
+ def test_eolas_search_returns_compact_rows():
92
+ df = pd.DataFrame([
93
+ {"name": "nz_cpi", "title": "NZ CPI", "source": "OECD", "namespace": "oecd"},
94
+ {"name": "rbnz_m1_prices", "title": "RBNZ M1", "source": "RBNZ", "namespace": "rbnz"},
95
+ ])
96
+ _mock_client(search=lambda q, source=None: df)
97
+
98
+ out = eolas_search("cpi", limit=10)
99
+ assert out["count"] == 2
100
+ assert len(out["datasets"]) == 2
101
+ assert out["datasets"][0]["name"] == "nz_cpi"
102
+ assert "description" not in out["datasets"][0]
103
+
104
+
105
+ def test_eolas_search_client_error():
106
+ _mock_client(search=lambda q, source=None: (_ for _ in ()).throw(NotFoundError("x")))
107
+
108
+ out = eolas_search("missing")
109
+ assert out["datasets"] == []
110
+ assert "error" in out
111
+
112
+
113
+ def test_eolas_search_caps_limit():
114
+ rows = [{"name": f"d{i}", "title": f"T{i}", "source": "X"} for i in range(100)]
115
+ _mock_client(search=lambda q, source=None: pd.DataFrame(rows))
116
+
117
+ out = eolas_search("x", limit=999)
118
+ assert len(out["datasets"]) == _MCP_SEARCH_CAP
119
+ assert out["truncated"] is True
120
+
121
+
122
+ def test_eolas_info_success():
123
+ meta = {
124
+ "name": "nz_parcels",
125
+ "title": "NZ Parcels",
126
+ "source": "LINZ",
127
+ "cdc_serving_tier": "snapshot",
128
+ "bulk_export_class": "cc-by",
129
+ "row_count_at_last_refresh": 5_499_508,
130
+ }
131
+ _mock_client(info=lambda name: meta)
132
+
133
+ out = eolas_info("nz_parcels")
134
+ assert out["name"] == "nz_parcels"
135
+ assert out["cdc_serving_tier"] == "snapshot"
136
+ assert out["row_count_at_last_refresh"] == 5_499_508
137
+
138
+
139
+ def test_eolas_info_not_found():
140
+ _mock_client(info=lambda name: (_ for _ in ()).throw(NotFoundError("missing")))
141
+
142
+ out = eolas_info("no_such")
143
+ assert "error" in out
144
+ assert out["name"] == "no_such"
145
+
146
+
147
+ def test_eolas_get_caps_rows():
148
+ df = pd.DataFrame({"date": pd.date_range("2020-01-01", periods=600), "value": range(600)})
149
+ _mock_client(get=lambda name, start=None, end=None, limit=None: df.head(limit))
150
+
151
+ out = eolas_get("nz_cpi", limit=999)
152
+ assert out["limit_applied"] == _MCP_GET_ROW_CAP
153
+ assert len(out["rows"]) == _MCP_GET_ROW_CAP
154
+ assert out["truncated"] is True
155
+
156
+
157
+ def test_eolas_get_client_error():
158
+ _mock_client(get=lambda *a, **k: (_ for _ in ()).throw(NotFoundError("nope")))
159
+
160
+ out = eolas_get("nz_cpi")
161
+ assert out["rows"] == []
162
+ assert "error" in out
163
+
164
+
165
+ def test_eolas_download_writes_path(tmp_path):
166
+ dest = tmp_path / "nz_cpi.parquet"
167
+ dest.write_bytes(b"PAR1testdata")
168
+
169
+ _mock_client(
170
+ download_bulk=lambda name, path, format, freshness, progress: pathlib.Path(path),
171
+ )
172
+
173
+ out = eolas_download("nz_cpi", path=str(dest), format="parquet")
174
+ assert out["path"] == str(dest.resolve())
175
+ assert out["bytes"] == len(b"PAR1testdata")
176
+ assert out["format"] == "parquet"
177
+
178
+
179
+ def test_eolas_download_rejects_unknown_format():
180
+ out = eolas_download("nz_cpi", path="/tmp/x.parquet", format="xlsx")
181
+ assert "error" in out
182
+ assert "parquet" in out["error"]
183
+
184
+
185
+ def test_eolas_download_maps_csv_alias(tmp_path):
186
+ dest = tmp_path / "nz_cpi.csv.gz"
187
+ dest.write_bytes(b"gzdata")
188
+
189
+ captured = {}
190
+
191
+ def _dl(name, path, format, freshness, progress):
192
+ captured["format"] = format
193
+ return pathlib.Path(path)
194
+
195
+ _mock_client(download_bulk=_dl)
196
+
197
+ out = eolas_download("nz_cpi", path=str(dest), format="csv")
198
+ assert captured["format"] == "csv_gz"
199
+ assert out["format"] == "csv_gz"
200
+
201
+
202
+ def test_eolas_download_surfaces_client_errors(tmp_path):
203
+ _mock_client(
204
+ download_bulk=lambda *a, **k: (_ for _ in ()).throw(
205
+ BulkUpgradeRequired("Pro required")
206
+ ),
207
+ )
208
+
209
+ out = eolas_download("nz_cpi", path=str(tmp_path / "x.parquet"))
210
+ assert "error" in out
211
+ assert "Pro" in out["error"]
212
+
213
+
214
+ def test_eolas_sync_snapshot_mode(tmp_path):
215
+ dest = tmp_path / "nz_cpi.parquet"
216
+ result = SyncResult(
217
+ status="unchanged",
218
+ previous_snapshot_id="snap1",
219
+ current_snapshot_id="snap1",
220
+ path=dest,
221
+ bytes_downloaded=0,
222
+ sync_mode="snapshot",
223
+ )
224
+ _mock_client(
225
+ info=lambda name: {"cdc_serving_tier": "snapshot"},
226
+ sync=lambda name, path, format, freshness, progress: result,
227
+ )
228
+
229
+ out = eolas_sync("nz_cpi", path=str(dest))
230
+ assert out["status"] == "unchanged"
231
+ assert out["sync_mode"] == "snapshot"
232
+ assert out["bytes_downloaded"] == 0
233
+
234
+
235
+ def test_eolas_sync_changelog_requires_parquet(tmp_path):
236
+ dest = tmp_path / "buildings.parquet"
237
+ _mock_client(
238
+ info=lambda name: {"cdc_serving_tier": "changelog"},
239
+ )
240
+
241
+ out = eolas_sync("nz_building_outlines", path=str(dest), format="csv")
242
+ assert "error" in out
243
+ assert "parquet" in out["error"].lower()
244
+
245
+
246
+ def test_eolas_sync_changelog_mode(tmp_path):
247
+ dest = tmp_path / "buildings.parquet"
248
+ result = SyncResult(
249
+ status="updated",
250
+ previous_snapshot_id="snap1",
251
+ current_snapshot_id="snap1",
252
+ path=dest,
253
+ bytes_downloaded=0,
254
+ sync_mode="changelog",
255
+ previous_seq=100,
256
+ current_seq=142,
257
+ ops_applied=42,
258
+ )
259
+ _mock_client(
260
+ info=lambda name: {"cdc_serving_tier": "changelog"},
261
+ sync=lambda name, path, format, freshness, progress: result,
262
+ )
263
+
264
+ out = eolas_sync("nz_building_outlines", path=str(dest))
265
+ assert out["sync_mode"] == "changelog"
266
+ assert out["ops_applied"] == 42
267
+ assert out["current_seq"] == 142
File without changes
File without changes
File without changes