pitstop-cli 1.2.0__tar.gz → 1.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.
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/.github/workflows/ci.yml +1 -1
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/.github/workflows/upstream-smoke.yml +5 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/PKG-INFO +5 -5
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/README.md +2 -2
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/pyproject.toml +6 -5
- pitstop_cli-1.3.0/scripts/geo-acceptance.sh +136 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/scripts/smoke-installed.py +28 -5
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/skills/pitstop/SKILL.md +6 -4
- pitstop_cli-1.3.0/src/pitstop/cache.py +63 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/src/pitstop/core.py +2 -3
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/src/pitstop/geocoding.py +2 -3
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/src/pitstop/mcp_server.py +12 -5
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/src/pitstop/overpass.py +2 -3
- pitstop_cli-1.3.0/src/pitstop/version.py +1 -0
- pitstop_cli-1.3.0/tests/test_retry.py +61 -0
- pitstop_cli-1.2.0/src/pitstop/cache.py +0 -36
- pitstop_cli-1.2.0/src/pitstop/version.py +0 -1
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/.github/workflows/release.yml +0 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/.gitignore +0 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/CHANGELOG.md +0 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/LICENSE +0 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/evals/agent/README.md +0 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/evals/agent/recipes.json +0 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/evals/agent/results/.gitkeep +0 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/evals/agent/tasks.json +0 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/scripts/run-agent-evals.sh +0 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/src/pitstop/__init__.py +0 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/src/pitstop/__main__.py +0 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/src/pitstop/chargers.py +0 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/src/pitstop/cli.py +0 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/src/pitstop/cpo_tariffs.py +0 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/src/pitstop/results.py +0 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/src/pitstop/validation.py +0 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/tests/test_chargers.py +0 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/tests/test_core.py +0 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/tests/test_geocoding.py +0 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/tests/test_query_reuse.py +0 -0
- {pitstop_cli-1.2.0 → pitstop_cli-1.3.0}/tests/test_validation.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: pitstop-cli
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.3.0
|
|
4
4
|
Summary: JSON-first CLI + MCP server for Italian fuel-station prices and EV charging — MIMIT, OpenStreetMap, ISTAT.
|
|
5
5
|
Project-URL: Homepage, https://github.com/galjos/pitstop-cli
|
|
6
6
|
Project-URL: Repository, https://github.com/galjos/pitstop-cli
|
|
@@ -44,10 +44,10 @@ Classifier: Topic :: Scientific/Engineering :: GIS
|
|
|
44
44
|
Classifier: Topic :: Utilities
|
|
45
45
|
Requires-Python: >=3.10
|
|
46
46
|
Provides-Extra: dev
|
|
47
|
-
Requires-Dist: mcp
|
|
47
|
+
Requires-Dist: mcp>=1.12; extra == 'dev'
|
|
48
48
|
Requires-Dist: pytest>=7; extra == 'dev'
|
|
49
49
|
Provides-Extra: mcp
|
|
50
|
-
Requires-Dist: mcp
|
|
50
|
+
Requires-Dist: mcp>=1.12; extra == 'mcp'
|
|
51
51
|
Description-Content-Type: text/markdown
|
|
52
52
|
|
|
53
53
|
# pitstop
|
|
@@ -128,11 +128,11 @@ pitstop chargers --comune Livo --provincia TN --json
|
|
|
128
128
|
pitstop chargers --comune-id 021008 --radius 5 --fast --json
|
|
129
129
|
```
|
|
130
130
|
|
|
131
|
-
`stations` flags: `--comune`, `--provincia`, `--brand`, `--near "lat,lon"`, `--radius`, `--fuel` (substring, case-insensitive), `--self`, `--served`, `--cheapest` (needs `--fuel`), `--min-price`, `--fresh-within-days`, `--max-deviation-pct`, `--no-comune-validate`, `--limit`, `--json`, `--geojson`. Choose one output format. `--limit 0` returns every match.
|
|
131
|
+
`stations` flags: `--comune`, `--provincia`, `--brand`, `--near "lat,lon"`, `--radius`, `--fuel` (substring, case-insensitive), `--self`, `--served`, `--cheapest` (needs `--fuel`), `--min-price`, `--fresh-within-days`, `--max-deviation-pct`, `--drop-outliers`, `--no-comune-validate`, `--limit`, `--json`, `--geojson`. Choose one output format. `--limit 0` returns every match.
|
|
132
132
|
|
|
133
133
|
Distances and radii are straight-line measurements, not driving distances or travel times.
|
|
134
134
|
|
|
135
|
-
Loading flags (`--refresh`, `--max-age` in seconds, `--timeout` in seconds) apply to MIMIT commands and charger searches. The default caches last 24 hours for MIMIT, seven days for OSM, and 30 days for the municipality reference. `--refresh` also refreshes a charger's municipality lookup; `--max-age` controls its charger results. `--max-age 0` accepts cached files of any age. `places` supports `--refresh` and `--timeout
|
|
135
|
+
Loading flags (`--refresh`, `--max-age` in seconds, `--timeout` in seconds) apply to MIMIT commands and charger searches. The default caches last 24 hours for MIMIT, seven days for OSM, and 30 days for the municipality reference. `--refresh` also refreshes a charger's municipality lookup; `--max-age` controls its charger results. `--max-age 0` accepts cached files of any age. `places` supports `--refresh` and `--timeout` (no `--max-age`).
|
|
136
136
|
|
|
137
137
|
Every returned price carries a `median_basis`. A `screened` price also carries `regional_median` and `deviation_pct`, plus `outlier: true` when it is >15% below the local median **or** below the Tukey lower fence Q1−1.5·IQR (the Tukey rule catches misreports in tight markets that the percent rule alone misses). The `outlier` key is emitted **only when it is true**, so read it as optional. Pass `--drop-outliers` to remove flagged prices entirely.
|
|
138
138
|
|
|
@@ -76,11 +76,11 @@ pitstop chargers --comune Livo --provincia TN --json
|
|
|
76
76
|
pitstop chargers --comune-id 021008 --radius 5 --fast --json
|
|
77
77
|
```
|
|
78
78
|
|
|
79
|
-
`stations` flags: `--comune`, `--provincia`, `--brand`, `--near "lat,lon"`, `--radius`, `--fuel` (substring, case-insensitive), `--self`, `--served`, `--cheapest` (needs `--fuel`), `--min-price`, `--fresh-within-days`, `--max-deviation-pct`, `--no-comune-validate`, `--limit`, `--json`, `--geojson`. Choose one output format. `--limit 0` returns every match.
|
|
79
|
+
`stations` flags: `--comune`, `--provincia`, `--brand`, `--near "lat,lon"`, `--radius`, `--fuel` (substring, case-insensitive), `--self`, `--served`, `--cheapest` (needs `--fuel`), `--min-price`, `--fresh-within-days`, `--max-deviation-pct`, `--drop-outliers`, `--no-comune-validate`, `--limit`, `--json`, `--geojson`. Choose one output format. `--limit 0` returns every match.
|
|
80
80
|
|
|
81
81
|
Distances and radii are straight-line measurements, not driving distances or travel times.
|
|
82
82
|
|
|
83
|
-
Loading flags (`--refresh`, `--max-age` in seconds, `--timeout` in seconds) apply to MIMIT commands and charger searches. The default caches last 24 hours for MIMIT, seven days for OSM, and 30 days for the municipality reference. `--refresh` also refreshes a charger's municipality lookup; `--max-age` controls its charger results. `--max-age 0` accepts cached files of any age. `places` supports `--refresh` and `--timeout
|
|
83
|
+
Loading flags (`--refresh`, `--max-age` in seconds, `--timeout` in seconds) apply to MIMIT commands and charger searches. The default caches last 24 hours for MIMIT, seven days for OSM, and 30 days for the municipality reference. `--refresh` also refreshes a charger's municipality lookup; `--max-age` controls its charger results. `--max-age 0` accepts cached files of any age. `places` supports `--refresh` and `--timeout` (no `--max-age`).
|
|
84
84
|
|
|
85
85
|
Every returned price carries a `median_basis`. A `screened` price also carries `regional_median` and `deviation_pct`, plus `outlier: true` when it is >15% below the local median **or** below the Tukey lower fence Q1−1.5·IQR (the Tukey rule catches misreports in tight markets that the percent rule alone misses). The `outlier` key is emitted **only when it is true**, so read it as optional. Pass `--drop-outliers` to remove flagged prices entirely.
|
|
86
86
|
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "pitstop-cli"
|
|
7
|
-
version = "1.
|
|
7
|
+
version = "1.3.0"
|
|
8
8
|
description = "JSON-first CLI + MCP server for Italian fuel-station prices and EV charging — MIMIT, OpenStreetMap, ISTAT."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -38,10 +38,11 @@ Changelog = "https://github.com/galjos/pitstop-cli/blob/main/CHANGELOG.md"
|
|
|
38
38
|
Issues = "https://github.com/galjos/pitstop-cli/issues"
|
|
39
39
|
|
|
40
40
|
[project.optional-dependencies]
|
|
41
|
-
#
|
|
42
|
-
#
|
|
43
|
-
|
|
44
|
-
|
|
41
|
+
# mcp_server.py imports MCPServer/FastMCP and ToolAnnotations through a
|
|
42
|
+
# version shim covering mcp 1.12+ and 2.x; keep the 1.12 floor (read-only
|
|
43
|
+
# annotations, structured output) on both extras.
|
|
44
|
+
mcp = ["mcp>=1.12"]
|
|
45
|
+
dev = ["pytest>=7", "mcp>=1.12"]
|
|
45
46
|
|
|
46
47
|
[project.scripts]
|
|
47
48
|
pitstop = "pitstop.cli:main"
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# Geographic acceptance: municipality resolution and charger locations.
|
|
3
|
+
#
|
|
4
|
+
# Live-only (needs the comuni reference + Overpass). Runs in the weekly
|
|
5
|
+
# upstream-smoke workflow, not in PR CI.
|
|
6
|
+
#
|
|
7
|
+
# Exit 0 -> all location assertions passed, or the upstream was unreachable
|
|
8
|
+
# and that outage was reported honestly (GitHub ::warning, UPSTREAM-* lines).
|
|
9
|
+
# Exit 1 -> pitstop resolved a place it should have gotten right. Act on it.
|
|
10
|
+
#
|
|
11
|
+
# Distance budgets are generous on purpose: they catch a wrong-city regression
|
|
12
|
+
# (the 20 km Bolzano reference error this suite exists for) without paging on
|
|
13
|
+
# ordinary reference-vs-OSM drift of a few kilometres.
|
|
14
|
+
|
|
15
|
+
set -u
|
|
16
|
+
|
|
17
|
+
BIN="${PITSTOP_GEO_BIN:-pitstop}"
|
|
18
|
+
OUT="$(mktemp -d "${TMPDIR:-/tmp}/pitstop-geo-acceptance-XXXXXX")"
|
|
19
|
+
trap 'rm -rf "$OUT"' EXIT INT TERM
|
|
20
|
+
|
|
21
|
+
warn() {
|
|
22
|
+
echo "GEO-ACCEPTANCE: UPSTREAM-$1"
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
check_charger_center() {
|
|
26
|
+
name="$1"; comune="$2"; lat="$3"; lon="$4"; budget_km="$5"
|
|
27
|
+
if ! "$BIN" chargers --comune "$comune" --radius 5 --limit 1 --json > "$OUT/center.json" 2>"$OUT/center.err"; then
|
|
28
|
+
if grep -qi "no unique mapped center\|could not fetch\|failed" "$OUT/center.err"; then
|
|
29
|
+
warn "DEGRADED charger center $name unverifiable: $(cat "$OUT/center.err")"
|
|
30
|
+
return 2
|
|
31
|
+
fi
|
|
32
|
+
echo "GEO-ACCEPTANCE: FAIL $name: chargers exited non-zero: $(cat "$OUT/center.err")"
|
|
33
|
+
return 1
|
|
34
|
+
fi
|
|
35
|
+
python3 - "$OUT/center.json" "$name" "$lat" "$lon" "$budget_km" <<'PY'
|
|
36
|
+
import json, math, sys
|
|
37
|
+
|
|
38
|
+
path, name, lat, lon, budget = sys.argv[1], sys.argv[2], float(sys.argv[3]), float(sys.argv[4]), float(sys.argv[5])
|
|
39
|
+
with open(path, encoding="utf-8") as fh:
|
|
40
|
+
payload = json.load(fh)
|
|
41
|
+
if payload.get("error"):
|
|
42
|
+
print(f"GEO-ACCEPTANCE: UPSTREAM-DEGRADED charger center {name}: {payload['error']}")
|
|
43
|
+
sys.exit(2)
|
|
44
|
+
loc = payload.get("location", {})
|
|
45
|
+
try:
|
|
46
|
+
got_lat, got_lon = float(loc["lat"]), float(loc["lon"])
|
|
47
|
+
except (KeyError, TypeError, ValueError):
|
|
48
|
+
print(f"GEO-ACCEPTANCE: FAIL {name}: no location in {payload}")
|
|
49
|
+
sys.exit(1)
|
|
50
|
+
|
|
51
|
+
r = 6371.0
|
|
52
|
+
p1, p2 = math.radians(lat), math.radians(got_lat)
|
|
53
|
+
h = math.sin(math.radians(got_lat - lat) / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(math.radians(got_lon - lon) / 2) ** 2
|
|
54
|
+
km = 2 * r * math.asin(math.sqrt(h))
|
|
55
|
+
if km > budget:
|
|
56
|
+
print(f"GEO-ACCEPTANCE: FAIL {name}: center {got_lat},{got_lon} ({km:.1f} km from {lat},{lon}, budget {budget} km)")
|
|
57
|
+
sys.exit(1)
|
|
58
|
+
print(f"GEO-ACCEPTANCE: ok {name} center -> {got_lat},{got_lon} ({km:.1f} km)")
|
|
59
|
+
PY
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
failures=0
|
|
63
|
+
unavailable=0
|
|
64
|
+
|
|
65
|
+
check_charger_center "Bozen" "Bozen" "46.498" "11.354" "25"; rc=$?
|
|
66
|
+
[ "$rc" -eq 1 ] && failures=$((failures + 1))
|
|
67
|
+
[ "$rc" -eq 2 ] && unavailable=$((unavailable + 1))
|
|
68
|
+
|
|
69
|
+
check_charger_center "Roma" "Roma" "41.903" "12.496" "30"; rc=$?
|
|
70
|
+
[ "$rc" -eq 1 ] && failures=$((failures + 1))
|
|
71
|
+
[ "$rc" -eq 2 ] && unavailable=$((unavailable + 1))
|
|
72
|
+
|
|
73
|
+
if "$BIN" places Livo --json > "$OUT/livo.json" 2>"$OUT/livo.err"; then
|
|
74
|
+
python3 - "$OUT/livo.json" <<'PY'
|
|
75
|
+
import json, sys
|
|
76
|
+
|
|
77
|
+
with open(sys.argv[1], encoding="utf-8") as fh:
|
|
78
|
+
payload = json.load(fh)
|
|
79
|
+
provs = {p.get("provincia") for p in payload.get("places", [])}
|
|
80
|
+
if not {"CO", "TN"} <= provs:
|
|
81
|
+
print(f"GEO-ACCEPTANCE: FAIL Livo: CO+TN missing from {sorted(provs)}")
|
|
82
|
+
sys.exit(1)
|
|
83
|
+
print("GEO-ACCEPTANCE: ok Livo -> CO+TN both listed")
|
|
84
|
+
PY
|
|
85
|
+
[ "$?" -ne 0 ] && failures=$((failures + 1))
|
|
86
|
+
# Ambiguous exact names must refuse to guess (exit 2), not pick a province.
|
|
87
|
+
"$BIN" chargers --comune Livo --json > "$OUT/livo-amb.json" 2>"$OUT/livo-amb.err"
|
|
88
|
+
rc=$?
|
|
89
|
+
if [ "$rc" -eq 2 ] && grep -qi "ambiguous\|disambiguat" "$OUT/livo-amb.err"; then
|
|
90
|
+
echo "GEO-ACCEPTANCE: ok Livo -> ambiguous --comune exits 2"
|
|
91
|
+
else
|
|
92
|
+
echo "GEO-ACCEPTANCE: FAIL Livo: ambiguous --comune exited $rc, want 2 with a disambiguation error: $(cat "$OUT/livo-amb.err")"
|
|
93
|
+
failures=$((failures + 1))
|
|
94
|
+
fi
|
|
95
|
+
else
|
|
96
|
+
warn "UNAVAILABLE places Livo exited non-zero: $(cat "$OUT/livo.err")"
|
|
97
|
+
unavailable=$((unavailable + 1))
|
|
98
|
+
fi
|
|
99
|
+
|
|
100
|
+
if "$BIN" chargers --near 46.498,11.354 --radius 5 --limit 5 --json > "$OUT/chargers.json" 2>"$OUT/chargers.err"; then
|
|
101
|
+
python3 - "$OUT/chargers.json" <<'PY'
|
|
102
|
+
import json, math, sys
|
|
103
|
+
|
|
104
|
+
with open(sys.argv[1], encoding="utf-8") as fh:
|
|
105
|
+
payload = json.load(fh)
|
|
106
|
+
if payload.get("error"):
|
|
107
|
+
print(f"GEO-ACCEPTANCE: UPSTREAM-DEGRADED chargers: {payload['error']}")
|
|
108
|
+
sys.exit(2)
|
|
109
|
+
qlat, qlon, radius = 46.498, 11.354, 5.0
|
|
110
|
+
for st in payload.get("stations", []):
|
|
111
|
+
try:
|
|
112
|
+
d = float(st.get("distance_km", "nan"))
|
|
113
|
+
except (TypeError, ValueError):
|
|
114
|
+
print(f"GEO-ACCEPTANCE: FAIL charger without distance: {st.get('name')}")
|
|
115
|
+
sys.exit(1)
|
|
116
|
+
if not (d <= radius + 1.0):
|
|
117
|
+
print(f"GEO-ACCEPTANCE: FAIL charger {st.get('name')} at {d} km, outside radius {radius} km + 1 km tolerance")
|
|
118
|
+
sys.exit(1)
|
|
119
|
+
print(f"GEO-ACCEPTANCE: ok chargers near 46.498,11.354 ({payload.get('count', 0)} returned)")
|
|
120
|
+
PY
|
|
121
|
+
rc=$?
|
|
122
|
+
[ "$rc" -eq 1 ] && failures=$((failures + 1))
|
|
123
|
+
[ "$rc" -eq 2 ] && unavailable=$((unavailable + 1))
|
|
124
|
+
else
|
|
125
|
+
warn "UNAVAILABLE chargers exited non-zero: $(cat "$OUT/chargers.err")"
|
|
126
|
+
unavailable=$((unavailable + 1))
|
|
127
|
+
fi
|
|
128
|
+
|
|
129
|
+
if [ "$failures" -gt 0 ]; then
|
|
130
|
+
echo "GEO-ACCEPTANCE: $failures failing check(s)"
|
|
131
|
+
exit 1
|
|
132
|
+
fi
|
|
133
|
+
if [ "$unavailable" -gt 0 ]; then
|
|
134
|
+
echo "::warning title=Geo acceptance skipped on unreachable upstream::$unavailable check(s) could not reach the comuni reference or Overpass; location assertions that ran passed."
|
|
135
|
+
fi
|
|
136
|
+
echo "GEO-ACCEPTANCE: passed"
|
|
@@ -14,6 +14,22 @@ async def check_mcp(env):
|
|
|
14
14
|
from mcp import ClientSession, StdioServerParameters
|
|
15
15
|
from mcp.client.stdio import stdio_client
|
|
16
16
|
|
|
17
|
+
# CallToolResult.isError on mcp 1.x, is_error on 2.x.
|
|
18
|
+
def _result_error(result):
|
|
19
|
+
for name in ("isError", "is_error"):
|
|
20
|
+
value = getattr(result, name, None)
|
|
21
|
+
if value is not None:
|
|
22
|
+
return value
|
|
23
|
+
raise AssertionError("CallToolResult has neither isError nor is_error")
|
|
24
|
+
|
|
25
|
+
# structuredContent on mcp 1.x, structured_content on 2.x.
|
|
26
|
+
def _structured(result):
|
|
27
|
+
for name in ("structuredContent", "structured_content"):
|
|
28
|
+
value = getattr(result, name, None)
|
|
29
|
+
if value is not None:
|
|
30
|
+
return value
|
|
31
|
+
raise AssertionError("CallToolResult has neither structuredContent nor structured_content")
|
|
32
|
+
|
|
17
33
|
params = StdioServerParameters(command=sys.executable, args=["-m", "pitstop.mcp_server"], env=env)
|
|
18
34
|
async with stdio_client(params) as (read, write):
|
|
19
35
|
async with ClientSession(read, write) as session:
|
|
@@ -22,13 +38,20 @@ async def check_mcp(env):
|
|
|
22
38
|
assert {t.name for t in tools} == {
|
|
23
39
|
"find_stations", "find_cheapest", "find_chargers", "find_places", "list_fuels", "get_stats"
|
|
24
40
|
}
|
|
25
|
-
|
|
26
|
-
|
|
41
|
+
# ToolAnnotations field names are camelCase on mcp 1.x, snake_case on 2.x.
|
|
42
|
+
def _ann(tool, *names):
|
|
43
|
+
for name in names:
|
|
44
|
+
value = getattr(tool.annotations, name, None)
|
|
45
|
+
if value is not None:
|
|
46
|
+
return value
|
|
47
|
+
return None
|
|
48
|
+
assert all(t.annotations and _ann(t, "readOnlyHint", "read_only_hint") and
|
|
49
|
+
_ann(t, "destructiveHint", "destructive_hint") is False for t in tools)
|
|
27
50
|
result = await session.call_tool("find_places", {"query": "Livo"})
|
|
28
|
-
assert not result
|
|
29
|
-
assert {p["provincia"] for p in result
|
|
51
|
+
assert not _result_error(result) and _structured(result)["matched_count"] == 2
|
|
52
|
+
assert {p["provincia"] for p in _structured(result)["places"]} == {"CO", "TN"}
|
|
30
53
|
result = await session.call_tool("find_chargers", {"near": "nan,11"})
|
|
31
|
-
assert result
|
|
54
|
+
assert _result_error(result)
|
|
32
55
|
print("Installed MCP: six read-only tools, structured discovery, invalid-input error passed")
|
|
33
56
|
|
|
34
57
|
|
|
@@ -13,14 +13,14 @@ metadata:
|
|
|
13
13
|
{
|
|
14
14
|
"id": "uvx",
|
|
15
15
|
"kind": "uvx",
|
|
16
|
-
"package": "pitstop-cli>=1.
|
|
16
|
+
"package": "pitstop-cli>=1.3.0",
|
|
17
17
|
"bins": ["pitstop"],
|
|
18
18
|
"label": "Run pitstop on demand (uvx)",
|
|
19
19
|
},
|
|
20
20
|
{
|
|
21
21
|
"id": "pipx",
|
|
22
22
|
"kind": "pipx",
|
|
23
|
-
"package": "pitstop-cli>=1.
|
|
23
|
+
"package": "pitstop-cli>=1.3.0",
|
|
24
24
|
"bins": ["pitstop"],
|
|
25
25
|
"label": "Install pitstop (pipx)",
|
|
26
26
|
},
|
|
@@ -65,10 +65,12 @@ pitstop chargers --comune Bozen --radius 5 --socket ccs --fast --public --json
|
|
|
65
65
|
|
|
66
66
|
Key flags:
|
|
67
67
|
- `--comune`: Municipality name. Supports international names (**Rome, Milan, Venice, Florence, Bozen, Mailand, Venise**, etc.).
|
|
68
|
-
- `--fuel`: Substring search. Supports **comma-separated lists** (e.g. `Benzina,Gasolio`).
|
|
68
|
+
- `--fuel`: Substring search. Supports **comma-separated lists** (e.g. `Benzina,Gasolio`). With `--cheapest` and a comma list, each station ranks by its cheapest listed fuel.
|
|
69
69
|
- `--geojson`: Emits a standard GeoJSON FeatureCollection with properties and geometry.
|
|
70
|
-
- Other flags: `--provincia`, `--brand`, `--near`, `--radius`, `--self`/`--served`, `--cheapest
|
|
70
|
+
- Other station flags: `--provincia`, `--brand`, `--near`, `--radius`, `--self`/`--served`, `--cheapest` (needs `--fuel`), `--min-price`, `--fresh-within-days`, `--max-deviation-pct`, `--drop-outliers`, `--no-comune-validate`, `--limit`, `--json`, `--refresh`, `--max-age`, `--timeout`.
|
|
71
|
+
- Charger flags: `--near`, `--comune`, `--provincia`, `--comune-id` (discover with `places`; use when names duplicate), `--radius`, `--operator`, `--socket`, `--min-power`, `--fast`, `--ultra-fast`, `--free` (only explicit `fee=no`; unknown fee excluded), `--public` (only explicit public access; unknown excluded), `--limit`, `--json`/`--geojson`, `--refresh`, `--timeout`, `--max-age`.
|
|
71
72
|
- Charger power uses `--min-power` in kW; `--fast` means at least 50 kW and `--ultra-fast` at least 150 kW. Inspect the matching socket's power as well as the station maximum.
|
|
73
|
+
- CLI↔MCP names differ: `--min-power` is `min_power_kw`, `--radius` is `radius_km`, `--free`/`--public` are `free_only`/`public_only`, `--fresh-within-days` is `max_age_days`, `--comune-id` is `comune_id`.
|
|
72
74
|
|
|
73
75
|
## JSON / GeoJSON contract
|
|
74
76
|
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Atomic cache writes, source-fetch timestamps, and bounded download retries."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import tempfile
|
|
7
|
+
import time
|
|
8
|
+
import urllib.error
|
|
9
|
+
import urllib.request
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
RETRY_ATTEMPTS = 3
|
|
14
|
+
RETRY_BASE_DELAY = 1.0 # seconds; doubled between attempts
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def write_atomic(path: Path, data: bytes) -> None:
|
|
18
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
19
|
+
name = None
|
|
20
|
+
try:
|
|
21
|
+
with tempfile.NamedTemporaryFile(dir=path.parent, prefix=path.name + ".", delete=False) as f:
|
|
22
|
+
name = f.name
|
|
23
|
+
f.write(data)
|
|
24
|
+
os.replace(name, path)
|
|
25
|
+
finally:
|
|
26
|
+
if name is not None:
|
|
27
|
+
Path(name).unlink(missing_ok=True)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def file_metadata(path: Path, status: str | None = None) -> dict:
|
|
31
|
+
return fetch_metadata(path.stat().st_mtime, status)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def fetch_metadata(fetched: float, status: str | None = None) -> dict:
|
|
35
|
+
result = {
|
|
36
|
+
"fetched_at": datetime.fromtimestamp(fetched, timezone.utc).isoformat(),
|
|
37
|
+
"age_seconds": max(0, int(time.time() - fetched)),
|
|
38
|
+
}
|
|
39
|
+
if status is not None:
|
|
40
|
+
result["cache_status"] = status
|
|
41
|
+
return result
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _retryable(error: Exception) -> bool:
|
|
45
|
+
"""Whether a failed download is worth retrying (transient network or server)."""
|
|
46
|
+
if isinstance(error, urllib.error.HTTPError):
|
|
47
|
+
return error.code == 429 or 500 <= error.code < 600
|
|
48
|
+
return isinstance(error, (urllib.error.URLError, OSError))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def fetch_bytes(req: urllib.request.Request, timeout: int, attempts: int = RETRY_ATTEMPTS) -> bytes:
|
|
52
|
+
"""Download a URL, retrying transient failures with backoff. Raises the last error."""
|
|
53
|
+
last: Exception | None = None
|
|
54
|
+
for attempt in range(max(1, attempts)):
|
|
55
|
+
try:
|
|
56
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
57
|
+
return resp.read()
|
|
58
|
+
except (urllib.error.URLError, OSError) as e:
|
|
59
|
+
last = e
|
|
60
|
+
if not _retryable(e) or attempt + 1 >= max(1, attempts):
|
|
61
|
+
raise
|
|
62
|
+
time.sleep(RETRY_BASE_DELAY * (2 ** attempt))
|
|
63
|
+
raise last # pragma: no cover - loop always raises first
|
|
@@ -17,7 +17,7 @@ from functools import cached_property, lru_cache
|
|
|
17
17
|
from pathlib import Path
|
|
18
18
|
|
|
19
19
|
from .validation import validate_search, validate_download, validate_nonnegative
|
|
20
|
-
from .cache import fetch_metadata, write_atomic
|
|
20
|
+
from .cache import fetch_bytes, fetch_metadata, write_atomic
|
|
21
21
|
from .results import SearchResults, coverage_of
|
|
22
22
|
|
|
23
23
|
ANAGRAFICA_URL = "https://www.mimit.gov.it/images/exportCSV/anagrafica_impianti_attivi.csv"
|
|
@@ -161,8 +161,7 @@ def _cached_file(
|
|
|
161
161
|
return path
|
|
162
162
|
|
|
163
163
|
req = urllib.request.Request(url, headers={"User-Agent": "pitstop"})
|
|
164
|
-
|
|
165
|
-
data = resp.read()
|
|
164
|
+
data = fetch_bytes(req, timeout)
|
|
166
165
|
|
|
167
166
|
# MIMIT serves its maintenance page with HTTP 200, so a successful request is
|
|
168
167
|
# not evidence we got the CSV. Caching one blip poisons the whole max_age window.
|
|
@@ -20,7 +20,7 @@ import urllib.request
|
|
|
20
20
|
from dataclasses import dataclass
|
|
21
21
|
from pathlib import Path
|
|
22
22
|
|
|
23
|
-
from .cache import write_atomic
|
|
23
|
+
from .cache import fetch_bytes, write_atomic
|
|
24
24
|
from .validation import QueryError, parse_near, validate_download
|
|
25
25
|
|
|
26
26
|
COMUNI_URL = (
|
|
@@ -110,8 +110,7 @@ def _cached_path(refresh: bool, max_age: int, timeout: int) -> Path | None:
|
|
|
110
110
|
return path
|
|
111
111
|
try:
|
|
112
112
|
req = urllib.request.Request(COMUNI_URL, headers={"User-Agent": "pitstop"})
|
|
113
|
-
|
|
114
|
-
data = resp.read()
|
|
113
|
+
data = fetch_bytes(req, timeout)
|
|
115
114
|
except (urllib.error.URLError, OSError) as e:
|
|
116
115
|
# Graceful fallback: if we cannot fetch, return any stale cache or None.
|
|
117
116
|
print(f"pitstop: could not fetch comune coordinates ({e}); "
|
|
@@ -5,15 +5,22 @@ optional `mcp` extra: pip install "pitstop-cli[mcp]". Run with `pitstop-mcp`."""
|
|
|
5
5
|
|
|
6
6
|
from typing import Any, Optional
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
from mcp.
|
|
8
|
+
try: # mcp 2.x renamed FastMCP to MCPServer and moved ToolAnnotations out of mcp.types
|
|
9
|
+
from mcp.server.mcpserver import MCPServer as _Server
|
|
10
|
+
from mcp_types import ToolAnnotations
|
|
11
|
+
_ANNOTATIONS_KW = {"read_only_hint": True, "destructive_hint": False,
|
|
12
|
+
"idempotent_hint": True, "open_world_hint": True}
|
|
13
|
+
except ImportError: # mcp 1.x
|
|
14
|
+
from mcp.server.fastmcp import FastMCP as _Server
|
|
15
|
+
from mcp.types import ToolAnnotations
|
|
16
|
+
_ANNOTATIONS_KW = {"readOnlyHint": True, "destructiveHint": False,
|
|
17
|
+
"idempotentHint": True, "openWorldHint": True}
|
|
10
18
|
|
|
11
19
|
from . import chargers as ev_chargers
|
|
12
20
|
from . import core, geocoding, validation
|
|
13
21
|
|
|
14
|
-
mcp =
|
|
15
|
-
_READ_ONLY = ToolAnnotations(
|
|
16
|
-
idempotentHint=True, openWorldHint=True)
|
|
22
|
+
mcp = _Server("pitstop")
|
|
23
|
+
_READ_ONLY = ToolAnnotations(**_ANNOTATIONS_KW)
|
|
17
24
|
|
|
18
25
|
_CAVEATS = (
|
|
19
26
|
" Data is daily (not real-time): prices are as of ~08:00 the day before "
|
|
@@ -15,7 +15,7 @@ import urllib.error
|
|
|
15
15
|
import urllib.request
|
|
16
16
|
from pathlib import Path
|
|
17
17
|
|
|
18
|
-
from .cache import file_metadata, write_atomic
|
|
18
|
+
from .cache import fetch_bytes, file_metadata, write_atomic
|
|
19
19
|
from .validation import validate_download
|
|
20
20
|
from .version import __version__
|
|
21
21
|
|
|
@@ -80,8 +80,7 @@ def fetch_elements(
|
|
|
80
80
|
)
|
|
81
81
|
error = None
|
|
82
82
|
try:
|
|
83
|
-
|
|
84
|
-
data = resp.read()
|
|
83
|
+
data = fetch_bytes(req, timeout)
|
|
85
84
|
except (urllib.error.URLError, OSError) as e:
|
|
86
85
|
error = str(e)
|
|
87
86
|
print(f"pitstop: Overpass fetch failed ({error}); "
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.3.0"
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Bounded download retries: transient failures retried, permanent ones raised fast."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
import urllib.error
|
|
7
|
+
|
|
8
|
+
from pitstop import cache
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class _Resp:
|
|
12
|
+
def __init__(self, data: bytes):
|
|
13
|
+
self._data = data
|
|
14
|
+
|
|
15
|
+
def read(self) -> bytes:
|
|
16
|
+
return self._data
|
|
17
|
+
|
|
18
|
+
def __enter__(self):
|
|
19
|
+
return self
|
|
20
|
+
|
|
21
|
+
def __exit__(self, *args):
|
|
22
|
+
return False
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _req():
|
|
26
|
+
import urllib.request
|
|
27
|
+
|
|
28
|
+
return urllib.request.Request("https://example.test/x")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_retry_then_success(monkeypatch):
|
|
32
|
+
monkeypatch.setattr(cache, "RETRY_BASE_DELAY", 0)
|
|
33
|
+
calls = {"n": 0}
|
|
34
|
+
|
|
35
|
+
def flaky(req, timeout):
|
|
36
|
+
calls["n"] += 1
|
|
37
|
+
if calls["n"] < 3:
|
|
38
|
+
raise urllib.error.HTTPError(req.full_url, 503, "busy", {}, io.BytesIO())
|
|
39
|
+
return _Resp(b"ok")
|
|
40
|
+
|
|
41
|
+
monkeypatch.setattr(cache.urllib.request, "urlopen", flaky)
|
|
42
|
+
assert cache.fetch_bytes(_req(), 5) == b"ok"
|
|
43
|
+
assert calls["n"] == 3
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_no_retry_on_404(monkeypatch):
|
|
47
|
+
monkeypatch.setattr(cache, "RETRY_BASE_DELAY", 0)
|
|
48
|
+
calls = {"n": 0}
|
|
49
|
+
|
|
50
|
+
def missing(req, timeout):
|
|
51
|
+
calls["n"] += 1
|
|
52
|
+
raise urllib.error.HTTPError(req.full_url, 404, "nope", {}, io.BytesIO())
|
|
53
|
+
|
|
54
|
+
monkeypatch.setattr(cache.urllib.request, "urlopen", missing)
|
|
55
|
+
try:
|
|
56
|
+
cache.fetch_bytes(_req(), 5)
|
|
57
|
+
except urllib.error.HTTPError as e:
|
|
58
|
+
assert e.code == 404
|
|
59
|
+
else:
|
|
60
|
+
raise AssertionError("expected HTTPError")
|
|
61
|
+
assert calls["n"] == 1
|
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
"""Atomic cache writes and source-fetch timestamps."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
import os
|
|
6
|
-
import tempfile
|
|
7
|
-
import time
|
|
8
|
-
from datetime import datetime, timezone
|
|
9
|
-
from pathlib import Path
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
def write_atomic(path: Path, data: bytes) -> None:
|
|
13
|
-
path.parent.mkdir(parents=True, exist_ok=True)
|
|
14
|
-
name = None
|
|
15
|
-
try:
|
|
16
|
-
with tempfile.NamedTemporaryFile(dir=path.parent, prefix=path.name + ".", delete=False) as f:
|
|
17
|
-
name = f.name
|
|
18
|
-
f.write(data)
|
|
19
|
-
os.replace(name, path)
|
|
20
|
-
finally:
|
|
21
|
-
if name is not None:
|
|
22
|
-
Path(name).unlink(missing_ok=True)
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
def file_metadata(path: Path, status: str | None = None) -> dict:
|
|
26
|
-
return fetch_metadata(path.stat().st_mtime, status)
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
def fetch_metadata(fetched: float, status: str | None = None) -> dict:
|
|
30
|
-
result = {
|
|
31
|
-
"fetched_at": datetime.fromtimestamp(fetched, timezone.utc).isoformat(),
|
|
32
|
-
"age_seconds": max(0, int(time.time() - fetched)),
|
|
33
|
-
}
|
|
34
|
-
if status is not None:
|
|
35
|
-
result["cache_status"] = status
|
|
36
|
-
return result
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "1.2.0"
|
|
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
|
|
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
|
|
File without changes
|