imageserver-export 0.2.0__tar.gz → 0.3.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.
- {imageserver_export-0.2.0 → imageserver_export-0.3.0}/PKG-INFO +31 -33
- {imageserver_export-0.2.0 → imageserver_export-0.3.0}/README.md +30 -30
- {imageserver_export-0.2.0 → imageserver_export-0.3.0}/pyproject.toml +2 -9
- {imageserver_export-0.2.0 → imageserver_export-0.3.0}/pyproject.toml.orig +2 -12
- {imageserver_export-0.2.0 → imageserver_export-0.3.0}/src/imageserver_export/__init__.py +27 -2
- imageserver_export-0.3.0/src/imageserver_export/explore.py +409 -0
- imageserver_export-0.2.0/src/imageserver_export/mcp_server.py +0 -457
- {imageserver_export-0.2.0 → imageserver_export-0.3.0}/LICENSE +0 -0
- {imageserver_export-0.2.0 → imageserver_export-0.3.0}/src/imageserver_export/aggregate.py +0 -0
- {imageserver_export-0.2.0 → imageserver_export-0.3.0}/src/imageserver_export/client.py +0 -0
- {imageserver_export-0.2.0 → imageserver_export-0.3.0}/src/imageserver_export/errors.py +0 -0
- {imageserver_export-0.2.0 → imageserver_export-0.3.0}/src/imageserver_export/grid.py +0 -0
- {imageserver_export-0.2.0 → imageserver_export-0.3.0}/src/imageserver_export/mosaic.py +0 -0
- {imageserver_export-0.2.0 → imageserver_export-0.3.0}/src/imageserver_export/py.typed +0 -0
- {imageserver_export-0.2.0 → imageserver_export-0.3.0}/src/imageserver_export/request.py +0 -0
- {imageserver_export-0.2.0 → imageserver_export-0.3.0}/src/imageserver_export/service.py +0 -0
- {imageserver_export-0.2.0 → imageserver_export-0.3.0}/src/imageserver_export/tiles.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: imageserver-export
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Export ArcGIS ImageServer rasters (like the open Copernicus Land layers the EEA serves) to aligned, atomic GeoTIFF mosaics
|
|
5
5
|
Keywords: arcgis,imageserver,geotiff,raster,copernicus,eea,land monitoring,imperviousness,gis
|
|
6
6
|
Author: Giuseppe Zileni
|
|
@@ -19,12 +19,10 @@ Classifier: Typing :: Typed
|
|
|
19
19
|
Requires-Dist: httpx>=0.27
|
|
20
20
|
Requires-Dist: numpy>=1.26
|
|
21
21
|
Requires-Dist: rasterio>=1.3
|
|
22
|
-
Requires-Dist: mcp>=2.0 ; extra == 'mcp'
|
|
23
22
|
Requires-Python: >=3.12
|
|
24
23
|
Project-URL: Homepage, https://github.com/agent-engineering-studio/imageserver-export
|
|
25
24
|
Project-URL: Issues, https://github.com/agent-engineering-studio/imageserver-export/issues
|
|
26
25
|
Project-URL: Changelog, https://github.com/agent-engineering-studio/imageserver-export/blob/main/CHANGELOG.md
|
|
27
|
-
Provides-Extra: mcp
|
|
28
26
|
Description-Content-Type: text/markdown
|
|
29
27
|
|
|
30
28
|
<p align="center">
|
|
@@ -72,7 +70,7 @@ Three dependencies: `httpx`, `numpy`, `rasterio`.
|
|
|
72
70
|
- [How it works](#how-it-works)
|
|
73
71
|
- [Why nearest neighbour](#why-nearest-neighbour)
|
|
74
72
|
- [Recipes](#recipes)
|
|
75
|
-
- [
|
|
73
|
+
- [Answers about a layer, for assistants](#answers-about-a-layer-for-assistants)
|
|
76
74
|
- [The traps we already fell into](#the-traps-we-already-fell-into)
|
|
77
75
|
- [API at a glance](#api-at-a-glance)
|
|
78
76
|
- [Data licence and credits](#data-licence-and-credits)
|
|
@@ -340,42 +338,41 @@ async def send(method: str, url: str, **kw) -> httpx.Response:
|
|
|
340
338
|
server = ImageServer(url, send=send) # every request goes through `send`
|
|
341
339
|
```
|
|
342
340
|
|
|
343
|
-
##
|
|
341
|
+
## Answers about a layer, for assistants
|
|
344
342
|
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
claude mcp add imageserver -- imageserver-mcp # Claude Code
|
|
348
|
-
```
|
|
343
|
+
`Explorer` asks the questions an assistant, a notebook or a tool server asks
|
|
344
|
+
of a layer, and each answer is one call returning plain, JSON-ready data:
|
|
349
345
|
|
|
350
|
-
|
|
346
|
+
```python
|
|
347
|
+
from pathlib import Path
|
|
348
|
+
from imageserver_export import ANSWER_RULES, Explorer
|
|
351
349
|
|
|
352
|
-
|
|
353
|
-
|
|
350
|
+
async with Explorer(output=Path("exports")) as explore:
|
|
351
|
+
await explore.describe_layer("HRL_ImperviousnessDensity_2018")
|
|
352
|
+
await explore.sample_point("HRL_ImperviousnessDensity_2018", lon=9.19, lat=45.46)
|
|
353
|
+
await explore.area_summary(
|
|
354
|
+
"HRL_ImperviousnessDensity_2018", [9.0, 45.4, 9.2, 45.5], valid_range=[0, 100]
|
|
355
|
+
)
|
|
354
356
|
```
|
|
355
357
|
|
|
356
|
-
|
|
357
|
-
value at the Duomo?"*. The agent gets six tools:
|
|
358
|
-
|
|
359
|
-
| Tool | What it answers |
|
|
358
|
+
| Method | What it answers |
|
|
360
359
|
|---|---|
|
|
361
|
-
| `list_layers` | the layers of a folder (by default the EEA's 26 Copernicus Land layers) |
|
|
362
|
-
| `describe_layer` | pixel type, native resolution, CRS, extent, and what each value means |
|
|
363
|
-
| `attribute_table` | the raster attribute table, up to `limit` rows |
|
|
364
|
-
| `sample_point` | the value at a longitude/latitude, with its label |
|
|
365
|
-
| `area_summary` | mean, min, max, valid share and class counts (with labels) of a box |
|
|
366
|
-
| `export_area` | writes a box as a GeoTIFF into the output folder (the only
|
|
360
|
+
| `list_layers()` | the layers of a folder (by default the EEA's 26 Copernicus Land layers) |
|
|
361
|
+
| `describe_layer(service)` | pixel type, native resolution, CRS, extent, and what each value means |
|
|
362
|
+
| `attribute_table(service, limit=200)` | the raster attribute table, up to `limit` rows |
|
|
363
|
+
| `sample_point(service, lon, lat, res=None)` | the value at a longitude/latitude, with its label |
|
|
364
|
+
| `area_summary(service, bbox, res=100, valid_range=None, nodata=255)` | mean, min, max, valid share and class counts (with labels) of a box |
|
|
365
|
+
| `export_area(service, bbox, res, name, ...)` | writes a box as a GeoTIFF into the output folder (the only method that writes) |
|
|
367
366
|
|
|
368
367
|
A `service` is an EEA layer name or the URL of any ImageServer. **Every
|
|
369
|
-
number comes from the library, not from the model**: the
|
|
370
|
-
data and explains it, the same rule as in Limen.
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
an environment variable (`IMAGESERVER_MCP_TRANSPORT`, `_HOST`, `_PORT`,
|
|
378
|
-
`_ALLOWED_HOSTS`, `_OUTPUT`).
|
|
368
|
+
number comes from the library, not from the model**: the assistant finds the
|
|
369
|
+
data and explains it, the same rule as in Limen. `ANSWER_RULES` is that rule,
|
|
370
|
+
written for whoever words the answers: pass it as the system prompt or the
|
|
371
|
+
server instructions. Areas are capped (4 million pixels for a summary,
|
|
372
|
+
25 million for an export) and a refusal says which resolution would fit, so a
|
|
373
|
+
single call cannot ask a server for a continent at 10 m. Bad arguments raise
|
|
374
|
+
`ValueError`; the pieces (`summarize`, `read_area`, `value_labels`,
|
|
375
|
+
`check_bbox`, ...) are public too.
|
|
379
376
|
|
|
380
377
|
Tried live: the Duomo of Milan is `100% imperviousness value`; the box of
|
|
381
378
|
Milan and its belt at 100 m is 27.9 % sealed on average, 59 % of it not
|
|
@@ -411,6 +408,7 @@ sealed at all.
|
|
|
411
408
|
| `Mosaic(path, grid, ...)` | the atomic GeoTIFF writer |
|
|
412
409
|
| `aggregate(path, factor, valid_range=None)` | `Aggregate(grid, mean, valid_fraction)`: coarse cells |
|
|
413
410
|
| `eea(name)`, `EEA_URL`, `EEA_FOLDER` | the European Environment Agency's server |
|
|
411
|
+
| `Explorer(client=None, *, output=None)` | plain-data answers about a layer; `ANSWER_RULES` |
|
|
414
412
|
|
|
415
413
|
Full reference: [agentengineering.it/imageserver-export](https://agentengineering.it/imageserver-export/).
|
|
416
414
|
|
|
@@ -428,7 +426,7 @@ from them.
|
|
|
428
426
|
uv sync
|
|
429
427
|
make check # ruff, mypy --strict, pytest (100 % coverage)
|
|
430
428
|
uv run --group docs python docs/make_images.py # redraw the README images from live data
|
|
431
|
-
uv run --group docs
|
|
429
|
+
uv run --group docs zensical serve # the documentation site, locally
|
|
432
430
|
```
|
|
433
431
|
|
|
434
432
|
Ideas: a command-line `imageserver-export` entry point; a `bbox` given in
|
|
@@ -43,7 +43,7 @@ Three dependencies: `httpx`, `numpy`, `rasterio`.
|
|
|
43
43
|
- [How it works](#how-it-works)
|
|
44
44
|
- [Why nearest neighbour](#why-nearest-neighbour)
|
|
45
45
|
- [Recipes](#recipes)
|
|
46
|
-
- [
|
|
46
|
+
- [Answers about a layer, for assistants](#answers-about-a-layer-for-assistants)
|
|
47
47
|
- [The traps we already fell into](#the-traps-we-already-fell-into)
|
|
48
48
|
- [API at a glance](#api-at-a-glance)
|
|
49
49
|
- [Data licence and credits](#data-licence-and-credits)
|
|
@@ -311,42 +311,41 @@ async def send(method: str, url: str, **kw) -> httpx.Response:
|
|
|
311
311
|
server = ImageServer(url, send=send) # every request goes through `send`
|
|
312
312
|
```
|
|
313
313
|
|
|
314
|
-
##
|
|
314
|
+
## Answers about a layer, for assistants
|
|
315
315
|
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
claude mcp add imageserver -- imageserver-mcp # Claude Code
|
|
319
|
-
```
|
|
316
|
+
`Explorer` asks the questions an assistant, a notebook or a tool server asks
|
|
317
|
+
of a layer, and each answer is one call returning plain, JSON-ready data:
|
|
320
318
|
|
|
321
|
-
|
|
319
|
+
```python
|
|
320
|
+
from pathlib import Path
|
|
321
|
+
from imageserver_export import ANSWER_RULES, Explorer
|
|
322
322
|
|
|
323
|
-
|
|
324
|
-
|
|
323
|
+
async with Explorer(output=Path("exports")) as explore:
|
|
324
|
+
await explore.describe_layer("HRL_ImperviousnessDensity_2018")
|
|
325
|
+
await explore.sample_point("HRL_ImperviousnessDensity_2018", lon=9.19, lat=45.46)
|
|
326
|
+
await explore.area_summary(
|
|
327
|
+
"HRL_ImperviousnessDensity_2018", [9.0, 45.4, 9.2, 45.5], valid_range=[0, 100]
|
|
328
|
+
)
|
|
325
329
|
```
|
|
326
330
|
|
|
327
|
-
|
|
328
|
-
value at the Duomo?"*. The agent gets six tools:
|
|
329
|
-
|
|
330
|
-
| Tool | What it answers |
|
|
331
|
+
| Method | What it answers |
|
|
331
332
|
|---|---|
|
|
332
|
-
| `list_layers` | the layers of a folder (by default the EEA's 26 Copernicus Land layers) |
|
|
333
|
-
| `describe_layer` | pixel type, native resolution, CRS, extent, and what each value means |
|
|
334
|
-
| `attribute_table` | the raster attribute table, up to `limit` rows |
|
|
335
|
-
| `sample_point` | the value at a longitude/latitude, with its label |
|
|
336
|
-
| `area_summary` | mean, min, max, valid share and class counts (with labels) of a box |
|
|
337
|
-
| `export_area` | writes a box as a GeoTIFF into the output folder (the only
|
|
333
|
+
| `list_layers()` | the layers of a folder (by default the EEA's 26 Copernicus Land layers) |
|
|
334
|
+
| `describe_layer(service)` | pixel type, native resolution, CRS, extent, and what each value means |
|
|
335
|
+
| `attribute_table(service, limit=200)` | the raster attribute table, up to `limit` rows |
|
|
336
|
+
| `sample_point(service, lon, lat, res=None)` | the value at a longitude/latitude, with its label |
|
|
337
|
+
| `area_summary(service, bbox, res=100, valid_range=None, nodata=255)` | mean, min, max, valid share and class counts (with labels) of a box |
|
|
338
|
+
| `export_area(service, bbox, res, name, ...)` | writes a box as a GeoTIFF into the output folder (the only method that writes) |
|
|
338
339
|
|
|
339
340
|
A `service` is an EEA layer name or the URL of any ImageServer. **Every
|
|
340
|
-
number comes from the library, not from the model**: the
|
|
341
|
-
data and explains it, the same rule as in Limen.
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
an environment variable (`IMAGESERVER_MCP_TRANSPORT`, `_HOST`, `_PORT`,
|
|
349
|
-
`_ALLOWED_HOSTS`, `_OUTPUT`).
|
|
341
|
+
number comes from the library, not from the model**: the assistant finds the
|
|
342
|
+
data and explains it, the same rule as in Limen. `ANSWER_RULES` is that rule,
|
|
343
|
+
written for whoever words the answers: pass it as the system prompt or the
|
|
344
|
+
server instructions. Areas are capped (4 million pixels for a summary,
|
|
345
|
+
25 million for an export) and a refusal says which resolution would fit, so a
|
|
346
|
+
single call cannot ask a server for a continent at 10 m. Bad arguments raise
|
|
347
|
+
`ValueError`; the pieces (`summarize`, `read_area`, `value_labels`,
|
|
348
|
+
`check_bbox`, ...) are public too.
|
|
350
349
|
|
|
351
350
|
Tried live: the Duomo of Milan is `100% imperviousness value`; the box of
|
|
352
351
|
Milan and its belt at 100 m is 27.9 % sealed on average, 59 % of it not
|
|
@@ -382,6 +381,7 @@ sealed at all.
|
|
|
382
381
|
| `Mosaic(path, grid, ...)` | the atomic GeoTIFF writer |
|
|
383
382
|
| `aggregate(path, factor, valid_range=None)` | `Aggregate(grid, mean, valid_fraction)`: coarse cells |
|
|
384
383
|
| `eea(name)`, `EEA_URL`, `EEA_FOLDER` | the European Environment Agency's server |
|
|
384
|
+
| `Explorer(client=None, *, output=None)` | plain-data answers about a layer; `ANSWER_RULES` |
|
|
385
385
|
|
|
386
386
|
Full reference: [agentengineering.it/imageserver-export](https://agentengineering.it/imageserver-export/).
|
|
387
387
|
|
|
@@ -399,7 +399,7 @@ from them.
|
|
|
399
399
|
uv sync
|
|
400
400
|
make check # ruff, mypy --strict, pytest (100 % coverage)
|
|
401
401
|
uv run --group docs python docs/make_images.py # redraw the README images from live data
|
|
402
|
-
uv run --group docs
|
|
402
|
+
uv run --group docs zensical serve # the documentation site, locally
|
|
403
403
|
```
|
|
404
404
|
|
|
405
405
|
Ideas: a command-line `imageserver-export` entry point; a `bbox` given in
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "imageserver-export"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.3.0"
|
|
4
4
|
description = "Export ArcGIS ImageServer rasters (like the open Copernicus Land layers the EEA serves) to aligned, atomic GeoTIFF mosaics"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
keywords = [
|
|
@@ -38,12 +38,6 @@ dependencies = [
|
|
|
38
38
|
name = "Giuseppe Zileni"
|
|
39
39
|
email = "giuseppe.zileni@gmail.com"
|
|
40
40
|
|
|
41
|
-
[project.optional-dependencies]
|
|
42
|
-
mcp = ["mcp>=2.0"]
|
|
43
|
-
|
|
44
|
-
[project.scripts]
|
|
45
|
-
imageserver-mcp = "imageserver_export.mcp_server:main"
|
|
46
|
-
|
|
47
41
|
[project.urls]
|
|
48
42
|
Homepage = "https://github.com/agent-engineering-studio/imageserver-export"
|
|
49
43
|
Issues = "https://github.com/agent-engineering-studio/imageserver-export/issues"
|
|
@@ -55,7 +49,6 @@ build-backend = "uv_build"
|
|
|
55
49
|
|
|
56
50
|
[dependency-groups]
|
|
57
51
|
dev = [
|
|
58
|
-
"imageserver-export[mcp]",
|
|
59
52
|
"mypy>=1.13",
|
|
60
53
|
"pytest>=8.3",
|
|
61
54
|
"pytest-asyncio>=0.24",
|
|
@@ -63,7 +56,7 @@ dev = [
|
|
|
63
56
|
"ruff>=0.8",
|
|
64
57
|
]
|
|
65
58
|
docs = [
|
|
66
|
-
"
|
|
59
|
+
"zensical>=0.1.0",
|
|
67
60
|
"mkdocstrings[python]>=0.26",
|
|
68
61
|
"matplotlib>=3.8",
|
|
69
62
|
]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "imageserver-export"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.3.0"
|
|
4
4
|
description = "Export ArcGIS ImageServer rasters (like the open Copernicus Land layers the EEA serves) to aligned, atomic GeoTIFF mosaics"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
keywords = ["arcgis", "imageserver", "geotiff", "raster", "copernicus", "eea", "land monitoring", "imperviousness", "gis"]
|
|
@@ -27,15 +27,6 @@ dependencies = [
|
|
|
27
27
|
"rasterio>=1.3",
|
|
28
28
|
]
|
|
29
29
|
|
|
30
|
-
[project.optional-dependencies]
|
|
31
|
-
# The imageserver-mcp server for AI agents: imageserver_export.mcp_server.
|
|
32
|
-
mcp = [
|
|
33
|
-
"mcp>=2.0",
|
|
34
|
-
]
|
|
35
|
-
|
|
36
|
-
[project.scripts]
|
|
37
|
-
imageserver-mcp = "imageserver_export.mcp_server:main"
|
|
38
|
-
|
|
39
30
|
[project.urls]
|
|
40
31
|
Homepage = "https://github.com/agent-engineering-studio/imageserver-export"
|
|
41
32
|
Issues = "https://github.com/agent-engineering-studio/imageserver-export/issues"
|
|
@@ -47,7 +38,6 @@ build-backend = "uv_build"
|
|
|
47
38
|
|
|
48
39
|
[dependency-groups]
|
|
49
40
|
dev = [
|
|
50
|
-
"imageserver-export[mcp]",
|
|
51
41
|
"mypy>=1.13",
|
|
52
42
|
"pytest>=8.3",
|
|
53
43
|
"pytest-asyncio>=0.24",
|
|
@@ -56,7 +46,7 @@ dev = [
|
|
|
56
46
|
]
|
|
57
47
|
|
|
58
48
|
docs = [
|
|
59
|
-
"
|
|
49
|
+
"zensical>=0.1.0",
|
|
60
50
|
"mkdocstrings[python]>=0.26",
|
|
61
51
|
"matplotlib>=3.8",
|
|
62
52
|
]
|
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
Pure pieces (:mod:`~imageserver_export.service`, :mod:`~imageserver_export.grid`,
|
|
4
4
|
:mod:`~imageserver_export.tiles`, :mod:`~imageserver_export.request`), the
|
|
5
5
|
mosaic writer (:mod:`~imageserver_export.mosaic`), an async client over
|
|
6
|
-
them (:class:`ImageServer`),
|
|
7
|
-
(:func:`aggregate`)
|
|
6
|
+
them (:class:`ImageServer`), coarse cells from a fine raster
|
|
7
|
+
(:func:`aggregate`), and plain-data answers about a layer (:class:`Explorer`,
|
|
8
|
+
with :data:`ANSWER_RULES` for whoever words them).
|
|
8
9
|
"""
|
|
9
10
|
|
|
10
11
|
from importlib.metadata import version
|
|
@@ -12,6 +13,19 @@ from importlib.metadata import version
|
|
|
12
13
|
from imageserver_export.aggregate import Aggregate, aggregate
|
|
13
14
|
from imageserver_export.client import Export, ImageServer, Send, list_services
|
|
14
15
|
from imageserver_export.errors import ImageServerError
|
|
16
|
+
from imageserver_export.explore import (
|
|
17
|
+
ANSWER_RULES,
|
|
18
|
+
Explorer,
|
|
19
|
+
check_bbox,
|
|
20
|
+
check_name,
|
|
21
|
+
check_pixels,
|
|
22
|
+
check_range,
|
|
23
|
+
label_of,
|
|
24
|
+
read_area,
|
|
25
|
+
service_url,
|
|
26
|
+
summarize,
|
|
27
|
+
value_labels,
|
|
28
|
+
)
|
|
15
29
|
from imageserver_export.grid import Bounds, Grid
|
|
16
30
|
from imageserver_export.mosaic import Mosaic, read_band, valid_mask
|
|
17
31
|
from imageserver_export.request import Interpolation, check_image, export_params
|
|
@@ -29,11 +43,13 @@ from imageserver_export.tiles import DEFAULT_TILE_PX, Tile, occupied, plan
|
|
|
29
43
|
__version__ = version("imageserver-export")
|
|
30
44
|
|
|
31
45
|
__all__ = [
|
|
46
|
+
"ANSWER_RULES",
|
|
32
47
|
"DEFAULT_TILE_PX",
|
|
33
48
|
"EEA_FOLDER",
|
|
34
49
|
"EEA_URL",
|
|
35
50
|
"Aggregate",
|
|
36
51
|
"Bounds",
|
|
52
|
+
"Explorer",
|
|
37
53
|
"Export",
|
|
38
54
|
"Grid",
|
|
39
55
|
"ImageServer",
|
|
@@ -45,15 +61,24 @@ __all__ = [
|
|
|
45
61
|
"Tile",
|
|
46
62
|
"__version__",
|
|
47
63
|
"aggregate",
|
|
64
|
+
"check_bbox",
|
|
48
65
|
"check_image",
|
|
66
|
+
"check_name",
|
|
67
|
+
"check_pixels",
|
|
68
|
+
"check_range",
|
|
49
69
|
"eea",
|
|
50
70
|
"export_params",
|
|
71
|
+
"label_of",
|
|
51
72
|
"list_services",
|
|
52
73
|
"occupied",
|
|
53
74
|
"parse_attribute_table",
|
|
54
75
|
"parse_info",
|
|
55
76
|
"parse_services",
|
|
56
77
|
"plan",
|
|
78
|
+
"read_area",
|
|
57
79
|
"read_band",
|
|
80
|
+
"service_url",
|
|
81
|
+
"summarize",
|
|
58
82
|
"valid_mask",
|
|
83
|
+
"value_labels",
|
|
59
84
|
]
|
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
"""Answers about a layer, in plain data: what it is, a value at a place, a box summed up.
|
|
2
|
+
|
|
3
|
+
:class:`Explorer` gathers the questions an assistant, a notebook or a tool
|
|
4
|
+
server asks of an ImageServer, each one call returning plain dicts and lists
|
|
5
|
+
(JSON-ready)::
|
|
6
|
+
|
|
7
|
+
async with Explorer(output=Path("exports")) as explore:
|
|
8
|
+
await explore.list_layers()
|
|
9
|
+
await explore.describe_layer("HRL_ImperviousnessDensity_2018")
|
|
10
|
+
await explore.sample_point("HRL_ImperviousnessDensity_2018", 9.19, 45.46)
|
|
11
|
+
await explore.area_summary("HRL_ImperviousnessDensity_2018", [9.0, 45.4, 9.2, 45.5],
|
|
12
|
+
valid_range=[0, 100])
|
|
13
|
+
await explore.export_area("HRL_ImperviousnessDensity_2018", [9.0, 45.4, 9.2, 45.5],
|
|
14
|
+
res=100, name="milan")
|
|
15
|
+
|
|
16
|
+
A ``service`` is either the name of one of the European Environment Agency's
|
|
17
|
+
open Copernicus Land layers (``HRL_ImperviousnessDensity_2018``) or the full
|
|
18
|
+
URL of any ImageServer. Every number (a value, a mean, a share, a class
|
|
19
|
+
count) is computed here, never left to whoever words the answer: see
|
|
20
|
+
:data:`ANSWER_RULES`. Only :meth:`Explorer.export_area` writes, and only into
|
|
21
|
+
the output folder; areas are capped in pixels, so one call can never ask a
|
|
22
|
+
server for a continent at 10 m.
|
|
23
|
+
|
|
24
|
+
Bad arguments raise :class:`ValueError`, service refusals
|
|
25
|
+
:class:`~imageserver_export.errors.ImageServerError`, and network failures
|
|
26
|
+
:class:`httpx.HTTPError`: a tool server turns these into the error it shows.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import math
|
|
32
|
+
import tempfile
|
|
33
|
+
from collections.abc import Mapping, Sequence
|
|
34
|
+
from dataclasses import asdict
|
|
35
|
+
from pathlib import Path
|
|
36
|
+
from types import TracebackType
|
|
37
|
+
from typing import Any
|
|
38
|
+
|
|
39
|
+
import httpx
|
|
40
|
+
import numpy as np
|
|
41
|
+
import numpy.typing as npt
|
|
42
|
+
|
|
43
|
+
from imageserver_export.client import ImageServer, list_services
|
|
44
|
+
from imageserver_export.grid import Bounds, Grid
|
|
45
|
+
from imageserver_export.mosaic import valid_mask
|
|
46
|
+
from imageserver_export.service import EEA_FOLDER, EEA_URL, eea
|
|
47
|
+
|
|
48
|
+
ANSWER_RULES: str = """\
|
|
49
|
+
Rasters from ArcGIS ImageServers. By default, the European Environment
|
|
50
|
+
Agency's open Copernicus Land Monitoring Service layers of Europe at 10 m:
|
|
51
|
+
sealed soil (HRL_ImperviousnessDensity_2018), tree cover
|
|
52
|
+
(HRL_TreeCoverDensity_2018), forest type (HRL_DominantLeafType2018),
|
|
53
|
+
grassland, water and wetness, small woody features. A `service` is one of
|
|
54
|
+
those names (list_layers) or the full URL of any ImageServer.
|
|
55
|
+
|
|
56
|
+
Start with describe_layer: it says the pixel type, the native resolution and
|
|
57
|
+
what each value means. Percentage layers use 0-100 and keep sentinels in the
|
|
58
|
+
same band (254 unclassifiable, 255 no data): pass valid_range [0, 100] so they
|
|
59
|
+
stay out of every mean. Boxes are [min_lon, min_lat, max_lon, max_lat].
|
|
60
|
+
sample_point gives the value at a place; area_summary the mean, the valid
|
|
61
|
+
share and the class counts of a box; export_area writes a GeoTIFF.
|
|
62
|
+
|
|
63
|
+
Report the numbers these functions return; do not compute your own. Credit
|
|
64
|
+
the EEA layers as "© European Union, Copernicus Land Monitoring Service,
|
|
65
|
+
European Environment Agency (EEA)".
|
|
66
|
+
"""
|
|
67
|
+
"""The rules for whoever words answers from these data.
|
|
68
|
+
|
|
69
|
+
Meant for whoever builds an assistant or a tool server on :class:`Explorer`:
|
|
70
|
+
pass it as the system prompt or the server instructions. The names it uses
|
|
71
|
+
(``list_layers``, ``describe_layer``, ``sample_point``, ``area_summary``,
|
|
72
|
+
``export_area``) are the methods of :class:`Explorer`.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
#: Pixel types of ``pixelType`` and the numpy dtype that holds them.
|
|
76
|
+
DTYPES: dict[str, str] = {
|
|
77
|
+
"U1": "uint8",
|
|
78
|
+
"U2": "uint8",
|
|
79
|
+
"U4": "uint8",
|
|
80
|
+
"U8": "uint8",
|
|
81
|
+
"S8": "int8",
|
|
82
|
+
"U16": "uint16",
|
|
83
|
+
"S16": "int16",
|
|
84
|
+
"U32": "uint32",
|
|
85
|
+
"S32": "int32",
|
|
86
|
+
"F32": "float32",
|
|
87
|
+
"F64": "float64",
|
|
88
|
+
}
|
|
89
|
+
#: The most pixels :meth:`Explorer.area_summary` reads, by default.
|
|
90
|
+
SUMMARY_MAX_PX = 4_000_000
|
|
91
|
+
#: The most pixels :meth:`Explorer.export_area` writes, by default.
|
|
92
|
+
EXPORT_MAX_PX = 25_000_000
|
|
93
|
+
#: The most classes :func:`summarize` lists, largest first.
|
|
94
|
+
TOP_CLASSES = 30
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def service_url(service: str) -> str:
|
|
98
|
+
"""The URL of ``service``: an EEA layer name, or already a URL.
|
|
99
|
+
|
|
100
|
+
Raises:
|
|
101
|
+
ValueError: ``service`` is blank.
|
|
102
|
+
"""
|
|
103
|
+
service = service.strip()
|
|
104
|
+
if not service:
|
|
105
|
+
raise ValueError("service is an EEA layer name or an ImageServer URL")
|
|
106
|
+
if service.startswith(("http://", "https://")):
|
|
107
|
+
return service.rstrip("/")
|
|
108
|
+
return eea(service)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def label_of(row: Mapping[str, Any]) -> str | None:
|
|
112
|
+
"""The class label of an attribute-table row (``Class_name`` or ``class_name``)."""
|
|
113
|
+
return next(
|
|
114
|
+
(str(v) for k, v in row.items() if k.lower() in ("class_name", "classname") and v), None
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def check_bbox(bbox: Sequence[float]) -> Bounds:
|
|
119
|
+
"""``bbox`` as ``(min_lon, min_lat, max_lon, max_lat)`` in degrees, checked.
|
|
120
|
+
|
|
121
|
+
Raises:
|
|
122
|
+
ValueError: not four numbers, or not a box in degrees.
|
|
123
|
+
"""
|
|
124
|
+
if len(bbox) != 4:
|
|
125
|
+
raise ValueError("bbox is [min_lon, min_lat, max_lon, max_lat]")
|
|
126
|
+
x0, y0, x1, y1 = (float(v) for v in bbox)
|
|
127
|
+
if not (-180 <= x0 < x1 <= 180 and -90 <= y0 < y1 <= 90):
|
|
128
|
+
raise ValueError(f"bbox is [min_lon, min_lat, max_lon, max_lat] in degrees: {list(bbox)}")
|
|
129
|
+
return (x0, y0, x1, y1)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def check_range(valid_range: Sequence[float] | None) -> tuple[float, float] | None:
|
|
133
|
+
"""``valid_range`` as ``(low, high)``, checked; ``None`` stays ``None``.
|
|
134
|
+
|
|
135
|
+
Raises:
|
|
136
|
+
ValueError: not two numbers with ``low <= high``.
|
|
137
|
+
"""
|
|
138
|
+
if valid_range is None:
|
|
139
|
+
return None
|
|
140
|
+
if len(valid_range) != 2 or valid_range[0] > valid_range[1]:
|
|
141
|
+
raise ValueError("valid_range is [low, high]")
|
|
142
|
+
return (float(valid_range[0]), float(valid_range[1]))
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def check_pixels(grid: Grid, max_px: int) -> Grid:
|
|
146
|
+
"""``grid`` itself if it has at most ``max_px`` pixels.
|
|
147
|
+
|
|
148
|
+
Raises:
|
|
149
|
+
ValueError: too many pixels; the message names a resolution that fits.
|
|
150
|
+
"""
|
|
151
|
+
if grid.width * grid.height > max_px:
|
|
152
|
+
coarser = grid.res * math.ceil(math.sqrt(grid.width * grid.height / max_px))
|
|
153
|
+
raise ValueError(
|
|
154
|
+
f"{grid.width}x{grid.height} pixels at {grid.res:g} m is over the limit of "
|
|
155
|
+
f"{max_px:,}: use a smaller box or res ≥ {coarser:g}"
|
|
156
|
+
)
|
|
157
|
+
return grid
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def check_name(name: str) -> str:
|
|
161
|
+
"""``name`` if it is a plain file name: no folders, not hidden, not empty.
|
|
162
|
+
|
|
163
|
+
Raises:
|
|
164
|
+
ValueError: otherwise.
|
|
165
|
+
"""
|
|
166
|
+
if not name or Path(name).name != name or name.startswith("."):
|
|
167
|
+
raise ValueError("name is a plain file name, without folders")
|
|
168
|
+
return name
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def summarize(
|
|
172
|
+
band: npt.NDArray[Any], *, valid_range: tuple[float, float] | None, nodata: float | None
|
|
173
|
+
) -> dict[str, Any]:
|
|
174
|
+
"""Valid share, mean, min, max and class counts of a band: the numbers to report.
|
|
175
|
+
|
|
176
|
+
``pixels``, ``valid_pixels`` and ``valid_fraction`` always; ``mean``,
|
|
177
|
+
``min`` and ``max`` when a pixel is valid; for integer bands ``classes``,
|
|
178
|
+
the :data:`TOP_CLASSES` most common values with their ``pixels`` and
|
|
179
|
+
``share``, largest first.
|
|
180
|
+
"""
|
|
181
|
+
mask = valid_mask(band, valid_range=valid_range, nodata=nodata)
|
|
182
|
+
values = band[mask]
|
|
183
|
+
out: dict[str, Any] = {
|
|
184
|
+
"pixels": int(band.size),
|
|
185
|
+
"valid_pixels": int(values.size),
|
|
186
|
+
"valid_fraction": round(float(values.size) / band.size, 4) if band.size else 0.0,
|
|
187
|
+
}
|
|
188
|
+
if values.size:
|
|
189
|
+
out |= {
|
|
190
|
+
"mean": round(float(values.mean()), 3),
|
|
191
|
+
"min": float(values.min()),
|
|
192
|
+
"max": float(values.max()),
|
|
193
|
+
}
|
|
194
|
+
if band.dtype.kind in "iu":
|
|
195
|
+
classes, counts = np.unique(band, return_counts=True)
|
|
196
|
+
order = np.argsort(counts)[::-1][:TOP_CLASSES]
|
|
197
|
+
out["classes"] = [
|
|
198
|
+
{
|
|
199
|
+
"value": int(classes[i]),
|
|
200
|
+
"pixels": int(counts[i]),
|
|
201
|
+
"share": round(float(counts[i]) / band.size, 4),
|
|
202
|
+
}
|
|
203
|
+
for i in order
|
|
204
|
+
]
|
|
205
|
+
return out
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
async def value_labels(server: ImageServer) -> dict[int, str]:
|
|
209
|
+
"""The label of each value of a thematic layer, from its attribute table.
|
|
210
|
+
|
|
211
|
+
Empty when the layer has no attribute table; rows with no label are left out.
|
|
212
|
+
"""
|
|
213
|
+
info = await server.info()
|
|
214
|
+
rows = await server.attribute_table() if info.has_attribute_table else []
|
|
215
|
+
return {
|
|
216
|
+
int(r["Value"]): label for r in rows if "Value" in r and (label := label_of(r)) is not None
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
async def read_area(
|
|
221
|
+
server: ImageServer,
|
|
222
|
+
grid: Grid,
|
|
223
|
+
*,
|
|
224
|
+
valid_range: tuple[float, float] | None = None,
|
|
225
|
+
nodata: float | None = None,
|
|
226
|
+
) -> npt.NDArray[Any]:
|
|
227
|
+
"""The band of ``grid`` from ``server``, in memory, through a temporary GeoTIFF."""
|
|
228
|
+
import rasterio
|
|
229
|
+
|
|
230
|
+
info = await server.info()
|
|
231
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
232
|
+
path = Path(tmp) / "area.tif"
|
|
233
|
+
await server.export(
|
|
234
|
+
grid,
|
|
235
|
+
path,
|
|
236
|
+
pixel_type=info.pixel_type,
|
|
237
|
+
dtype=DTYPES.get(info.pixel_type, "float64"),
|
|
238
|
+
nodata=nodata,
|
|
239
|
+
valid_range=valid_range,
|
|
240
|
+
)
|
|
241
|
+
with rasterio.open(path) as src:
|
|
242
|
+
band: npt.NDArray[Any] = src.read(1)
|
|
243
|
+
return band
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
class Explorer:
|
|
247
|
+
"""The questions to ask of ImageServer layers, each one call returning plain data.
|
|
248
|
+
|
|
249
|
+
``client`` defaults to one the explorer opens and closes itself
|
|
250
|
+
(:meth:`aclose`, or ``async with``). :meth:`export_area` writes into
|
|
251
|
+
``output`` (default ``./imageserver-exports``). Value labels are read once
|
|
252
|
+
per service and kept.
|
|
253
|
+
"""
|
|
254
|
+
|
|
255
|
+
def __init__(
|
|
256
|
+
self,
|
|
257
|
+
client: httpx.AsyncClient | None = None,
|
|
258
|
+
*,
|
|
259
|
+
output: Path | None = None,
|
|
260
|
+
summary_max_px: int = SUMMARY_MAX_PX,
|
|
261
|
+
export_max_px: int = EXPORT_MAX_PX,
|
|
262
|
+
) -> None:
|
|
263
|
+
self._own = client is None
|
|
264
|
+
self.client = client or httpx.AsyncClient(follow_redirects=True)
|
|
265
|
+
self.output = output or Path("imageserver-exports")
|
|
266
|
+
self.summary_max_px = summary_max_px
|
|
267
|
+
self.export_max_px = export_max_px
|
|
268
|
+
self._labels: dict[str, dict[int, str]] = {}
|
|
269
|
+
|
|
270
|
+
async def __aenter__(self) -> Explorer:
|
|
271
|
+
return self
|
|
272
|
+
|
|
273
|
+
async def __aexit__(
|
|
274
|
+
self,
|
|
275
|
+
exc_type: type[BaseException] | None,
|
|
276
|
+
exc: BaseException | None,
|
|
277
|
+
tb: TracebackType | None,
|
|
278
|
+
) -> None:
|
|
279
|
+
await self.aclose()
|
|
280
|
+
|
|
281
|
+
async def aclose(self) -> None:
|
|
282
|
+
"""Close the HTTP client, if the explorer opened it."""
|
|
283
|
+
if self._own:
|
|
284
|
+
await self.client.aclose()
|
|
285
|
+
|
|
286
|
+
def open(self, service: str) -> ImageServer:
|
|
287
|
+
"""The :class:`ImageServer` of ``service`` (an EEA layer name or a URL)."""
|
|
288
|
+
return ImageServer(service_url(service), self.client)
|
|
289
|
+
|
|
290
|
+
async def labels(self, server: ImageServer) -> dict[int, str]:
|
|
291
|
+
""":func:`value_labels` of ``server``, read once and kept."""
|
|
292
|
+
if server.url not in self._labels:
|
|
293
|
+
self._labels[server.url] = await value_labels(server)
|
|
294
|
+
return self._labels[server.url]
|
|
295
|
+
|
|
296
|
+
async def list_layers(self, folder_url: str = f"{EEA_URL}/{EEA_FOLDER}") -> list[str]:
|
|
297
|
+
"""The ImageServer layers of a folder; by default the EEA's Copernicus Land layers."""
|
|
298
|
+
names = await list_services(folder_url, self.client)
|
|
299
|
+
return [n.rsplit("/", 1)[-1] for n in names]
|
|
300
|
+
|
|
301
|
+
async def describe_layer(self, service: str) -> dict[str, Any]:
|
|
302
|
+
"""What a layer is: pixel type, native resolution, CRS, extent, URL and value labels."""
|
|
303
|
+
server = self.open(service)
|
|
304
|
+
info = await server.info()
|
|
305
|
+
found = asdict(info) | {"url": server.url}
|
|
306
|
+
found["value_labels"] = {str(k): v for k, v in (await self.labels(server)).items()}
|
|
307
|
+
return found
|
|
308
|
+
|
|
309
|
+
async def attribute_table(self, service: str, limit: int = 200) -> list[dict[str, Any]]:
|
|
310
|
+
"""The raster attribute table of a thematic layer: every row, up to ``limit`` (1-5000)."""
|
|
311
|
+
if not 1 <= limit <= 5000:
|
|
312
|
+
raise ValueError("limit must be between 1 and 5000")
|
|
313
|
+
return (await self.open(service).attribute_table())[:limit]
|
|
314
|
+
|
|
315
|
+
async def sample_point(
|
|
316
|
+
self, service: str, lon: float, lat: float, res: float | None = None
|
|
317
|
+
) -> dict[str, Any]:
|
|
318
|
+
"""The pixel value at a place, with its label: ``{value, label, res, crs}``.
|
|
319
|
+
|
|
320
|
+
``res`` is the pixel side in metres, in LAEA Europe (default: the
|
|
321
|
+
service's pixel size, 10 m for the EEA layers).
|
|
322
|
+
"""
|
|
323
|
+
if not (-180 <= lon <= 180 and -90 <= lat <= 90):
|
|
324
|
+
raise ValueError("lon and lat are in degrees")
|
|
325
|
+
server = self.open(service)
|
|
326
|
+
info = await server.info()
|
|
327
|
+
from rasterio.warp import transform
|
|
328
|
+
|
|
329
|
+
size = res or info.pixel_size[0]
|
|
330
|
+
xs, ys = transform(4326, 3035, [lon], [lat])
|
|
331
|
+
# The one pixel of a grid of ``size`` (on whole multiples) that holds the point.
|
|
332
|
+
grid = Grid(
|
|
333
|
+
crs=3035,
|
|
334
|
+
left=math.floor(xs[0] / size) * size,
|
|
335
|
+
top=(math.floor(ys[0] / size) + 1) * size,
|
|
336
|
+
res=size,
|
|
337
|
+
width=1,
|
|
338
|
+
height=1,
|
|
339
|
+
)
|
|
340
|
+
band = await read_area(server, grid)
|
|
341
|
+
value = band[0, 0].item()
|
|
342
|
+
label = (await self.labels(server)).get(int(value)) if band.dtype.kind in "iu" else None
|
|
343
|
+
return {"value": value, "label": label, "res": size, "crs": grid.crs}
|
|
344
|
+
|
|
345
|
+
async def area_summary(
|
|
346
|
+
self,
|
|
347
|
+
service: str,
|
|
348
|
+
bbox: Sequence[float],
|
|
349
|
+
res: float = 100,
|
|
350
|
+
valid_range: Sequence[float] | None = None,
|
|
351
|
+
nodata: float | None = 255,
|
|
352
|
+
) -> dict[str, Any]:
|
|
353
|
+
"""Mean, min, max, valid share and class counts of a box, at ``res`` metres.
|
|
354
|
+
|
|
355
|
+
:func:`summarize` of the box, with a ``label`` on each class and the
|
|
356
|
+
``width``, ``height``, ``res`` and ``crs`` of the grid read. Pass
|
|
357
|
+
``valid_range`` [0, 100] for percentage layers, so sentinels stay out
|
|
358
|
+
of the mean.
|
|
359
|
+
"""
|
|
360
|
+
server = self.open(service)
|
|
361
|
+
valid = check_range(valid_range)
|
|
362
|
+
grid = check_pixels(Grid.from_lonlat(check_bbox(bbox), res=res), self.summary_max_px)
|
|
363
|
+
found = summarize(
|
|
364
|
+
await read_area(server, grid, valid_range=valid, nodata=nodata),
|
|
365
|
+
valid_range=valid,
|
|
366
|
+
nodata=nodata,
|
|
367
|
+
)
|
|
368
|
+
names = await self.labels(server)
|
|
369
|
+
for row in found.get("classes", []):
|
|
370
|
+
row["label"] = names.get(row["value"])
|
|
371
|
+
return found | {"width": grid.width, "height": grid.height, "res": res, "crs": grid.crs}
|
|
372
|
+
|
|
373
|
+
async def export_area(
|
|
374
|
+
self,
|
|
375
|
+
service: str,
|
|
376
|
+
bbox: Sequence[float],
|
|
377
|
+
res: float,
|
|
378
|
+
name: str,
|
|
379
|
+
valid_range: Sequence[float] | None = None,
|
|
380
|
+
skip_empty: bool = False,
|
|
381
|
+
) -> dict[str, Any]:
|
|
382
|
+
"""Write a box of a layer as a GeoTIFF ``<name>.tif`` in the output folder.
|
|
383
|
+
|
|
384
|
+
LAEA Europe (EPSG:3035), nearest neighbour, written whole or not at
|
|
385
|
+
all. Returns ``{path, width, height, tiles, skipped, valid_fraction, crs}``.
|
|
386
|
+
"""
|
|
387
|
+
check_name(name)
|
|
388
|
+
server = self.open(service)
|
|
389
|
+
valid = check_range(valid_range)
|
|
390
|
+
grid = check_pixels(Grid.from_lonlat(check_bbox(bbox), res=res), self.export_max_px)
|
|
391
|
+
info = await server.info()
|
|
392
|
+
dest = self.output / f"{name.removesuffix('.tif')}.tif"
|
|
393
|
+
result = await server.export(
|
|
394
|
+
grid,
|
|
395
|
+
dest,
|
|
396
|
+
pixel_type=info.pixel_type,
|
|
397
|
+
dtype=DTYPES.get(info.pixel_type, "float64"),
|
|
398
|
+
valid_range=valid,
|
|
399
|
+
skip_empty=skip_empty,
|
|
400
|
+
)
|
|
401
|
+
return {
|
|
402
|
+
"path": str(result.path.resolve()),
|
|
403
|
+
"width": result.width,
|
|
404
|
+
"height": result.height,
|
|
405
|
+
"tiles": result.tiles,
|
|
406
|
+
"skipped": result.skipped,
|
|
407
|
+
"valid_fraction": round(result.valid_fraction, 4),
|
|
408
|
+
"crs": grid.crs,
|
|
409
|
+
}
|
|
@@ -1,457 +0,0 @@
|
|
|
1
|
-
"""An MCP server over ArcGIS ImageServers, for AI agents: ``pip install "imageserver-export[mcp]"``.
|
|
2
|
-
|
|
3
|
-
imageserver-mcp # stdio: Claude Desktop, IDEs
|
|
4
|
-
imageserver-mcp --transport streamable-http --host 0.0.0.0 --port 8768
|
|
5
|
-
|
|
6
|
-
Over HTTP the MCP endpoint is ``/mcp`` and ``GET /health`` answers
|
|
7
|
-
``{"status": "ok"}`` for container healthchecks. Every option also reads an
|
|
8
|
-
environment variable (``IMAGESERVER_MCP_TRANSPORT``, ``IMAGESERVER_MCP_HOST``,
|
|
9
|
-
``IMAGESERVER_MCP_PORT``, ``IMAGESERVER_MCP_ALLOWED_HOSTS``,
|
|
10
|
-
``IMAGESERVER_MCP_OUTPUT``), so a compose file needs no command line.
|
|
11
|
-
|
|
12
|
-
A ``service`` is either the name of one of the European Environment Agency's
|
|
13
|
-
open Copernicus Land layers (``HRL_ImperviousnessDensity_2018``) or the full
|
|
14
|
-
URL of any ImageServer. Every number an agent gets back (a value, a mean, a
|
|
15
|
-
share, a class count) is computed here, by the library, never left to the
|
|
16
|
-
model: the agent finds the data and explains it. Only ``export_area`` writes,
|
|
17
|
-
and only into the output folder; areas are capped in pixels, so one call can
|
|
18
|
-
never ask a server for a continent at 10 m.
|
|
19
|
-
"""
|
|
20
|
-
|
|
21
|
-
from __future__ import annotations
|
|
22
|
-
|
|
23
|
-
import argparse
|
|
24
|
-
import logging
|
|
25
|
-
import math
|
|
26
|
-
import os
|
|
27
|
-
import tempfile
|
|
28
|
-
from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence
|
|
29
|
-
from contextlib import asynccontextmanager
|
|
30
|
-
from dataclasses import asdict
|
|
31
|
-
from functools import wraps
|
|
32
|
-
from pathlib import Path
|
|
33
|
-
from typing import Any, cast
|
|
34
|
-
|
|
35
|
-
import httpx
|
|
36
|
-
|
|
37
|
-
from imageserver_export.client import ImageServer, list_services
|
|
38
|
-
from imageserver_export.errors import ImageServerError
|
|
39
|
-
from imageserver_export.grid import Bounds, Grid
|
|
40
|
-
from imageserver_export.mosaic import valid_mask
|
|
41
|
-
from imageserver_export.service import EEA_FOLDER, EEA_URL, eea
|
|
42
|
-
|
|
43
|
-
try:
|
|
44
|
-
from mcp.server.mcpserver import MCPServer
|
|
45
|
-
from mcp.server.mcpserver.exceptions import ToolError
|
|
46
|
-
from mcp.server.transport_security import TransportSecuritySettings
|
|
47
|
-
from mcp.types import ToolAnnotations
|
|
48
|
-
from starlette.requests import Request
|
|
49
|
-
from starlette.responses import JSONResponse, Response
|
|
50
|
-
except ImportError as exc: # pragma: no cover - exercised only without the extra
|
|
51
|
-
raise ImportError(
|
|
52
|
-
'imageserver_export.mcp_server needs the mcp extra: pip install "imageserver-export[mcp]"'
|
|
53
|
-
) from exc
|
|
54
|
-
|
|
55
|
-
INSTRUCTIONS = """\
|
|
56
|
-
Rasters from ArcGIS ImageServers. By default, the European Environment
|
|
57
|
-
Agency's open Copernicus Land Monitoring Service layers of Europe at 10 m:
|
|
58
|
-
sealed soil (HRL_ImperviousnessDensity_2018), tree cover
|
|
59
|
-
(HRL_TreeCoverDensity_2018), forest type (HRL_DominantLeafType2018),
|
|
60
|
-
grassland, water and wetness, small woody features. A `service` is one of
|
|
61
|
-
those names (list_layers) or the full URL of any ImageServer.
|
|
62
|
-
|
|
63
|
-
Start with describe_layer: it says the pixel type, the native resolution and
|
|
64
|
-
what each value means. Percentage layers use 0-100 and keep sentinels in the
|
|
65
|
-
same band (254 unclassifiable, 255 no data): pass valid_range [0, 100] so they
|
|
66
|
-
stay out of every mean. Boxes are [min_lon, min_lat, max_lon, max_lat].
|
|
67
|
-
sample_point gives the value at a place; area_summary the mean, the valid
|
|
68
|
-
share and the class counts of a box; export_area writes a GeoTIFF.
|
|
69
|
-
|
|
70
|
-
Report the numbers the tools return; do not compute your own. Credit the EEA
|
|
71
|
-
layers as "© European Union, Copernicus Land Monitoring Service, European
|
|
72
|
-
Environment Agency (EEA)".
|
|
73
|
-
"""
|
|
74
|
-
|
|
75
|
-
#: Pixel types of ``pixelType`` and the numpy dtype that holds them.
|
|
76
|
-
DTYPES = {
|
|
77
|
-
"U1": "uint8",
|
|
78
|
-
"U2": "uint8",
|
|
79
|
-
"U4": "uint8",
|
|
80
|
-
"U8": "uint8",
|
|
81
|
-
"S8": "int8",
|
|
82
|
-
"U16": "uint16",
|
|
83
|
-
"S16": "int16",
|
|
84
|
-
"U32": "uint32",
|
|
85
|
-
"S32": "int32",
|
|
86
|
-
"F32": "float32",
|
|
87
|
-
"F64": "float64",
|
|
88
|
-
}
|
|
89
|
-
#: The most pixels area_summary reads, and export_area writes, by default.
|
|
90
|
-
SUMMARY_MAX_PX = 4_000_000
|
|
91
|
-
EXPORT_MAX_PX = 25_000_000
|
|
92
|
-
#: The most classes area_summary lists, largest first.
|
|
93
|
-
_TOP_CLASSES = 30
|
|
94
|
-
|
|
95
|
-
_READ = ToolAnnotations(read_only_hint=True, open_world_hint=True)
|
|
96
|
-
_WRITE = ToolAnnotations(
|
|
97
|
-
read_only_hint=False, destructive_hint=False, idempotent_hint=True, open_world_hint=True
|
|
98
|
-
)
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
def service_url(service: str) -> str:
|
|
102
|
-
"""The URL of ``service``: an EEA layer name, or already a URL."""
|
|
103
|
-
service = service.strip()
|
|
104
|
-
if not service:
|
|
105
|
-
raise ValueError("service is an EEA layer name or an ImageServer URL")
|
|
106
|
-
if service.startswith(("http://", "https://")):
|
|
107
|
-
return service.rstrip("/")
|
|
108
|
-
return eea(service)
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
def label_of(row: Mapping[str, Any]) -> str | None:
|
|
112
|
-
"""The class label of an attribute-table row (``Class_name`` or ``class_name``)."""
|
|
113
|
-
return next(
|
|
114
|
-
(str(v) for k, v in row.items() if k.lower() in ("class_name", "classname") and v), None
|
|
115
|
-
)
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
def _bbox(bbox: Sequence[float]) -> Bounds:
|
|
119
|
-
if len(bbox) != 4:
|
|
120
|
-
raise ValueError("bbox is [min_lon, min_lat, max_lon, max_lat]")
|
|
121
|
-
x0, y0, x1, y1 = (float(v) for v in bbox)
|
|
122
|
-
if not (-180 <= x0 < x1 <= 180 and -90 <= y0 < y1 <= 90):
|
|
123
|
-
raise ValueError(f"bbox is [min_lon, min_lat, max_lon, max_lat] in degrees: {list(bbox)}")
|
|
124
|
-
return (x0, y0, x1, y1)
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
def _range(valid_range: Sequence[float] | None) -> tuple[float, float] | None:
|
|
128
|
-
if valid_range is None:
|
|
129
|
-
return None
|
|
130
|
-
if len(valid_range) != 2 or valid_range[0] > valid_range[1]:
|
|
131
|
-
raise ValueError("valid_range is [low, high]")
|
|
132
|
-
return (float(valid_range[0]), float(valid_range[1]))
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
def _capped(grid: Grid, max_px: int) -> Grid:
|
|
136
|
-
if grid.width * grid.height > max_px:
|
|
137
|
-
coarser = grid.res * math.ceil(math.sqrt(grid.width * grid.height / max_px))
|
|
138
|
-
raise ValueError(
|
|
139
|
-
f"{grid.width}x{grid.height} pixels at {grid.res:g} m is over the limit of "
|
|
140
|
-
f"{max_px:,}: use a smaller box or res ≥ {coarser:g}"
|
|
141
|
-
)
|
|
142
|
-
return grid
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
def summarize(
|
|
146
|
-
band: Any, *, valid_range: tuple[float, float] | None, nodata: float | None
|
|
147
|
-
) -> dict[str, Any]:
|
|
148
|
-
"""Valid share, mean, min, max and class counts of a band: the numbers an agent reports."""
|
|
149
|
-
import numpy as np
|
|
150
|
-
|
|
151
|
-
mask = valid_mask(band, valid_range=valid_range, nodata=nodata)
|
|
152
|
-
values = band[mask]
|
|
153
|
-
out: dict[str, Any] = {
|
|
154
|
-
"pixels": int(band.size),
|
|
155
|
-
"valid_pixels": int(values.size),
|
|
156
|
-
"valid_fraction": round(float(values.size) / band.size, 4) if band.size else 0.0,
|
|
157
|
-
}
|
|
158
|
-
if values.size:
|
|
159
|
-
out |= {
|
|
160
|
-
"mean": round(float(values.mean()), 3),
|
|
161
|
-
"min": float(values.min()),
|
|
162
|
-
"max": float(values.max()),
|
|
163
|
-
}
|
|
164
|
-
if band.dtype.kind in "iu":
|
|
165
|
-
classes, counts = np.unique(band, return_counts=True)
|
|
166
|
-
order = np.argsort(counts)[::-1][:_TOP_CLASSES]
|
|
167
|
-
out["classes"] = [
|
|
168
|
-
{
|
|
169
|
-
"value": int(classes[i]),
|
|
170
|
-
"pixels": int(counts[i]),
|
|
171
|
-
"share": round(float(counts[i]) / band.size, 4),
|
|
172
|
-
}
|
|
173
|
-
for i in order
|
|
174
|
-
]
|
|
175
|
-
return out
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
@asynccontextmanager
|
|
179
|
-
async def _closing(client: httpx.AsyncClient, *, own: bool) -> AsyncIterator[None]:
|
|
180
|
-
"""The server's lifespan: close the HTTP client at shutdown if it is ours."""
|
|
181
|
-
try:
|
|
182
|
-
yield
|
|
183
|
-
finally:
|
|
184
|
-
if own:
|
|
185
|
-
await client.aclose()
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
def _tool_errors[**P, T](call: Callable[P, Awaitable[T]]) -> Callable[P, Awaitable[T]]:
|
|
189
|
-
"""Service refusals, HTTP failures and bad arguments as a ToolError the agent can read."""
|
|
190
|
-
|
|
191
|
-
@wraps(call)
|
|
192
|
-
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
|
|
193
|
-
try:
|
|
194
|
-
return await call(*args, **kwargs)
|
|
195
|
-
except (ImageServerError, ValueError) as exc:
|
|
196
|
-
raise ToolError(str(exc)) from exc
|
|
197
|
-
except httpx.HTTPError as exc:
|
|
198
|
-
raise ToolError(f"the service could not be reached: {exc}") from exc
|
|
199
|
-
|
|
200
|
-
return wrapper
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
def server(
|
|
204
|
-
client: httpx.AsyncClient | None = None,
|
|
205
|
-
*,
|
|
206
|
-
output: Path | None = None,
|
|
207
|
-
summary_max_px: int = SUMMARY_MAX_PX,
|
|
208
|
-
export_max_px: int = EXPORT_MAX_PX,
|
|
209
|
-
) -> MCPServer[Any]:
|
|
210
|
-
"""The MCP server; ``client`` defaults to one it opens and closes itself.
|
|
211
|
-
|
|
212
|
-
``export_area`` writes into ``output`` (default ``$IMAGESERVER_MCP_OUTPUT``,
|
|
213
|
-
else ``./imageserver-exports``).
|
|
214
|
-
"""
|
|
215
|
-
http = client or httpx.AsyncClient(follow_redirects=True)
|
|
216
|
-
folder = output or Path(os.environ.get("IMAGESERVER_MCP_OUTPUT", "imageserver-exports"))
|
|
217
|
-
labels: dict[str, dict[int, str]] = {}
|
|
218
|
-
|
|
219
|
-
def open_service(service: str) -> ImageServer:
|
|
220
|
-
return ImageServer(service_url(service), http)
|
|
221
|
-
|
|
222
|
-
async def labels_of(server: ImageServer) -> dict[int, str]:
|
|
223
|
-
if server.url not in labels:
|
|
224
|
-
info = await server.info()
|
|
225
|
-
rows = await server.attribute_table() if info.has_attribute_table else []
|
|
226
|
-
labels[server.url] = {
|
|
227
|
-
int(r["Value"]): label
|
|
228
|
-
for r in rows
|
|
229
|
-
if "Value" in r and (label := label_of(r)) is not None
|
|
230
|
-
}
|
|
231
|
-
return labels[server.url]
|
|
232
|
-
|
|
233
|
-
async def read_area(
|
|
234
|
-
server: ImageServer,
|
|
235
|
-
grid: Grid,
|
|
236
|
-
*,
|
|
237
|
-
valid_range: tuple[float, float] | None,
|
|
238
|
-
nodata: float | None,
|
|
239
|
-
) -> Any:
|
|
240
|
-
"""The band of ``grid``, through a temporary GeoTIFF."""
|
|
241
|
-
import rasterio
|
|
242
|
-
|
|
243
|
-
info = await server.info()
|
|
244
|
-
dtype = DTYPES.get(info.pixel_type, "float64")
|
|
245
|
-
with tempfile.TemporaryDirectory() as tmp:
|
|
246
|
-
path = Path(tmp) / "area.tif"
|
|
247
|
-
await server.export(
|
|
248
|
-
grid,
|
|
249
|
-
path,
|
|
250
|
-
pixel_type=info.pixel_type,
|
|
251
|
-
dtype=dtype,
|
|
252
|
-
nodata=nodata,
|
|
253
|
-
valid_range=valid_range,
|
|
254
|
-
)
|
|
255
|
-
with rasterio.open(path) as src:
|
|
256
|
-
return src.read(1)
|
|
257
|
-
|
|
258
|
-
mcp: MCPServer[Any] = MCPServer(
|
|
259
|
-
"imageserver-export",
|
|
260
|
-
instructions=INSTRUCTIONS,
|
|
261
|
-
lifespan=lambda _server: _closing(http, own=client is None),
|
|
262
|
-
)
|
|
263
|
-
|
|
264
|
-
async def health(_request: Request) -> Response:
|
|
265
|
-
"""``GET /health`` over HTTP, for container healthchecks."""
|
|
266
|
-
return JSONResponse({"status": "ok", "server": "imageserver-export"})
|
|
267
|
-
|
|
268
|
-
# custom_route is untyped in the SDK: register the typed handler through a cast.
|
|
269
|
-
route = cast(Callable[[Any], Any], mcp.custom_route("/health", methods=["GET"]))
|
|
270
|
-
route(health)
|
|
271
|
-
|
|
272
|
-
@mcp.tool(annotations=_READ)
|
|
273
|
-
@_tool_errors
|
|
274
|
-
async def list_layers(folder_url: str = f"{EEA_URL}/{EEA_FOLDER}") -> list[str]:
|
|
275
|
-
"""The ImageServer layers of a folder; by default the EEA's Copernicus Land layers."""
|
|
276
|
-
names = await list_services(folder_url, http)
|
|
277
|
-
return [n.rsplit("/", 1)[-1] for n in names]
|
|
278
|
-
|
|
279
|
-
@mcp.tool(annotations=_READ)
|
|
280
|
-
@_tool_errors
|
|
281
|
-
async def describe_layer(service: str) -> dict[str, Any]:
|
|
282
|
-
"""What a layer is: pixel type, native resolution, CRS, extent, and its value labels."""
|
|
283
|
-
server = open_service(service)
|
|
284
|
-
info = await server.info()
|
|
285
|
-
found = asdict(info) | {"url": server.url}
|
|
286
|
-
found["value_labels"] = {str(k): v for k, v in (await labels_of(server)).items()}
|
|
287
|
-
return found
|
|
288
|
-
|
|
289
|
-
@mcp.tool(annotations=_READ)
|
|
290
|
-
@_tool_errors
|
|
291
|
-
async def attribute_table(service: str, limit: int = 200) -> list[dict[str, Any]]:
|
|
292
|
-
"""The raster attribute table of a thematic layer: every row, up to ``limit``."""
|
|
293
|
-
if not 1 <= limit <= 5000:
|
|
294
|
-
raise ValueError("limit must be between 1 and 5000")
|
|
295
|
-
return (await open_service(service).attribute_table())[:limit]
|
|
296
|
-
|
|
297
|
-
@mcp.tool(annotations=_READ)
|
|
298
|
-
@_tool_errors
|
|
299
|
-
async def sample_point(
|
|
300
|
-
service: str, lon: float, lat: float, res: float | None = None
|
|
301
|
-
) -> dict[str, Any]:
|
|
302
|
-
"""The pixel value at a place, with its label.
|
|
303
|
-
|
|
304
|
-
``res`` is the pixel side in metres, in LAEA Europe (default: the
|
|
305
|
-
service's pixel size, 10 m for the EEA layers).
|
|
306
|
-
"""
|
|
307
|
-
if not (-180 <= lon <= 180 and -90 <= lat <= 90):
|
|
308
|
-
raise ValueError("lon and lat are in degrees")
|
|
309
|
-
server = open_service(service)
|
|
310
|
-
info = await server.info()
|
|
311
|
-
from rasterio.warp import transform
|
|
312
|
-
|
|
313
|
-
size = res or info.pixel_size[0]
|
|
314
|
-
xs, ys = transform(4326, 3035, [lon], [lat])
|
|
315
|
-
# The one pixel of a grid of ``size`` (on whole multiples) that holds the point.
|
|
316
|
-
grid = Grid(
|
|
317
|
-
crs=3035,
|
|
318
|
-
left=math.floor(xs[0] / size) * size,
|
|
319
|
-
top=(math.floor(ys[0] / size) + 1) * size,
|
|
320
|
-
res=size,
|
|
321
|
-
width=1,
|
|
322
|
-
height=1,
|
|
323
|
-
)
|
|
324
|
-
band = await read_area(server, grid, valid_range=None, nodata=None)
|
|
325
|
-
value = band[0, 0].item()
|
|
326
|
-
label = (await labels_of(server)).get(int(value)) if band.dtype.kind in "iu" else None
|
|
327
|
-
return {"value": value, "label": label, "res": size, "crs": grid.crs}
|
|
328
|
-
|
|
329
|
-
@mcp.tool(annotations=_READ)
|
|
330
|
-
@_tool_errors
|
|
331
|
-
async def area_summary(
|
|
332
|
-
service: str,
|
|
333
|
-
bbox: list[float],
|
|
334
|
-
res: float = 100,
|
|
335
|
-
valid_range: list[float] | None = None,
|
|
336
|
-
nodata: float | None = 255,
|
|
337
|
-
) -> dict[str, Any]:
|
|
338
|
-
"""Mean, min, max, valid share and class counts of a box, at ``res`` metres.
|
|
339
|
-
|
|
340
|
-
Pass ``valid_range`` [0, 100] for percentage layers, so sentinels stay
|
|
341
|
-
out of the mean. Class counts come with their labels.
|
|
342
|
-
"""
|
|
343
|
-
server = open_service(service)
|
|
344
|
-
valid = _range(valid_range)
|
|
345
|
-
grid = _capped(Grid.from_lonlat(_bbox(bbox), res=res), summary_max_px)
|
|
346
|
-
found = summarize(
|
|
347
|
-
await read_area(server, grid, valid_range=valid, nodata=nodata),
|
|
348
|
-
valid_range=valid,
|
|
349
|
-
nodata=nodata,
|
|
350
|
-
)
|
|
351
|
-
names = await labels_of(server)
|
|
352
|
-
for row in found.get("classes", []):
|
|
353
|
-
row["label"] = names.get(row["value"])
|
|
354
|
-
return found | {"width": grid.width, "height": grid.height, "res": res, "crs": grid.crs}
|
|
355
|
-
|
|
356
|
-
@mcp.tool(annotations=_WRITE)
|
|
357
|
-
@_tool_errors
|
|
358
|
-
async def export_area(
|
|
359
|
-
service: str,
|
|
360
|
-
bbox: list[float],
|
|
361
|
-
res: float,
|
|
362
|
-
name: str,
|
|
363
|
-
valid_range: list[float] | None = None,
|
|
364
|
-
skip_empty: bool = False,
|
|
365
|
-
) -> dict[str, Any]:
|
|
366
|
-
"""Write a box of a layer as a GeoTIFF ``<name>.tif`` in the output folder.
|
|
367
|
-
|
|
368
|
-
LAEA Europe (EPSG:3035), nearest neighbour, written whole or not at
|
|
369
|
-
all. Returns the path, size and valid share.
|
|
370
|
-
"""
|
|
371
|
-
if not name or Path(name).name != name or name.startswith("."):
|
|
372
|
-
raise ValueError("name is a plain file name, without folders")
|
|
373
|
-
server = open_service(service)
|
|
374
|
-
valid = _range(valid_range)
|
|
375
|
-
grid = _capped(Grid.from_lonlat(_bbox(bbox), res=res), export_max_px)
|
|
376
|
-
info = await server.info()
|
|
377
|
-
dest = folder / f"{name.removesuffix('.tif')}.tif"
|
|
378
|
-
result = await server.export(
|
|
379
|
-
grid,
|
|
380
|
-
dest,
|
|
381
|
-
pixel_type=info.pixel_type,
|
|
382
|
-
dtype=DTYPES.get(info.pixel_type, "float64"),
|
|
383
|
-
valid_range=valid,
|
|
384
|
-
skip_empty=skip_empty,
|
|
385
|
-
)
|
|
386
|
-
return {
|
|
387
|
-
"path": str(result.path.resolve()),
|
|
388
|
-
"width": result.width,
|
|
389
|
-
"height": result.height,
|
|
390
|
-
"tiles": result.tiles,
|
|
391
|
-
"skipped": result.skipped,
|
|
392
|
-
"valid_fraction": round(result.valid_fraction, 4),
|
|
393
|
-
"crs": grid.crs,
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
return mcp
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
def options(
|
|
400
|
-
argv: Sequence[str] | None = None, environ: Mapping[str, str] = os.environ
|
|
401
|
-
) -> argparse.Namespace:
|
|
402
|
-
"""The command line of ``imageserver-mcp``, each default from its environment variable."""
|
|
403
|
-
top = argparse.ArgumentParser(
|
|
404
|
-
prog="imageserver-mcp", description="ArcGIS ImageServers as an MCP server."
|
|
405
|
-
)
|
|
406
|
-
top.add_argument(
|
|
407
|
-
"--transport",
|
|
408
|
-
choices=("stdio", "streamable-http"),
|
|
409
|
-
default=environ.get("IMAGESERVER_MCP_TRANSPORT", "stdio"),
|
|
410
|
-
help="stdio (default) or streamable-http, served at /mcp",
|
|
411
|
-
)
|
|
412
|
-
top.add_argument(
|
|
413
|
-
"--host",
|
|
414
|
-
default=environ.get("IMAGESERVER_MCP_HOST", "127.0.0.1"),
|
|
415
|
-
help="HTTP address (default 127.0.0.1; 0.0.0.0 in a container)",
|
|
416
|
-
)
|
|
417
|
-
top.add_argument("--port", type=int, default=int(environ.get("IMAGESERVER_MCP_PORT", "8768")))
|
|
418
|
-
top.add_argument(
|
|
419
|
-
"--allowed-host",
|
|
420
|
-
action="append",
|
|
421
|
-
default=[
|
|
422
|
-
h for h in environ.get("IMAGESERVER_MCP_ALLOWED_HOSTS", "").split(",") if h.strip()
|
|
423
|
-
],
|
|
424
|
-
metavar="HOST[:PORT]",
|
|
425
|
-
help="accept only these Host headers (DNS rebinding protection); repeatable",
|
|
426
|
-
)
|
|
427
|
-
top.add_argument(
|
|
428
|
-
"--output",
|
|
429
|
-
type=Path,
|
|
430
|
-
default=Path(environ.get("IMAGESERVER_MCP_OUTPUT", "imageserver-exports")),
|
|
431
|
-
help="the folder export_area writes into",
|
|
432
|
-
)
|
|
433
|
-
args = top.parse_args(argv)
|
|
434
|
-
if args.transport not in ("stdio", "streamable-http"):
|
|
435
|
-
top.error(f"unknown transport {args.transport!r}")
|
|
436
|
-
return args
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
def http_options(args: argparse.Namespace) -> dict[str, Any]:
|
|
440
|
-
"""The keyword arguments of ``MCPServer.run`` for the HTTP transport."""
|
|
441
|
-
found: dict[str, Any] = {"host": args.host, "port": args.port, "streamable_http_path": "/mcp"}
|
|
442
|
-
if args.allowed_host:
|
|
443
|
-
found["transport_security"] = TransportSecuritySettings(
|
|
444
|
-
enable_dns_rebinding_protection=True,
|
|
445
|
-
allowed_hosts=[h.strip() for h in args.allowed_host],
|
|
446
|
-
)
|
|
447
|
-
return found
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
def main(argv: Sequence[str] | None = None) -> None: # pragma: no cover - runs a server
|
|
451
|
-
"""Entry point of ``imageserver-mcp``."""
|
|
452
|
-
logging.getLogger("httpx").setLevel(logging.WARNING) # not one line per request
|
|
453
|
-
args = options(argv)
|
|
454
|
-
if args.transport == "stdio":
|
|
455
|
-
server(output=args.output).run("stdio")
|
|
456
|
-
else:
|
|
457
|
-
server(output=args.output).run("streamable-http", **http_options(args))
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|