flixtrain-mcp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,20 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ push:
5
+ tags: ["v*"]
6
+
7
+ jobs:
8
+ publish:
9
+ runs-on: ubuntu-latest
10
+ permissions:
11
+ id-token: write # required for PyPI trusted publishing (OIDC)
12
+ contents: read
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: actions/setup-python@v5
16
+ with:
17
+ python-version: "3.12"
18
+ - run: pip install build
19
+ - run: python -m build
20
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,61 @@
1
+ name: Publish to MCP Registry
2
+
3
+ # Official MCP Registry (registry.modelcontextprotocol.io) via GitHub OIDC.
4
+ # No secret, no interactive login: the runner's OIDC token proves ownership
5
+ # of the io.github.mohammad-abbasi-sh/* namespace.
6
+ # Refs: https://github.com/modelcontextprotocol/registry
7
+
8
+ on:
9
+ push:
10
+ tags: ["v*"]
11
+ workflow_dispatch:
12
+
13
+ jobs:
14
+ publish:
15
+ runs-on: ubuntu-latest
16
+ permissions:
17
+ id-token: write # required for OIDC -> MCP Registry
18
+ contents: read
19
+ steps:
20
+ - uses: actions/checkout@v4
21
+
22
+ - name: Sync server.json version to tag
23
+ # Only sync when running on a version tag (v*). On workflow_dispatch
24
+ # (ref = refs/heads/main) keep the version committed in server.json.
25
+ run: |
26
+ VER=""
27
+ if [[ "$GITHUB_REF" == refs/tags/* ]]; then
28
+ TAG="${GITHUB_REF#refs/tags/}"
29
+ VER="${TAG#v}"
30
+ fi
31
+ if [ -n "$VER" ]; then
32
+ python3 - "$VER" << 'EOF'
33
+ import json, sys
34
+ ver = sys.argv[1]
35
+ d = json.load(open('server.json'))
36
+ d['version'] = ver
37
+ for pkg in d.get('packages', []):
38
+ pkg['version'] = ver
39
+ json.dump(d, open('server.json', 'w'), indent=2, ensure_ascii=False)
40
+ print('server.json version ->', ver)
41
+ EOF
42
+ else
43
+ echo "No version tag ($GITHUB_REF); keeping server.json version as-is"
44
+ fi
45
+
46
+ - name: Install mcp-publisher
47
+ run: |
48
+ curl -sL "https://github.com/modelcontextprotocol/registry/releases/download/v1.8.7/mcp-publisher_linux_amd64.tar.gz" -o /tmp/mcp-publisher.tar.gz
49
+ tar -xzf /tmp/mcp-publisher.tar.gz -C /tmp
50
+ sudo mv /tmp/mcp-publisher /usr/local/bin/mcp-publisher
51
+ mcp-publisher --version
52
+
53
+ - name: Validate server.json
54
+ run: mcp-publisher validate server.json
55
+
56
+ - name: Publish to MCP Registry (OIDC)
57
+ run: |
58
+ mcp-publisher login github-oidc
59
+ mcp-publisher publish server.json
60
+ # A registry outage must never break the release; re-run from Actions if needed.
61
+ continue-on-error: true
@@ -0,0 +1,21 @@
1
+ name: Daily live smoke
2
+
3
+ # One fixed probe per day: catches fingerprint rot / bot-wall changes
4
+ # before users hit them. Fails visibly on 403/timeout.
5
+ on:
6
+ schedule:
7
+ - cron: "0 6 * * *"
8
+ workflow_dispatch:
9
+
10
+ jobs:
11
+ smoke:
12
+ runs-on: ubuntu-latest
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: actions/setup-python@v5
16
+ with:
17
+ python-version: "3.12"
18
+ - name: Install
19
+ run: pip install -e .
20
+ - name: Smoke probe
21
+ run: python tests/smoke_live.py
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohammad Abbasi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,60 @@
1
+ Metadata-Version: 2.5
2
+ Name: flixtrain-mcp
3
+ Version: 0.1.0
4
+ Summary: Unofficial read-only MCP server for FlixTrain — train times, stations & prices
5
+ Author: Mohammad Abbasi
6
+ License: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: httpx>=0.27
10
+ Requires-Dist: mcp<2
11
+ Description-Content-Type: text/markdown
12
+
13
+ # flixtrain-mcp 🚆
14
+
15
+ mcp-name: io.github.mohammad-abbasi-sh/flixtrain-mcp
16
+
17
+ Unofficial **read-only** MCP server for **[global.api.flixbus.com (FlixBus shop search API)](https://shop.flixbus.com)** — FlixTrain times & prices from the FlixBus shop search API (free, no key, no login): train-only departures between German cities, with stations, duration, price and seat availability. No key, no login.
18
+
19
+ > Built by Mohammad Abbasi as part of the "Germany MCP factory". Not affiliated with global.api.flixbus.com (FlixBus shop search API).
20
+
21
+ ## For AI agents
22
+
23
+ Add to your MCP client config (stdio):
24
+
25
+ ```json
26
+ {
27
+ "mcpServers": {
28
+ "flixtrain": {
29
+ "command": "uvx",
30
+ "args": ["flixtrain-mcp==0.1.0"]
31
+ }
32
+ }
33
+ }
34
+ ```
35
+
36
+ Or run locally: `python -m flixtrain_mcp.server` (needs `mcp<2`, `httpx`).
37
+
38
+ ## Tools
39
+
40
+ | Tool | Description |
41
+ |------|-------------|
42
+ | `flixtrain_search_trains` | Search FlixTrain-only departures between two cities on a date: times, stations, duration, price & seats — `from_city`, `to_city`, `date` (DD.MM.YYYY), `limit` 1..20, `sort` (departure/price) |
43
+ | `flixtrain_search_cities` | Find cities (with train stations) by name for the train search — `query`, `limit` 1..10 |
44
+ | `flixtrain_health` | Reachability probe (ok / blocked / error) — one polite request |
45
+
46
+ ## Development
47
+
48
+ ```bash
49
+ python3 -m venv .venv && .venv/bin/pip install "mcp<2" httpx pytest
50
+ .venv/bin/pip install -e .
51
+ .venv/bin/python -m pytest tests/ -q
52
+ ```
53
+
54
+ ## License
55
+
56
+ MIT
57
+
58
+ ---
59
+
60
+ Built by [Mohammad Abbasi](https://github.com/mohammad-abbasi-sh) — [Almanibama](https://almanibama.ir) · [mabbasi.ir](https://mabbasi.ir)
@@ -0,0 +1,48 @@
1
+ # flixtrain-mcp 🚆
2
+
3
+ mcp-name: io.github.mohammad-abbasi-sh/flixtrain-mcp
4
+
5
+ Inoffizieller **nur lesender** MCP-Server für **[global.api.flixbus.com (FlixBus shop search API)](https://shop.flixbus.com)** — FlixTrain-Zeiten & Preise über die FlixBus-Shop-Suche (kostenlos, kein Schlüssel, kein Login): nur Zugverbindungen zwischen deutschen Städten, mit Bahnhöfen, Fahrzeit, Preis und Sitzplatzverfügbarkeit. Kein Schlüssel, keine Anmeldung.
6
+
7
+ > Gebaut von Mohammad Abbasi als Teil der "Germany MCP factory". Nicht mit global.api.flixbus.com (FlixBus shop search API) verbunden.
8
+
9
+ ## Für KI-Agenten
10
+
11
+ Zur MCP-Client-Konfiguration hinzufügen (stdio):
12
+
13
+ ```json
14
+ {
15
+ "mcpServers": {
16
+ "flixtrain": {
17
+ "command": "uvx",
18
+ "args": ["flixtrain-mcp==0.1.0"]
19
+ }
20
+ }
21
+ }
22
+ ```
23
+
24
+ Oder lokal starten: `python -m flixtrain_mcp.server` (benötigt `mcp<2`, `httpx`).
25
+
26
+ ## Tools
27
+
28
+ | Tool | Beschreibung |
29
+ |------|-------------|
30
+ | `flixtrain_search_trains` | FlixTrain-Verbindungen zwischen zwei Städten suchen |
31
+ | `flixtrain_search_cities` | Städte nach Namen finden |
32
+ | `flixtrain_health` | Erreichbarkeitsprüfung (ok / blocked / error) — eine höfliche Anfrage |
33
+
34
+ ## Entwicklung
35
+
36
+ ```bash
37
+ python3 -m venv .venv && .venv/bin/pip install "mcp<2" httpx pytest
38
+ .venv/bin/pip install -e .
39
+ .venv/bin/python -m pytest tests/ -q
40
+ ```
41
+
42
+ ## Lizenz
43
+
44
+ MIT
45
+
46
+ ---
47
+
48
+ Built by [Mohammad Abbasi](https://github.com/mohammad-abbasi-sh) — [Almanibama](https://almanibama.ir) · [mabbasi.ir](https://mabbasi.ir)
@@ -0,0 +1,48 @@
1
+ # flixtrain-mcp 🚆
2
+
3
+ mcp-name: io.github.mohammad-abbasi-sh/flixtrain-mcp
4
+
5
+ سرور MCP غیررسمی و **فقط‌خواندنی** برای **[global.api.flixbus.com (FlixBus shop search API)](https://shop.flixbus.com)** — زمان‌بندی و قیمت فلیکس‌ترین از API جست‌وجوی فروشگاه فلیکس‌بوس (رایگان، بدون کلید): فقط سفرهای قطار بین شهرهای آلمان، با ایستگاه‌ها، مدت سفر، قیمت و صندلی‌های موجود. بدون کلید، بدون ورود.
6
+
7
+ > ساختهٔ محمد عباسی، بخشی از «کارخانهٔ MCP آلمان». وابسته به global.api.flixbus.com (FlixBus shop search API) نیست.
8
+
9
+ ## برای ایجنت‌های هوش مصنوعی
10
+
11
+ به پیکربندی MCP کلاینت اضافه کنید (stdio):
12
+
13
+ ```json
14
+ {
15
+ "mcpServers": {
16
+ "flixtrain": {
17
+ "command": "uvx",
18
+ "args": ["flixtrain-mcp==0.1.0"]
19
+ }
20
+ }
21
+ }
22
+ ```
23
+
24
+ یا به‌صورت محلی اجرا کنید: `python -m flixtrain_mcp.server` (نیازمند `mcp<2` و `httpx`).
25
+
26
+ ## ابزارها
27
+
28
+ | ابزار | توضیح |
29
+ |------|-------|
30
+ | `flixtrain_search_trains` | جست‌وجوی سفرهای فلیکس‌ترین بین دو شهر |
31
+ | `flixtrain_search_cities` | یافتن شهرها بر اساس نام |
32
+ | `flixtrain_health` | بررسی دسترس‌پذیری (ok / blocked / error) — یک درخواست مؤدبانه |
33
+
34
+ ## توسعه
35
+
36
+ ```bash
37
+ python3 -m venv .venv && .venv/bin/pip install "mcp<2" httpx pytest
38
+ .venv/bin/pip install -e .
39
+ .venv/bin/python -m pytest tests/ -q
40
+ ```
41
+
42
+ ## لایسنس
43
+
44
+ MIT
45
+
46
+ ---
47
+
48
+ Built by [Mohammad Abbasi](https://github.com/mohammad-abbasi-sh) — [Almanibama](https://almanibama.ir) · [mabbasi.ir](https://mabbasi.ir)
@@ -0,0 +1,48 @@
1
+ # flixtrain-mcp 🚆
2
+
3
+ mcp-name: io.github.mohammad-abbasi-sh/flixtrain-mcp
4
+
5
+ Unofficial **read-only** MCP server for **[global.api.flixbus.com (FlixBus shop search API)](https://shop.flixbus.com)** — FlixTrain times & prices from the FlixBus shop search API (free, no key, no login): train-only departures between German cities, with stations, duration, price and seat availability. No key, no login.
6
+
7
+ > Built by Mohammad Abbasi as part of the "Germany MCP factory". Not affiliated with global.api.flixbus.com (FlixBus shop search API).
8
+
9
+ ## For AI agents
10
+
11
+ Add to your MCP client config (stdio):
12
+
13
+ ```json
14
+ {
15
+ "mcpServers": {
16
+ "flixtrain": {
17
+ "command": "uvx",
18
+ "args": ["flixtrain-mcp==0.1.0"]
19
+ }
20
+ }
21
+ }
22
+ ```
23
+
24
+ Or run locally: `python -m flixtrain_mcp.server` (needs `mcp<2`, `httpx`).
25
+
26
+ ## Tools
27
+
28
+ | Tool | Description |
29
+ |------|-------------|
30
+ | `flixtrain_search_trains` | Search FlixTrain-only departures between two cities on a date: times, stations, duration, price & seats — `from_city`, `to_city`, `date` (DD.MM.YYYY), `limit` 1..20, `sort` (departure/price) |
31
+ | `flixtrain_search_cities` | Find cities (with train stations) by name for the train search — `query`, `limit` 1..10 |
32
+ | `flixtrain_health` | Reachability probe (ok / blocked / error) — one polite request |
33
+
34
+ ## Development
35
+
36
+ ```bash
37
+ python3 -m venv .venv && .venv/bin/pip install "mcp<2" httpx pytest
38
+ .venv/bin/pip install -e .
39
+ .venv/bin/python -m pytest tests/ -q
40
+ ```
41
+
42
+ ## License
43
+
44
+ MIT
45
+
46
+ ---
47
+
48
+ Built by [Mohammad Abbasi](https://github.com/mohammad-abbasi-sh) — [Almanibama](https://almanibama.ir) · [mabbasi.ir](https://mabbasi.ir)
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "flixtrain-mcp"
7
+ version = "0.1.0"
8
+ description = "Unofficial read-only MCP server for FlixTrain — train times, stations & prices"
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.10"
12
+ dependencies = [
13
+ "mcp<2",
14
+ "httpx>=0.27",
15
+ ]
16
+ authors = [{ name = "Mohammad Abbasi" }]
17
+
18
+ [project.scripts]
19
+ flixtrain-mcp = "flixtrain_mcp.server:main"
20
+
21
+ [tool.hatch.build.targets.wheel]
22
+ packages = ["src/flixtrain_mcp"]
23
+
24
+ [tool.pytest.ini_options]
25
+ markers = ["live: tests that hit the real https://shop.flixbus.com site"]
@@ -0,0 +1 @@
1
+ {"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", "description": "Unofficial read-only MCP server for FlixTrain — train times, stations & prices.", "name": "io.github.mohammad-abbasi-sh/flixtrain-mcp", "packages": [{"identifier": "flixtrain-mcp", "registryBaseUrl": "https://pypi.org", "registryType": "pypi", "transport": {"type": "stdio"}, "version": "0.1.0"}], "repository": {"source": "github", "url": "https://github.com/mohammad-abbasi-sh/flixtrain-mcp"}, "title": "FlixTrain — train times, stations & prices between German cities", "version": "0.1.0", "websiteUrl": "https://github.com/mohammad-abbasi-sh/flixtrain-mcp"}
@@ -0,0 +1,7 @@
1
+ """flixtrain_mcp — unofficial read-only MCP server for global.api.flixbus.com (FlixBus shop search API).
2
+
3
+ FlixTrain times & prices from the FlixBus shop search API (free, no key, no login): train-only departures between German cities, with stations, duration, price and seat availability.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ __version__ = "0.1.0"
@@ -0,0 +1,188 @@
1
+ """Domain logic: shape the FlixBus shop search API (used by
2
+ flixtrain.de, which redirects to flixbus.com) into compact dicts
3
+ (stdlib only).
4
+
5
+ Data source: https://global.api.flixbus.com/search — the same JSON
6
+ API the FlixBus shop uses. Free, no key, no login, but the gateway
7
+ requires `Referer: https://shop.flixbus.com/` (without it: 403
8
+ "Missing Authentication Token").
9
+
10
+ Endpoints (verified 2026-11-10):
11
+ - GET /search/autocomplete/cities?q=<name>&locale=de — city
12
+ candidates [{id (UUID), name, country, has_train_station, lat/lon,
13
+ legacy_id}]. Note: names are the canonical (English) form — Köln
14
+ comes back as "Cologne" even with locale=de; matching happens
15
+ server-side on the query, so resolving by top hit works.
16
+ - GET /search/service/v4/search?from_city_id=<uuid>&to_city_id=<uuid>
17
+ &departure_date=DD.MM.YYYY&products={"adult":1}&currency=EUR
18
+ &locale=de&search_by=cities&include_after_midnight=false —
19
+ {trips: [{date, results: {uid: {...}}}], operators, brands,
20
+ cities, stations}. Each result has legs[] with
21
+ means_of_transport (bus/train), operator_id ("train" = FlixTrain
22
+ GmbH), departure/arrival (date, city_id, station_id), duration,
23
+ price {total, total_with_platform_fee}, available {seats},
24
+ amenities, transfer_type ("Zug" for trains). Station/city names
25
+ come from the response's stations/cities maps.
26
+ - Only train legs are exposed (the server is FlixTrain, not
27
+ FlixBus); the bus count is reported for context.
28
+ - The v2/trip/details endpoint was probed and does not accept the
29
+ documented uid params (400 "Must provide trip uid") — not used;
30
+ the v4 search already carries times, stations, price and seats.
31
+ - The search does not do round trips (return_date is ignored).
32
+ """
33
+ from __future__ import annotations
34
+
35
+ import json
36
+ import re
37
+ from datetime import datetime
38
+
39
+ API_BASE = "https://global.api.flixbus.com/search"
40
+ FLIXTRAIN_BRAND_ID = "adf3cadd-7991-436c-be53-eb0f9c5ac165"
41
+
42
+ _CITY_ID_RE = re.compile(
43
+ r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
44
+
45
+
46
+ def validate_query(query: str) -> str:
47
+ q = (query or "").strip()
48
+ if not q:
49
+ raise ValueError("query must not be empty")
50
+ if len(q) > 100:
51
+ raise ValueError("query too long (max 100 characters)")
52
+ return q
53
+
54
+
55
+ def validate_limit(limit: int, maximum: int = 20) -> int:
56
+ if not 1 <= limit <= maximum:
57
+ raise ValueError(
58
+ f"limit out of range: {limit} (expected 1..{maximum})")
59
+ return limit
60
+
61
+
62
+ def validate_date(date: str) -> str:
63
+ """DD.MM.YYYY (the API's format); must be a real calendar date
64
+ and not in the past."""
65
+ d = (date or "").strip()
66
+ try:
67
+ parsed = datetime.strptime(d, "%d.%m.%Y").date()
68
+ except ValueError:
69
+ raise ValueError(
70
+ f"invalid date {date!r} (expected DD.MM.YYYY, e.g. 11.11.2026)"
71
+ ) from None
72
+ if parsed < datetime.now().date():
73
+ raise ValueError(f"date {d} is in the past")
74
+ return d
75
+
76
+
77
+ def validate_sort(sort: str) -> str:
78
+ s = (sort or "departure").strip().lower()
79
+ if s not in ("departure", "price"):
80
+ raise ValueError(
81
+ f"unsupported sort: {sort!r} (use departure or price)")
82
+ return s
83
+
84
+
85
+ def autocomplete_url(query: str) -> str:
86
+ return f"{API_BASE}/autocomplete/cities?q={query}&locale=de"
87
+
88
+
89
+ def search_url(from_id: str, to_id: str, date: str) -> str:
90
+ return (
91
+ f"{API_BASE}/service/v4/search?from_city_id={from_id}"
92
+ f"&to_city_id={to_id}&departure_date={date}"
93
+ "&products=%7B%22adult%22%3A1%7D&currency=EUR&locale=de"
94
+ "&search_by=cities&include_after_midnight=false"
95
+ )
96
+
97
+
98
+ def parse_cities(payload) -> list[dict]:
99
+ """[{id, name, country, has_train_station, lat, lon}] — top
100
+ first (the API's own relevance ranking)."""
101
+ if isinstance(payload, str):
102
+ payload = json.loads(payload)
103
+ if not isinstance(payload, list):
104
+ raise ValueError("unexpected autocomplete response (not a list)")
105
+ out = []
106
+ for c in payload:
107
+ loc = c.get("location") or {}
108
+ out.append({
109
+ "id": c.get("id", ""),
110
+ "name": c.get("name", ""),
111
+ "country": c.get("country", ""),
112
+ "has_train_station": bool(c.get("has_train_station")),
113
+ "lat": loc.get("lat"),
114
+ "lon": loc.get("lon"),
115
+ })
116
+ return out
117
+
118
+
119
+ def resolve_city(cities: list[dict], query: str) -> dict:
120
+ """Top autocomplete hit (prefer one with a train station when
121
+ the top hit has none and a later hit has one — the train search
122
+ needs a station)."""
123
+ if not cities:
124
+ raise ValueError(
125
+ f"no city found for {query!r} "
126
+ "(try a different spelling, e.g. Cologne for Köln)")
127
+ top = cities[0]
128
+ if top["has_train_station"]:
129
+ return top
130
+ for c in cities[1:]:
131
+ if c["has_train_station"] and c["name"].casefold() == top["name"].casefold():
132
+ return c
133
+ return top
134
+
135
+
136
+ def parse_search(payload) -> dict:
137
+ """{trains: [{departure, departure_station, arrival,
138
+ arrival_station, duration_minutes, price_eur,
139
+ price_incl_fee_eur, seats_available, amenities, operator}],
140
+ bus_count, train_count, from_city, to_city} — trains only,
141
+ sorted by departure time."""
142
+ if isinstance(payload, str):
143
+ payload = json.loads(payload)
144
+ if not isinstance(payload, dict) or "trips" not in payload:
145
+ raise ValueError("unexpected search response (no trips)")
146
+ stations = payload.get("stations") or {}
147
+ cities = payload.get("cities") or {}
148
+ trains: list[dict] = []
149
+ bus_count = 0
150
+ from_city = to_city = ""
151
+ for group in payload["trips"]:
152
+ from_city = (cities.get(group.get("departure_city_id", "")) or {}).get("name", "")
153
+ to_city = (cities.get(group.get("arrival_city_id", "")) or {}).get("name", "")
154
+ for _uid, r in (group.get("results") or {}).items():
155
+ legs = r.get("legs") or []
156
+ if not legs:
157
+ continue
158
+ if legs[0].get("means_of_transport") != "train":
159
+ bus_count += 1
160
+ continue
161
+ dep = r.get("departure") or {}
162
+ arr = r.get("arrival") or {}
163
+ dep_station = stations.get(dep.get("station_id", "")) or {}
164
+ arr_station = stations.get(arr.get("station_id", "")) or {}
165
+ dur = r.get("duration") or {}
166
+ price = r.get("price") or {}
167
+ avail = r.get("available") or {}
168
+ trains.append({
169
+ "departure": dep.get("date", ""),
170
+ "departure_station": dep_station.get("name", ""),
171
+ "arrival": arr.get("date", ""),
172
+ "arrival_station": arr_station.get("name", ""),
173
+ "duration_minutes": (dur.get("hours", 0) * 60
174
+ + dur.get("minutes", 0)),
175
+ "price_eur": price.get("total"),
176
+ "price_incl_fee_eur": price.get("total_with_platform_fee"),
177
+ "seats_available": avail.get("seats"),
178
+ "amenities": legs[0].get("amenities") or [],
179
+ "operator": "FlixTrain",
180
+ })
181
+ trains.sort(key=lambda t: t["departure"])
182
+ return {
183
+ "trains": trains,
184
+ "train_count": len(trains),
185
+ "bus_count": bus_count,
186
+ "from_city": from_city,
187
+ "to_city": to_city,
188
+ }
@@ -0,0 +1,103 @@
1
+ """HTTP layer for flixtrain_mcp — plain httpx GETs against global.api.flixbus.com (FlixBus shop search API).
2
+
3
+ No key, no login. One retry on 429/5xx; error taxonomy (403/429/other).
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ import ssl
9
+ import time
10
+
11
+ import httpx
12
+
13
+ UA = (
14
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
15
+ "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
16
+ )
17
+ TIMEOUT = 25.0
18
+ PROBE_URL = "https://global.api.flixbus.com/search/autocomplete/cities?q=Berlin&locale=de"
19
+ SOURCE = "global.api.flixbus.com"
20
+
21
+
22
+ class FlixtrainMcpError(RuntimeError):
23
+ pass
24
+
25
+
26
+ def _verify():
27
+ """TLS trust store: the OS bundle when present, else httpx/certifi."""
28
+ for path in (
29
+ "/etc/ssl/certs/ca-certificates.crt",
30
+ ssl.get_default_verify_paths().openssl_cafile,
31
+ ):
32
+ if path and os.path.exists(path):
33
+ return ssl.create_default_context(cafile=path)
34
+ return True
35
+
36
+
37
+ def _client() -> httpx.Client:
38
+ # NOTE: we read the proxy URL from the environment but never log it.
39
+ proxy = os.environ.get("https_proxy") or os.environ.get("HTTPS_PROXY")
40
+ return httpx.Client(
41
+ headers={"User-Agent": UA, "Accept": "application/json, application/xml, text/html, */*",
42
+ # The FlixBus search API requires the shop as Referer;
43
+ # without it the gateway answers 403 "Missing
44
+ # Authentication Token".
45
+ "Referer": "https://shop.flixbus.com/"},
46
+ timeout=TIMEOUT,
47
+ proxy=proxy or None,
48
+ trust_env=False,
49
+ verify=_verify(),
50
+ )
51
+
52
+
53
+ def fetch_text(url: str) -> str:
54
+ """GET one URL and return its text. One retry on 429/5xx."""
55
+ last_exc: Exception | None = None
56
+ r: httpx.Response | None = None
57
+ for attempt in range(2):
58
+ try:
59
+ with _client() as c:
60
+ r = c.get(url)
61
+ except httpx.HTTPError as e:
62
+ last_exc = e
63
+ if attempt == 0:
64
+ time.sleep(1.0)
65
+ continue
66
+ raise FlixtrainMcpError(f"network error fetching {url}: {e}") from e
67
+ if r.status_code in (429, 500, 502, 503):
68
+ if attempt == 0:
69
+ time.sleep(1.0)
70
+ continue
71
+ break
72
+ assert r is not None # loop always assigns r or raises
73
+ if r.status_code == 403:
74
+ raise FlixtrainMcpError(
75
+ f"{SOURCE} returned HTTP 403 for {url} (bot wall) — try again later"
76
+ )
77
+ if r.status_code == 429:
78
+ raise FlixtrainMcpError(
79
+ f"{SOURCE} rate-limited the request (HTTP 429) — try again later"
80
+ )
81
+ if r.status_code != 200:
82
+ raise FlixtrainMcpError(f"{SOURCE} returned HTTP {r.status_code} for {url}")
83
+ return r.text
84
+
85
+
86
+ def health_check() -> dict:
87
+ """One polite probe of the source site.
88
+
89
+ Returns {"status": "ok"|"blocked"|"error", "http_status": int|None,
90
+ "url": ..., "detail": ...}. Used by the `<prefix>_health` tool
91
+ and the daily smoke CI.
92
+ """
93
+ url = PROBE_URL
94
+ try:
95
+ fetch_text(url)
96
+ except FlixtrainMcpError as e:
97
+ msg = str(e)
98
+ if "403" in msg:
99
+ return {"status": "blocked", "http_status": 403, "url": url, "detail": msg}
100
+ if "429" in msg:
101
+ return {"status": "blocked", "http_status": 429, "url": url, "detail": msg}
102
+ return {"status": "error", "http_status": None, "url": url, "detail": msg}
103
+ return {"status": "ok", "http_status": 200, "url": url}