pitstop-cli 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pitstop/__init__.py +3 -0
- pitstop/__main__.py +4 -0
- pitstop/chargers.py +281 -0
- pitstop/cli.py +418 -0
- pitstop/core.py +572 -0
- pitstop/cpo_tariffs.py +60 -0
- pitstop/geocoding.py +146 -0
- pitstop/mcp_server.py +264 -0
- pitstop/overpass.py +83 -0
- pitstop/version.py +1 -0
- pitstop_cli-1.0.0.dist-info/METADATA +170 -0
- pitstop_cli-1.0.0.dist-info/RECORD +15 -0
- pitstop_cli-1.0.0.dist-info/WHEEL +4 -0
- pitstop_cli-1.0.0.dist-info/entry_points.txt +3 -0
- pitstop_cli-1.0.0.dist-info/licenses/LICENSE +21 -0
pitstop/geocoding.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Second data source: authoritative Italian comune coordinates, used to
|
|
2
|
+
validate MIMIT station coordinates. Self-contained centroid heuristics in
|
|
3
|
+
`core` cannot catch mis-geocoded stations in single-station comuni (e.g.
|
|
4
|
+
RASUN-ANTERSELVA), so a true comune→(lat, lon) reference is required.
|
|
5
|
+
|
|
6
|
+
Source: opendatasicilia/comuni-italiani `main.csv`, derived from ISTAT.
|
|
7
|
+
Runtime fetch + local cache; no redistribution."""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import csv
|
|
12
|
+
import os
|
|
13
|
+
import sys
|
|
14
|
+
import time
|
|
15
|
+
import urllib.error
|
|
16
|
+
import urllib.request
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
COMUNI_URL = (
|
|
20
|
+
"https://raw.githubusercontent.com/opendatasicilia/comuni-italiani/main/dati/main.csv"
|
|
21
|
+
)
|
|
22
|
+
COMUNI_SOURCE_NAME = "opendatasicilia/comuni-italiani (ISTAT-derived)"
|
|
23
|
+
|
|
24
|
+
DEFAULT_COMUNI_MAX_AGE = 30 * 24 * 60 * 60 # 30 days; comuni change rarely
|
|
25
|
+
DEFAULT_TIMEOUT = 180
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _cache_dir() -> Path:
|
|
29
|
+
base = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
|
|
30
|
+
d = Path(base) / "pitstop"
|
|
31
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
32
|
+
return d
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# Common bilingual name mappings for major Italian cities and South Tyrol.
|
|
36
|
+
# MIMIT uses the Italian name but users/agents may use English, French, or
|
|
37
|
+
# German forms. Keyed by normalized uppercase foreign name. Each entry appears
|
|
38
|
+
# once — words shared across languages (e.g. ROME = English + French) are
|
|
39
|
+
# listed once and treated as language-neutral.
|
|
40
|
+
BILINGUAL_MAP = {
|
|
41
|
+
# South Tyrol / Südtirol (German → Italian)
|
|
42
|
+
"BOZEN": "BOLZANO",
|
|
43
|
+
"MERAN": "MERANO",
|
|
44
|
+
"BRIXEN": "BRESSANONE",
|
|
45
|
+
"BRUNECK": "BRUNICO",
|
|
46
|
+
"STERZING": "VIPITENO",
|
|
47
|
+
"LEIFERS": "LAIVES",
|
|
48
|
+
"KALTERN": "CALDARO SULLA STRADA DEL VINO",
|
|
49
|
+
"EPPAN": "APPIANO SULLA STRADA DEL VINO",
|
|
50
|
+
"NEUMARKT": "EGNA",
|
|
51
|
+
"ST. ULRICH": "ORTISEI",
|
|
52
|
+
"ST. CHRISTINA": "SANTA CRISTINA VALGARDENA",
|
|
53
|
+
"WOLKENSTEIN": "SELVA DI VAL GARDENA",
|
|
54
|
+
"SCHLANDERS": "SILANDRO",
|
|
55
|
+
"MALS": "MALLES VENOSTA",
|
|
56
|
+
"KLAUSEN": "CHIUSA",
|
|
57
|
+
"NATURNS": "NATURNO",
|
|
58
|
+
"LATSCH": "LACES",
|
|
59
|
+
"AUER": "ORA",
|
|
60
|
+
"PRAD": "PRATO ALLO STELVIO",
|
|
61
|
+
# Major Italian cities — German forms
|
|
62
|
+
"ROM": "ROMA",
|
|
63
|
+
"MAILAND": "MILANO",
|
|
64
|
+
"VENEDIG": "VENEZIA",
|
|
65
|
+
"FLORENZ": "FIRENZE",
|
|
66
|
+
"NEAPEL": "NAPOLI",
|
|
67
|
+
"GENUA": "GENOVA",
|
|
68
|
+
"SYRAKUS": "SIRACUSA",
|
|
69
|
+
# Major Italian cities — English forms
|
|
70
|
+
"ROME": "ROMA",
|
|
71
|
+
"MILAN": "MILANO",
|
|
72
|
+
"VENICE": "VENEZIA",
|
|
73
|
+
"FLORENCE": "FIRENZE",
|
|
74
|
+
"TURIN": "TORINO",
|
|
75
|
+
"NAPLES": "NAPOLI",
|
|
76
|
+
"GENOA": "GENOVA",
|
|
77
|
+
"PADUA": "PADOVA",
|
|
78
|
+
"SYRACUSE": "SIRACUSA",
|
|
79
|
+
"MANTUA": "MANTOVA",
|
|
80
|
+
# Major Italian cities — French forms (only the ones that differ from above)
|
|
81
|
+
"VENISE": "VENEZIA",
|
|
82
|
+
"GENES": "GENOVA",
|
|
83
|
+
"PADOUE": "PADOVA",
|
|
84
|
+
"MANTOUE": "MANTOVA",
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def normalize_comune(name: str) -> str:
|
|
89
|
+
"""Uppercase, trim, collapse internal whitespace. MIMIT uses uppercase
|
|
90
|
+
names; opendatasicilia uses capitalized — uppercase makes both match."""
|
|
91
|
+
if not name:
|
|
92
|
+
return ""
|
|
93
|
+
n = " ".join(name.strip().upper().split())
|
|
94
|
+
# Resolve common German names to the Italian names used in MIMIT/ISTAT.
|
|
95
|
+
return BILINGUAL_MAP.get(n, n)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _cached_path(refresh: bool, max_age: int, timeout: int) -> Path | None:
|
|
99
|
+
path = _cache_dir() / "comuni_main.csv"
|
|
100
|
+
if not refresh and path.exists():
|
|
101
|
+
if max_age <= 0 or (time.time() - path.stat().st_mtime) < max_age:
|
|
102
|
+
return path
|
|
103
|
+
try:
|
|
104
|
+
req = urllib.request.Request(COMUNI_URL, headers={"User-Agent": "pitstop"})
|
|
105
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
106
|
+
data = resp.read()
|
|
107
|
+
except (urllib.error.URLError, OSError) as e:
|
|
108
|
+
# Graceful fallback: if we cannot fetch, return any stale cache or None.
|
|
109
|
+
print(f"pitstop: could not fetch comune coordinates ({e}); "
|
|
110
|
+
f"falling back to self-contained heuristics", file=sys.stderr)
|
|
111
|
+
return path if path.exists() else None
|
|
112
|
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
|
113
|
+
tmp.write_bytes(data)
|
|
114
|
+
tmp.replace(path)
|
|
115
|
+
return path
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def load_comune_coords(
|
|
119
|
+
*,
|
|
120
|
+
refresh: bool = False,
|
|
121
|
+
max_age: int = DEFAULT_COMUNI_MAX_AGE,
|
|
122
|
+
timeout: int = DEFAULT_TIMEOUT,
|
|
123
|
+
) -> dict[str, tuple[float, float]]:
|
|
124
|
+
"""Return {normalized_comune_name: (lat, lon)}. Empty dict on fetch failure
|
|
125
|
+
with no cache, so callers should treat it as best-effort."""
|
|
126
|
+
path = _cached_path(refresh, max_age, timeout)
|
|
127
|
+
if path is None:
|
|
128
|
+
return {}
|
|
129
|
+
return _parse_comuni(path)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _parse_comuni(path: Path) -> dict[str, tuple[float, float]]:
|
|
133
|
+
out: dict[str, tuple[float, float]] = {}
|
|
134
|
+
with path.open("r", encoding="utf-8", errors="replace", newline="") as f:
|
|
135
|
+
reader = csv.DictReader(f)
|
|
136
|
+
for row in reader:
|
|
137
|
+
name = row.get("comune", "").strip()
|
|
138
|
+
if not name:
|
|
139
|
+
continue
|
|
140
|
+
try:
|
|
141
|
+
lat = float(row["lat"])
|
|
142
|
+
lon = float(row["long"])
|
|
143
|
+
except (KeyError, ValueError, TypeError):
|
|
144
|
+
continue
|
|
145
|
+
out[normalize_comune(name)] = (lat, lon)
|
|
146
|
+
return out
|
pitstop/mcp_server.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
"""MCP server exposing pitstop's Italian fuel-price data as agent tools.
|
|
2
|
+
|
|
3
|
+
Thin wrapper over pitstop.core (the same logic the CLI uses). Requires the
|
|
4
|
+
optional `mcp` extra: pip install "pitstop[mcp]". Run with `pitstop-mcp`."""
|
|
5
|
+
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
from mcp.server.fastmcp import FastMCP
|
|
9
|
+
|
|
10
|
+
from . import chargers as ev_chargers
|
|
11
|
+
from . import core, geocoding
|
|
12
|
+
|
|
13
|
+
mcp = FastMCP("pitstop")
|
|
14
|
+
|
|
15
|
+
_CAVEATS = (
|
|
16
|
+
" Data is daily (not real-time): prices are as of ~08:00 the day before "
|
|
17
|
+
"price_extraction_date. Italy only. `fuel` supports comma-separated values "
|
|
18
|
+
"(e.g. 'Benzina,Gasolio') and is a substring match. `comune` supports "
|
|
19
|
+
"international names (Rome, Mailand, Venise). Some operators report placeholder "
|
|
20
|
+
"prices (e.g. 1.000); set min_price (e.g. 1.2) to skip them when ranking. Each "
|
|
21
|
+
"price carries regional_median, deviation_pct, and an `outlier` flag (true when "
|
|
22
|
+
">15% below the fuel's median in that provincia) — use the flag to caveat or "
|
|
23
|
+
"set max_deviation_pct to silently drop suspect prices."
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
_FIND_STATIONS_DESC = (
|
|
27
|
+
"Find Italian fuel stations and their prices from MIMIT open data. Filter by "
|
|
28
|
+
"comune (municipality; supports international names like Rome/Milan/Bozen), "
|
|
29
|
+
"provincia (2-letter, e.g. BZ), brand, fuel (substring, case-insensitive; "
|
|
30
|
+
'supports comma-separated lists), near ("lat,lon") within radius_km, and '
|
|
31
|
+
"service mode (self_only/served_only). Set cheapest=True to sort by ascending "
|
|
32
|
+
"price, and min_price to drop placeholder values. Returns a JSON envelope with "
|
|
33
|
+
"provenance, navigation URLs, and a stations list." + _CAVEATS
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
_FIND_CHEAPEST_DESC = (
|
|
37
|
+
"Find the cheapest Italian stations for a given fuel, near a coordinate "
|
|
38
|
+
'("lat,lon") or in a comune (supports international names). By default '
|
|
39
|
+
"applies a fuel-aware price floor (skips placeholder values for petrol/diesel, "
|
|
40
|
+
"no floor for cheap fuels like GPL), ignores prices not updated in the last "
|
|
41
|
+
"90 days, and drops statistical outliers (>15% below median OR below the "
|
|
42
|
+
"Tukey lower fence). Override via min_price, max_age_days, drop_outliers. "
|
|
43
|
+
"Returns a provenance-carrying JSON envelope sorted cheapest-first with "
|
|
44
|
+
"navigation URLs." + _CAVEATS
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _parse_near(near: str) -> Optional[tuple]:
|
|
49
|
+
if not near.strip():
|
|
50
|
+
return None
|
|
51
|
+
lat, lon = near.split(",")
|
|
52
|
+
return (float(lat.strip()), float(lon.strip()))
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@mcp.tool()
|
|
56
|
+
def list_fuels() -> dict:
|
|
57
|
+
"""List the fuel-type names in the Italian MIMIT fuel dataset, with the number
|
|
58
|
+
of price rows for each. Call this first to discover exact `fuel` values."""
|
|
59
|
+
ds = core.load()
|
|
60
|
+
counts: dict[str, int] = {}
|
|
61
|
+
for st in ds.stations.values():
|
|
62
|
+
for p in st.prices:
|
|
63
|
+
counts[p.fuel] = counts.get(p.fuel, 0) + 1
|
|
64
|
+
items = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
|
|
65
|
+
return {
|
|
66
|
+
"source": core.SOURCE_NAME,
|
|
67
|
+
"price_extraction_date": ds.price_date,
|
|
68
|
+
"fuels": [{"fuel": f, "count": c} for f, c in items],
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@mcp.tool()
|
|
73
|
+
def get_stats(fuel: str = "") -> dict:
|
|
74
|
+
"""Get macro-level price statistics (median, min, max) per Italian province
|
|
75
|
+
and a national aggregate. Use this to give advice on whether a region is
|
|
76
|
+
generally cheaper or more expensive than others. `fuel` supports
|
|
77
|
+
comma-separated values."""
|
|
78
|
+
ds = core.load()
|
|
79
|
+
stats = core.fuel_stats(ds, fuel=fuel)
|
|
80
|
+
return {
|
|
81
|
+
"source": core.SOURCE_NAME,
|
|
82
|
+
"price_extraction_date": ds.price_date,
|
|
83
|
+
"generated_at": core.now_iso(),
|
|
84
|
+
"stats": stats
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@mcp.tool(description=_FIND_STATIONS_DESC)
|
|
89
|
+
def find_stations(
|
|
90
|
+
fuel: str = "",
|
|
91
|
+
comune: str = "",
|
|
92
|
+
provincia: str = "",
|
|
93
|
+
brand: str = "",
|
|
94
|
+
near: str = "",
|
|
95
|
+
radius_km: float = 10.0,
|
|
96
|
+
self_only: bool = False,
|
|
97
|
+
served_only: bool = False,
|
|
98
|
+
cheapest: bool = False,
|
|
99
|
+
min_price: float = 0.0,
|
|
100
|
+
max_age_days: int = 0,
|
|
101
|
+
max_deviation_pct: float = 0.0,
|
|
102
|
+
drop_outliers: bool = False,
|
|
103
|
+
limit: int = 20,
|
|
104
|
+
) -> dict:
|
|
105
|
+
ds = core.load()
|
|
106
|
+
comune_norm = geocoding.normalize_comune(comune)
|
|
107
|
+
stations = core.query_stations(
|
|
108
|
+
ds,
|
|
109
|
+
comune=comune_norm,
|
|
110
|
+
provincia=provincia,
|
|
111
|
+
brand=brand,
|
|
112
|
+
near=_parse_near(near),
|
|
113
|
+
radius_km=radius_km,
|
|
114
|
+
fuel=fuel,
|
|
115
|
+
self_only=self_only,
|
|
116
|
+
served_only=served_only,
|
|
117
|
+
cheapest=cheapest,
|
|
118
|
+
min_price=min_price,
|
|
119
|
+
max_age_days=max_age_days,
|
|
120
|
+
max_deviation_pct=max_deviation_pct,
|
|
121
|
+
drop_outliers=drop_outliers,
|
|
122
|
+
limit=limit,
|
|
123
|
+
)
|
|
124
|
+
query = {
|
|
125
|
+
k: v
|
|
126
|
+
for k, v in {
|
|
127
|
+
"fuel": fuel,
|
|
128
|
+
"comune": comune_norm or None,
|
|
129
|
+
"provincia": provincia,
|
|
130
|
+
"brand": brand,
|
|
131
|
+
"near": near,
|
|
132
|
+
"radius_km": radius_km if near.strip() else None,
|
|
133
|
+
"self": self_only or None,
|
|
134
|
+
"served": served_only or None,
|
|
135
|
+
"cheapest": cheapest or None,
|
|
136
|
+
"min_price": min_price or None,
|
|
137
|
+
"fresh_within_days": max_age_days or None,
|
|
138
|
+
}.items()
|
|
139
|
+
if v not in ("", None, False)
|
|
140
|
+
}
|
|
141
|
+
return core.response_envelope(ds, stations, query)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
@mcp.tool(description=_FIND_CHEAPEST_DESC)
|
|
145
|
+
def find_cheapest(
|
|
146
|
+
fuel: str,
|
|
147
|
+
comune: str = "",
|
|
148
|
+
near: str = "",
|
|
149
|
+
radius_km: float = 10.0,
|
|
150
|
+
self_only: bool = False,
|
|
151
|
+
min_price: float = -1.0,
|
|
152
|
+
max_age_days: int = -1,
|
|
153
|
+
max_deviation_pct: float = 0.0,
|
|
154
|
+
drop_outliers: bool = True,
|
|
155
|
+
limit: int = 5,
|
|
156
|
+
) -> dict:
|
|
157
|
+
if min_price < 0:
|
|
158
|
+
min_price = core.default_floor(fuel)
|
|
159
|
+
if max_age_days < 0:
|
|
160
|
+
max_age_days = 90 # ignore stale records when ranking by price
|
|
161
|
+
ds = core.load()
|
|
162
|
+
comune_norm = geocoding.normalize_comune(comune)
|
|
163
|
+
stations = core.query_stations(
|
|
164
|
+
ds,
|
|
165
|
+
comune=comune_norm,
|
|
166
|
+
near=_parse_near(near),
|
|
167
|
+
radius_km=radius_km,
|
|
168
|
+
fuel=fuel,
|
|
169
|
+
self_only=self_only,
|
|
170
|
+
cheapest=True,
|
|
171
|
+
min_price=min_price,
|
|
172
|
+
max_age_days=max_age_days,
|
|
173
|
+
max_deviation_pct=max_deviation_pct,
|
|
174
|
+
drop_outliers=drop_outliers,
|
|
175
|
+
limit=limit,
|
|
176
|
+
)
|
|
177
|
+
query: dict = {
|
|
178
|
+
"fuel": fuel,
|
|
179
|
+
"cheapest": True,
|
|
180
|
+
"min_price": min_price,
|
|
181
|
+
"fresh_within_days": max_age_days,
|
|
182
|
+
"drop_outliers": drop_outliers,
|
|
183
|
+
}
|
|
184
|
+
if comune_norm:
|
|
185
|
+
query["comune"] = comune_norm
|
|
186
|
+
if near.strip():
|
|
187
|
+
query["near"] = near
|
|
188
|
+
query["radius_km"] = radius_km
|
|
189
|
+
if self_only:
|
|
190
|
+
query["self"] = True
|
|
191
|
+
return core.response_envelope(ds, stations, query)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
_FIND_CHARGERS_DESC = (
|
|
195
|
+
"Find EV charging stations near a coordinate or Italian comune, from "
|
|
196
|
+
"OpenStreetMap. Pass either `near` (\"lat,lon\") or `comune` (Italian "
|
|
197
|
+
"municipality name; resolved via the comune-coords reference). Filter by "
|
|
198
|
+
"operator substring, plug type (e.g. 'ccs', 'chademo', 'type2'), minimum "
|
|
199
|
+
"max-power kW, free-only, and public-access-only. Returns a JSON envelope "
|
|
200
|
+
"with operator, plug types, max kW, fee, access, distance, and (when the "
|
|
201
|
+
"operator is recognized) a `tariff_info_url` pointing to the operator's "
|
|
202
|
+
"official tariff page. **Per-station €/kWh tariffs are not in this dataset** "
|
|
203
|
+
"— as of mid-2026 they are not openly machine-readable in Italy (AFIR DATEX "
|
|
204
|
+
"II is upload-only; Chargeprice/Eco-Movement are paid). When a user asks "
|
|
205
|
+
"about price, surface the `tariff_info_url` for the relevant operator(s) "
|
|
206
|
+
"rather than guessing a price."
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
@mcp.tool(description=_FIND_CHARGERS_DESC)
|
|
211
|
+
def find_chargers(
|
|
212
|
+
near: str = "",
|
|
213
|
+
comune: str = "",
|
|
214
|
+
radius_km: float = 10.0,
|
|
215
|
+
operator: str = "",
|
|
216
|
+
socket: str = "",
|
|
217
|
+
min_power_kw: float = 0.0,
|
|
218
|
+
free_only: bool = False,
|
|
219
|
+
public_only: bool = False,
|
|
220
|
+
limit: int = 20,
|
|
221
|
+
) -> dict:
|
|
222
|
+
if not near.strip() and not comune.strip():
|
|
223
|
+
return ev_chargers.response_envelope([], {}, error="pass either near or comune")
|
|
224
|
+
if near.strip():
|
|
225
|
+
lat_s, lon_s = near.split(",")
|
|
226
|
+
lat, lon = float(lat_s.strip()), float(lon_s.strip())
|
|
227
|
+
else:
|
|
228
|
+
comune_norm = geocoding.normalize_comune(comune)
|
|
229
|
+
coords = geocoding.load_comune_coords()
|
|
230
|
+
match = coords.get(comune_norm)
|
|
231
|
+
if not match:
|
|
232
|
+
return ev_chargers.response_envelope(
|
|
233
|
+
[], {"comune": comune}, error=f"comune '{comune}' not found"
|
|
234
|
+
)
|
|
235
|
+
lat, lon = match
|
|
236
|
+
|
|
237
|
+
stations, error = ev_chargers.find_chargers(
|
|
238
|
+
near=(lat, lon), radius_km=radius_km, operator=operator, socket=socket,
|
|
239
|
+
min_power_kw=min_power_kw, free_only=free_only, public_only=public_only,
|
|
240
|
+
)
|
|
241
|
+
if limit > 0:
|
|
242
|
+
stations = stations[:limit]
|
|
243
|
+
query = {"near": f"{lat},{lon}", "radius_km": radius_km}
|
|
244
|
+
if comune:
|
|
245
|
+
query["comune"] = comune
|
|
246
|
+
if operator:
|
|
247
|
+
query["operator"] = operator
|
|
248
|
+
if socket:
|
|
249
|
+
query["socket"] = socket
|
|
250
|
+
if min_power_kw > 0:
|
|
251
|
+
query["min_power_kw"] = min_power_kw
|
|
252
|
+
if free_only:
|
|
253
|
+
query["free"] = True
|
|
254
|
+
if public_only:
|
|
255
|
+
query["public"] = True
|
|
256
|
+
return ev_chargers.response_envelope(stations, query, error=error)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def main() -> None:
|
|
260
|
+
mcp.run()
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
if __name__ == "__main__":
|
|
264
|
+
main()
|
pitstop/overpass.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Thin Overpass-API client with on-disk caching. Used by `chargers.py` to
|
|
2
|
+
fetch OpenStreetMap charging-station nodes. Standard library only.
|
|
3
|
+
|
|
4
|
+
OSM data is licensed ODbL — `pitstop` runtime-fetches only and attributes the
|
|
5
|
+
source in its output. No redistribution."""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
import time
|
|
14
|
+
import urllib.error
|
|
15
|
+
import urllib.request
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
OVERPASS_URL = "https://overpass-api.de/api/interpreter"
|
|
19
|
+
SOURCE_NAME = "OpenStreetMap (via Overpass API)"
|
|
20
|
+
SOURCE_URL = "https://www.openstreetmap.org/copyright"
|
|
21
|
+
|
|
22
|
+
DEFAULT_MAX_AGE = 7 * 24 * 60 * 60 # 7 days — charger metadata moves slowly
|
|
23
|
+
DEFAULT_TIMEOUT = 60
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _cache_dir() -> Path:
|
|
27
|
+
base = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
|
|
28
|
+
d = Path(base) / "pitstop" / "overpass"
|
|
29
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
30
|
+
return d
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _cache_key(query: str) -> str:
|
|
34
|
+
return hashlib.sha256(query.encode("utf-8")).hexdigest()[:24]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def fetch_elements(
|
|
38
|
+
query: str,
|
|
39
|
+
*,
|
|
40
|
+
refresh: bool = False,
|
|
41
|
+
max_age: int = DEFAULT_MAX_AGE,
|
|
42
|
+
timeout: int = DEFAULT_TIMEOUT,
|
|
43
|
+
) -> tuple[list[dict], str | None]:
|
|
44
|
+
"""Run an Overpass QL query and return (elements, error_msg).
|
|
45
|
+
|
|
46
|
+
error_msg is None on success, or a string describing the failure.
|
|
47
|
+
If a failure occurs but a stale cache exists, elements are returned
|
|
48
|
+
from cache and error_msg is still set."""
|
|
49
|
+
path = _cache_dir() / f"{_cache_key(query)}.json"
|
|
50
|
+
if not refresh and path.exists():
|
|
51
|
+
if max_age <= 0 or (time.time() - path.stat().st_mtime) < max_age:
|
|
52
|
+
return _read(path), None
|
|
53
|
+
|
|
54
|
+
req = urllib.request.Request(
|
|
55
|
+
OVERPASS_URL,
|
|
56
|
+
data=query.encode("utf-8"),
|
|
57
|
+
headers={"User-Agent": "pitstop/0.7 (https://github.com/galjos/pitstop)"},
|
|
58
|
+
method="POST",
|
|
59
|
+
)
|
|
60
|
+
error = None
|
|
61
|
+
try:
|
|
62
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
63
|
+
data = resp.read()
|
|
64
|
+
except (urllib.error.URLError, OSError) as e:
|
|
65
|
+
error = str(e)
|
|
66
|
+
print(f"pitstop: Overpass fetch failed ({error}); "
|
|
67
|
+
f"{'using stale cache' if path.exists() else 'no data available'}",
|
|
68
|
+
file=sys.stderr)
|
|
69
|
+
return (_read(path) if path.exists() else []), error
|
|
70
|
+
|
|
71
|
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
|
72
|
+
tmp.write_bytes(data)
|
|
73
|
+
tmp.replace(path)
|
|
74
|
+
return _read(path), None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _read(path: Path) -> list[dict]:
|
|
78
|
+
try:
|
|
79
|
+
with path.open("r", encoding="utf-8") as f:
|
|
80
|
+
data = json.load(f)
|
|
81
|
+
return data.get("elements", []) if isinstance(data, dict) else []
|
|
82
|
+
except (json.JSONDecodeError, OSError):
|
|
83
|
+
return []
|
pitstop/version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.0.0"
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pitstop-cli
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: JSON-first CLI + MCP server for Italian fuel-station prices and EV charging — MIMIT, OpenStreetMap, ISTAT.
|
|
5
|
+
Project-URL: Homepage, https://github.com/galjos/pitstop
|
|
6
|
+
Project-URL: Repository, https://github.com/galjos/pitstop
|
|
7
|
+
Project-URL: Changelog, https://github.com/galjos/pitstop/blob/main/CHANGELOG.md
|
|
8
|
+
Project-URL: Issues, https://github.com/galjos/pitstop/issues
|
|
9
|
+
Author: Josef M. Gallmetzer
|
|
10
|
+
License: MIT License
|
|
11
|
+
|
|
12
|
+
Copyright (c) 2026 Josef M. Gallmetzer
|
|
13
|
+
|
|
14
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
15
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
16
|
+
in the Software without restriction, including without limitation the rights
|
|
17
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
18
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
19
|
+
furnished to do so, subject to the following conditions:
|
|
20
|
+
|
|
21
|
+
The above copyright notice and this permission notice shall be included in all
|
|
22
|
+
copies or substantial portions of the Software.
|
|
23
|
+
|
|
24
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
25
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
26
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
27
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
28
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
29
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
30
|
+
SOFTWARE.
|
|
31
|
+
License-File: LICENSE
|
|
32
|
+
Keywords: agent,carburanti,charging,cli,ev,fuel,italy,llm,mcp,mimit,openstreetmap,prices
|
|
33
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
34
|
+
Classifier: Environment :: Console
|
|
35
|
+
Classifier: Intended Audience :: Developers
|
|
36
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
37
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
38
|
+
Classifier: Operating System :: OS Independent
|
|
39
|
+
Classifier: Programming Language :: Python :: 3
|
|
40
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
41
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
42
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
43
|
+
Classifier: Topic :: Scientific/Engineering :: GIS
|
|
44
|
+
Classifier: Topic :: Utilities
|
|
45
|
+
Requires-Python: >=3.10
|
|
46
|
+
Provides-Extra: dev
|
|
47
|
+
Requires-Dist: pytest>=7; extra == 'dev'
|
|
48
|
+
Provides-Extra: mcp
|
|
49
|
+
Requires-Dist: mcp>=1.0; extra == 'mcp'
|
|
50
|
+
Description-Content-Type: text/markdown
|
|
51
|
+
|
|
52
|
+
# pitstop
|
|
53
|
+
|
|
54
|
+
A JSON-first CLI and MCP server for **Italian fuel-station prices** and **EV charging stations**, designed for AI agents, scripts, and humans.
|
|
55
|
+
|
|
56
|
+
Italy publishes per-station fuel prices daily (MIMIT *Osservaprezzi Carburanti* open data) and OpenStreetMap maps every EV charger in the country, but raw access means downloading multi-megabyte CSVs, joining files, sorting through misreports, and translating between Italian comune names and the ones a user actually types. `pitstop` does all of that locally and returns a small, well-formed JSON envelope.
|
|
57
|
+
|
|
58
|
+
Built for questions like:
|
|
59
|
+
- *"What's the cheapest diesel near Rome right now?"* → `pitstop find_cheapest --fuel Gasolio --near 41.9,12.5`
|
|
60
|
+
- *"Where can I fast-charge my EV in Bolzano?"* → `pitstop chargers --comune Bozen --fast`
|
|
61
|
+
- *"Are these station prices statistically reliable?"* → every price carries a `regional_median`, `deviation_pct`, and `outlier` flag.
|
|
62
|
+
|
|
63
|
+
International city names work out of the box (`Rome`, `Milan`, `Bozen`, `Mailand`, `Venise`, …).
|
|
64
|
+
|
|
65
|
+
## Disclaimer
|
|
66
|
+
|
|
67
|
+
Unofficial community project. Not affiliated with or endorsed by MIMIT. Fuel data belongs to MIMIT and is redistributed here under its open-data terms; `pitstop` always emits source and extraction-date provenance in its output.
|
|
68
|
+
|
|
69
|
+
## Data scope & freshness
|
|
70
|
+
|
|
71
|
+
- **Source:** MIMIT _Osservaprezzi Carburanti_ open data — a station registry (`anagrafica`, ~23.8k active stations) and a daily practiced-price file, joined on `idImpianto`.
|
|
72
|
+
- **Freshness:** prices reflect values reported by operators **as of ~08:00 the day before** the published extraction date. This is **daily, not real-time.**
|
|
73
|
+
- **Coverage:** Italy only (by design, for now).
|
|
74
|
+
- **Known caveats:**
|
|
75
|
+
- Some operators report placeholder values (e.g. `1.000`); use `--min-price` (e.g. `1.2`) to drop them.
|
|
76
|
+
- Some price records are **stale** (a few were last updated years ago); use `--fresh-within-days` and check the `UPDATED` column / `updated` field.
|
|
77
|
+
- Some stations are **mis-geocoded** in the registry. As of v0.4.0 `pitstop` joins a second data source (ISTAT-derived comune coordinates from [opendatasicilia/comuni-italiani](https://github.com/opendatasicilia/comuni-italiani), 97.5% match) to validate each station's coordinate against its declared comune's *true* location. Stations >30 km off are flagged `coordinate_suspect` (`*` in the table), and `--near` excludes stations whose declared comune is geographically too far from the query point — even single-station comuni like RASUN-ANTERSELVA. Pass `--no-comune-validate` to disable.
|
|
78
|
+
|
|
79
|
+
## Install
|
|
80
|
+
|
|
81
|
+
Requires Python ≥ 3.10. No third-party runtime dependencies.
|
|
82
|
+
|
|
83
|
+
From PyPI (the package is published as **`pitstop-cli`**; the CLI binary is `pitstop`):
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
pipx install pitstop-cli # or
|
|
87
|
+
uv tool install pitstop-cli # or just run on-demand:
|
|
88
|
+
uvx --from pitstop-cli pitstop --help
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
For the MCP server (optional extra):
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
pipx install "pitstop-cli[mcp]"
|
|
95
|
+
pitstop-mcp # stdio MCP server
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Run from a source checkout during development:
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
PYTHONPATH=src python3 -m pitstop --help
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Usage
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
# Cheapest *fresh* diesel in a municipality (skip placeholder + stale prices)
|
|
108
|
+
pitstop stations --comune ROMA --fuel Gasolio --cheapest --min-price 1.2 --fresh-within-days 90 --limit 5
|
|
109
|
+
|
|
110
|
+
# Self-service petrol within 5 km of a coordinate, as JSON
|
|
111
|
+
pitstop stations --near 46.498,11.354 --radius 5 --fuel Benzina --self --json
|
|
112
|
+
|
|
113
|
+
# Discover the fuel-type names present in the data
|
|
114
|
+
pitstop fuels
|
|
115
|
+
|
|
116
|
+
# Fast EV chargers (≥50 kW) within 5 km of Bolzano
|
|
117
|
+
pitstop chargers --near 46.498,11.354 --radius 5 --fast --json
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
`stations` flags: `--comune`, `--provincia`, `--brand`, `--near "lat,lon"`, `--radius`, `--fuel` (substring, case-insensitive), `--self`, `--served`, `--cheapest` (needs `--fuel`), `--min-price` (drop values below a floor; e.g. `1.2` to skip placeholders), `--fresh-within-days` (drop stale prices), `--max-deviation-pct` (drop prices more than N% below their fuel's provincial median — catches misreports), `--no-comune-validate`, `--limit`, `--json`. Loading flags (`--refresh`, `--max-age`, `--timeout`) apply to any data command.
|
|
121
|
+
|
|
122
|
+
Every returned price carries `regional_median`, `deviation_pct`, and an `outlier` flag (true when >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). Pass `--drop-outliers` to remove flagged prices entirely.
|
|
123
|
+
|
|
124
|
+
## MCP server
|
|
125
|
+
|
|
126
|
+
For agents that speak MCP, the same data is exposed as tools (`list_fuels`, `find_stations`, `find_cheapest`) over the shared core:
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
pip install "pitstop-cli[mcp]" # or: uv tool install "pitstop-cli[mcp]"
|
|
130
|
+
pitstop-mcp # stdio MCP server
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Example client config entry:
|
|
134
|
+
|
|
135
|
+
```json
|
|
136
|
+
{ "mcpServers": { "pitstop": { "command": "pitstop-mcp" } } }
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## Development
|
|
140
|
+
|
|
141
|
+
```bash
|
|
142
|
+
pip install -e ".[dev]"
|
|
143
|
+
pytest -q
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
## Automation contract
|
|
147
|
+
|
|
148
|
+
- `stdout` is command output; `stderr` is diagnostics.
|
|
149
|
+
- `--json` emits a stable object with `source`, `*_extraction_date`, `generated_at`, `query`, `count`, `stations[]`, and `disclaimer`.
|
|
150
|
+
- Exit codes: `0` success, `1` runtime error, `2` usage error.
|
|
151
|
+
- Source files are cached (default 24h) under `$XDG_CACHE_HOME/pitstop`; use `--refresh` to bypass.
|
|
152
|
+
- Non-interactive; no hidden browser state or scraping.
|
|
153
|
+
|
|
154
|
+
## Status & roadmap
|
|
155
|
+
|
|
156
|
+
v0.9.0 — fuel-price core (registry+price join, filters, proximity, cheapest, `--min-price` floor, `--fresh-within-days` freshness, combined 15% + Tukey IQR outlier rule, ISTAT comune-coordinate validation, JSON) + **EV charging stations via OSM Overpass** (operator, plug types, max kW, fee, access — `pitstop chargers`) + **operator tariff-page URLs** attached to each EV result. Includes **multi-fuel query support**, **international municipality mapping** (EN/FR/DE), **macro price statistics** (`pitstop stats`), and **navigation/GeoJSON support**. MCP server, Claude skill, tests, CI.
|
|
157
|
+
|
|
158
|
+
Planned, roughly in order:
|
|
159
|
+
- **EV charging** (locations via Open Charge Map; prices via the AFIR National Access Point / DATEX II as that data matures);
|
|
160
|
+
- additional countries behind a per-country source adapter (e.g. Germany Tankerkönig, France/Spain official feeds).
|
|
161
|
+
|
|
162
|
+
## Data sources & attributions
|
|
163
|
+
|
|
164
|
+
- Fuel stations and prices: **MIMIT Osservaprezzi Carburanti** open data.
|
|
165
|
+
- Comune coordinates (validation): **opendatasicilia/comuni-italiani** (ISTAT-derived).
|
|
166
|
+
- EV charging stations: **OpenStreetMap** via the Overpass API (© OpenStreetMap contributors, ODbL).
|
|
167
|
+
|
|
168
|
+
## Links
|
|
169
|
+
|
|
170
|
+
- MIMIT fuel open data: https://www.mimit.gov.it/it/open-data/elenco-dataset/carburanti-prezzi-praticati-e-anagrafica-degli-impianti
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
pitstop/__init__.py,sha256=v3x5oBkxwKJEZLv62QqSmP3iqNKLtZgrWZfH8eFzlQg,60
|
|
2
|
+
pitstop/__main__.py,sha256=MHKZ_ae3fSLGTLUUMOx15fWdeOnJSHhq-zslRP5F5Lc,79
|
|
3
|
+
pitstop/chargers.py,sha256=LHHmw7n3Hm_riIqDB_3MVFrZarQH56j-Kwdn6UE_Z3M,9814
|
|
4
|
+
pitstop/cli.py,sha256=1w-uVo_3oJfPXy4XoeQpxfZQs8g0kUJnTd9AVwSwuQ0,16517
|
|
5
|
+
pitstop/core.py,sha256=f4_1-LtfbfgRm0qzU2AAPdt-JrBIAPZTOAs3MY-vDA0,20024
|
|
6
|
+
pitstop/cpo_tariffs.py,sha256=oqyJ3r2X2ghhrFn0lGM3mAvyjjvYnYvOT18dFpNjevA,3098
|
|
7
|
+
pitstop/geocoding.py,sha256=_rmULt6Vw0IDzza-o7ghqlxyQZqn7OihTzvRhv-VLlE,5032
|
|
8
|
+
pitstop/mcp_server.py,sha256=wtHDSCnJ_wF3DkCnomgn4GuHFV-cwhQaqhUIRZ-EFh8,9204
|
|
9
|
+
pitstop/overpass.py,sha256=ifzsynjnVnl0KWAifoB1CQ_ehPjGy10CACGfDe8wCEU,2668
|
|
10
|
+
pitstop/version.py,sha256=J-j-u0itpEFT6irdmWmixQqYMadNl1X91TxUmoiLHMI,22
|
|
11
|
+
pitstop_cli-1.0.0.dist-info/METADATA,sha256=4Pl8AbzXIddEXhbg8QdqQuePRAISM9edxixXsLY-eBk,9296
|
|
12
|
+
pitstop_cli-1.0.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
|
|
13
|
+
pitstop_cli-1.0.0.dist-info/entry_points.txt,sha256=Shqp8uZTJXKbzyrj_Tqxd8pVgMJjo0bagYqPB0C600A,83
|
|
14
|
+
pitstop_cli-1.0.0.dist-info/licenses/LICENSE,sha256=CZjMue1Q94aVjY3owCgYOzbHVbGNlQxFO2hUW-m8_Pw,1076
|
|
15
|
+
pitstop_cli-1.0.0.dist-info/RECORD,,
|