luftfly-mcp 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.
- luftfly_mcp/__init__.py +6 -0
- luftfly_mcp/__main__.py +4 -0
- luftfly_mcp/client.py +94 -0
- luftfly_mcp/server.py +115 -0
- luftfly_mcp/tools.py +406 -0
- luftfly_mcp-1.0.0.dist-info/METADATA +102 -0
- luftfly_mcp-1.0.0.dist-info/RECORD +11 -0
- luftfly_mcp-1.0.0.dist-info/WHEEL +5 -0
- luftfly_mcp-1.0.0.dist-info/entry_points.txt +2 -0
- luftfly_mcp-1.0.0.dist-info/licenses/LICENSE +13 -0
- luftfly_mcp-1.0.0.dist-info/top_level.txt +1 -0
luftfly_mcp/__init__.py
ADDED
luftfly_mcp/__main__.py
ADDED
luftfly_mcp/client.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Small HTTP client for the LuftFly Data API (stdlib only).
|
|
2
|
+
|
|
3
|
+
Configuration (environment variables):
|
|
4
|
+
LUFTFLY_API_KEY your key (required)
|
|
5
|
+
LUFTFLY_PROVIDER rapidapi (default) | apimarket | custom
|
|
6
|
+
LUFTFLY_BASE_URL override the base URL (needed for custom)
|
|
7
|
+
LUFTFLY_KEY_HEADER header that carries the key (custom only; defaults to the provider's header)
|
|
8
|
+
"""
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import time
|
|
12
|
+
import urllib.error
|
|
13
|
+
import urllib.parse
|
|
14
|
+
import urllib.request
|
|
15
|
+
|
|
16
|
+
from . import __version__
|
|
17
|
+
|
|
18
|
+
RAPID_HOST = "luftfly-data-api.p.rapidapi.com"
|
|
19
|
+
PRESETS = {
|
|
20
|
+
"rapidapi": {"base": "https://" + RAPID_HOST, "key_header": "X-RapidAPI-Key", "extra": {"X-RapidAPI-Host": RAPID_HOST}},
|
|
21
|
+
"apimarket": {"base": "https://prod.api.market/v1/nanxor/luftfly", "key_header": "x-api-market-key", "extra": {}},
|
|
22
|
+
"custom": {"base": "", "key_header": "X-API-Key", "extra": {}},
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ApiError(Exception):
|
|
27
|
+
"""An API or configuration problem with a message that is safe and useful to show to the model."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, message, status=None, code=None):
|
|
30
|
+
super().__init__(message)
|
|
31
|
+
self.status = status
|
|
32
|
+
self.code = code
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Client:
|
|
36
|
+
def __init__(self, env=None, opener=None):
|
|
37
|
+
env = os.environ if env is None else env
|
|
38
|
+
self.provider = (env.get("LUFTFLY_PROVIDER") or "rapidapi").strip().lower()
|
|
39
|
+
if self.provider not in PRESETS:
|
|
40
|
+
raise ApiError("LUFTFLY_PROVIDER must be rapidapi, apimarket or custom.")
|
|
41
|
+
preset = PRESETS[self.provider]
|
|
42
|
+
self.key = (env.get("LUFTFLY_API_KEY") or "").strip()
|
|
43
|
+
self.base = (env.get("LUFTFLY_BASE_URL") or preset["base"]).rstrip("/")
|
|
44
|
+
self.key_header = env.get("LUFTFLY_KEY_HEADER") or preset["key_header"]
|
|
45
|
+
self.extra = dict(preset["extra"])
|
|
46
|
+
self.timeout = float(env.get("LUFTFLY_TIMEOUT") or 25)
|
|
47
|
+
self._open = opener or urllib.request.urlopen
|
|
48
|
+
|
|
49
|
+
def configured(self):
|
|
50
|
+
return bool(self.key and self.base)
|
|
51
|
+
|
|
52
|
+
def setup_hint(self):
|
|
53
|
+
return ("The LuftFly MCP server needs an API key. Subscribe (a free plan exists) at https://rapidapi.com/nanxor-enterprise-data-hub/api/luftfly-data-api "
|
|
54
|
+
"or https://api.market/store/nanxor/luftfly, then set LUFTFLY_API_KEY in the MCP server's environment "
|
|
55
|
+
"(and LUFTFLY_PROVIDER=apimarket if the key comes from api.market).")
|
|
56
|
+
|
|
57
|
+
def get(self, path, params=None):
|
|
58
|
+
"""GET a /v1/... path; returns the parsed JSON body. Raises ApiError."""
|
|
59
|
+
if not self.configured():
|
|
60
|
+
raise ApiError(self.setup_hint(), code="not_configured")
|
|
61
|
+
query = {k: ("true" if v is True else "false" if v is False else str(v)) for k, v in (params or {}).items() if v is not None and v != ""}
|
|
62
|
+
url = self.base + path + (("?" + urllib.parse.urlencode(query)) if query else "")
|
|
63
|
+
headers = {"Accept": "application/json", "User-Agent": f"luftfly-mcp/{__version__}", self.key_header: self.key, **self.extra}
|
|
64
|
+
last = None
|
|
65
|
+
for attempt in range(2):
|
|
66
|
+
try:
|
|
67
|
+
with self._open(urllib.request.Request(url, headers=headers), timeout=self.timeout) as r:
|
|
68
|
+
return json.loads(r.read().decode("utf-8"))
|
|
69
|
+
except urllib.error.HTTPError as e:
|
|
70
|
+
body = {}
|
|
71
|
+
try:
|
|
72
|
+
body = json.loads(e.read().decode("utf-8"))
|
|
73
|
+
except Exception: # noqa: BLE001
|
|
74
|
+
pass
|
|
75
|
+
code, msg = body.get("error"), body.get("message")
|
|
76
|
+
if e.code in (401, 403):
|
|
77
|
+
raise ApiError("The API rejected the key (HTTP %d). Check LUFTFLY_API_KEY, LUFTFLY_PROVIDER and that you are subscribed to a plan." % e.code, e.code, "unauthorized")
|
|
78
|
+
if e.code == 429:
|
|
79
|
+
if attempt == 0:
|
|
80
|
+
time.sleep(1.5)
|
|
81
|
+
last = ApiError("Rate limit reached for your plan. Try again shortly or upgrade the plan.", 429, "rate_limited")
|
|
82
|
+
continue
|
|
83
|
+
raise ApiError("Rate limit reached for your plan. Try again shortly or upgrade the plan.", 429, "rate_limited")
|
|
84
|
+
if e.code >= 500 and attempt == 0:
|
|
85
|
+
time.sleep(1.0)
|
|
86
|
+
last = ApiError(f"The API had a temporary problem (HTTP {e.code}).", e.code)
|
|
87
|
+
continue
|
|
88
|
+
raise ApiError(msg or f"The API returned HTTP {e.code}.", e.code, code)
|
|
89
|
+
except (urllib.error.URLError, TimeoutError, OSError) as e:
|
|
90
|
+
last = ApiError(f"Could not reach the API: {getattr(e, 'reason', e)}")
|
|
91
|
+
if attempt == 0:
|
|
92
|
+
time.sleep(1.0)
|
|
93
|
+
continue
|
|
94
|
+
raise last or ApiError("Request failed.")
|
luftfly_mcp/server.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Minimal MCP server over stdio (newline-delimited JSON-RPC 2.0), standard library only.
|
|
2
|
+
|
|
3
|
+
Implements what a tools server needs: initialize, ping, tools/list, tools/call, prompts/list, prompts/get. Logs go to stderr, never stdout.
|
|
4
|
+
"""
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from . import __version__
|
|
9
|
+
from .client import Client
|
|
10
|
+
from .tools import PROMPTS, TOOLS, TOOLS_BY_NAME, prompt_text, run_tool
|
|
11
|
+
|
|
12
|
+
SUPPORTED = ["2025-06-18", "2025-03-26", "2024-11-05"]
|
|
13
|
+
INSTRUCTIONS = ("LuftFly gives you travel and airport data from open and official sources: airports and airlines, weather and forecasts, climate and best time to visit, "
|
|
14
|
+
"US flight performance and routes, time zones, holidays, currencies, country facts and government travel advisories. Start with search_airports when you only "
|
|
15
|
+
"have a city name. Results carry an 'attribution' line: keep it when you present the data. The data is informational, not an official source and not for navigation "
|
|
16
|
+
"or flight planning, and it does not include live flight status or schedules.")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _tool_listing():
|
|
20
|
+
out = []
|
|
21
|
+
for t in TOOLS:
|
|
22
|
+
out.append({"name": t["name"], "title": t["title"], "description": t["description"], "inputSchema": t["inputSchema"],
|
|
23
|
+
"annotations": {"title": t["title"], "readOnlyHint": True, "destructiveHint": False, "idempotentHint": True, "openWorldHint": True}})
|
|
24
|
+
return out
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Server:
|
|
28
|
+
def __init__(self, client=None):
|
|
29
|
+
self.client = client or Client()
|
|
30
|
+
|
|
31
|
+
# -- message handling -------------------------------------------------------------
|
|
32
|
+
def handle(self, msg):
|
|
33
|
+
"""Returns a response dict, or None for notifications."""
|
|
34
|
+
if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0":
|
|
35
|
+
return {"jsonrpc": "2.0", "id": msg.get("id") if isinstance(msg, dict) else None, "error": {"code": -32600, "message": "Invalid Request"}}
|
|
36
|
+
method, mid, params = msg.get("method"), msg.get("id"), msg.get("params") or {}
|
|
37
|
+
is_notification = "id" not in msg
|
|
38
|
+
if method is None: # a response to something we never sent: ignore
|
|
39
|
+
return None
|
|
40
|
+
try:
|
|
41
|
+
result = self._dispatch(method, params)
|
|
42
|
+
except _RpcError as e:
|
|
43
|
+
return None if is_notification else {"jsonrpc": "2.0", "id": mid, "error": {"code": e.code, "message": e.message}}
|
|
44
|
+
except Exception as e: # noqa: BLE001 (never crash the server on one bad request)
|
|
45
|
+
print(f"[luftfly-mcp] internal error in {method}: {type(e).__name__}: {e}", file=sys.stderr)
|
|
46
|
+
return None if is_notification else {"jsonrpc": "2.0", "id": mid, "error": {"code": -32603, "message": "Internal error"}}
|
|
47
|
+
if is_notification:
|
|
48
|
+
return None
|
|
49
|
+
return {"jsonrpc": "2.0", "id": mid, "result": result}
|
|
50
|
+
|
|
51
|
+
def _dispatch(self, method, params):
|
|
52
|
+
if method == "initialize":
|
|
53
|
+
wanted = params.get("protocolVersion")
|
|
54
|
+
return {"protocolVersion": wanted if wanted in SUPPORTED else SUPPORTED[0],
|
|
55
|
+
"capabilities": {"tools": {"listChanged": False}, "prompts": {"listChanged": False}},
|
|
56
|
+
"serverInfo": {"name": "luftfly", "title": "LuftFly Data API", "version": __version__}, "instructions": INSTRUCTIONS}
|
|
57
|
+
if method in ("notifications/initialized", "notifications/cancelled", "notifications/roots/list_changed"):
|
|
58
|
+
return None
|
|
59
|
+
if method == "ping":
|
|
60
|
+
return {}
|
|
61
|
+
if method == "tools/list":
|
|
62
|
+
return {"tools": _tool_listing()}
|
|
63
|
+
if method == "tools/call":
|
|
64
|
+
name = params.get("name")
|
|
65
|
+
if name not in TOOLS_BY_NAME:
|
|
66
|
+
raise _RpcError(-32602, f"Unknown tool: {name}")
|
|
67
|
+
text, is_error = run_tool(self.client, name, params.get("arguments") or {})
|
|
68
|
+
return {"content": [{"type": "text", "text": text}], "isError": is_error}
|
|
69
|
+
if method == "prompts/list":
|
|
70
|
+
return {"prompts": PROMPTS}
|
|
71
|
+
if method == "prompts/get":
|
|
72
|
+
text = prompt_text(params.get("name"), params.get("arguments") or {})
|
|
73
|
+
if text is None:
|
|
74
|
+
raise _RpcError(-32602, f"Unknown prompt: {params.get('name')}")
|
|
75
|
+
return {"description": "Trip briefing", "messages": [{"role": "user", "content": {"type": "text", "text": text}}]}
|
|
76
|
+
raise _RpcError(-32601, f"Method not found: {method}")
|
|
77
|
+
|
|
78
|
+
# -- stdio loop -------------------------------------------------------------------
|
|
79
|
+
def serve(self, stdin=None, stdout=None):
|
|
80
|
+
stdin = stdin or sys.stdin.buffer
|
|
81
|
+
stdout = stdout or sys.stdout.buffer
|
|
82
|
+
for raw in stdin:
|
|
83
|
+
line = raw.decode("utf-8", "replace").strip()
|
|
84
|
+
if not line:
|
|
85
|
+
continue
|
|
86
|
+
try:
|
|
87
|
+
msg = json.loads(line)
|
|
88
|
+
except ValueError:
|
|
89
|
+
self._write(stdout, {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}})
|
|
90
|
+
continue
|
|
91
|
+
for m in (msg if isinstance(msg, list) else [msg]):
|
|
92
|
+
resp = self.handle(m)
|
|
93
|
+
if resp is not None:
|
|
94
|
+
self._write(stdout, resp)
|
|
95
|
+
|
|
96
|
+
@staticmethod
|
|
97
|
+
def _write(stdout, obj):
|
|
98
|
+
stdout.write((json.dumps(obj, ensure_ascii=False, separators=(",", ":")) + "\n").encode("utf-8"))
|
|
99
|
+
stdout.flush()
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class _RpcError(Exception):
|
|
103
|
+
def __init__(self, code, message):
|
|
104
|
+
super().__init__(message)
|
|
105
|
+
self.code, self.message = code, message
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def main():
|
|
109
|
+
if "--version" in sys.argv:
|
|
110
|
+
print(__version__)
|
|
111
|
+
return
|
|
112
|
+
client = Client()
|
|
113
|
+
if not client.configured():
|
|
114
|
+
print("[luftfly-mcp] LUFTFLY_API_KEY is not set: tools will explain how to get a key.", file=sys.stderr)
|
|
115
|
+
Server(client).serve()
|
luftfly_mcp/tools.py
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
"""The tools the LuftFly MCP server offers. Each tool is one or a few calls to the LuftFly Data API, shaped for an AI assistant:
|
|
2
|
+
compact results, the data attribution carried along, and clear messages when a piece of data is not available."""
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
import urllib.parse
|
|
6
|
+
|
|
7
|
+
from .client import ApiError
|
|
8
|
+
|
|
9
|
+
MAX_CHARS = 30000
|
|
10
|
+
DISCLAIMER = ("Informational data from open and official sources; not an official source and not for navigation or flight planning. "
|
|
11
|
+
"Verify travel requirements with the issuing authority. Keep the attribution when you show this data to people.")
|
|
12
|
+
CODE_RE = re.compile(r"^[A-Za-z0-9-]{2,8}$")
|
|
13
|
+
COUNTRY_RE = re.compile(r"^[A-Za-z]{2,3}$")
|
|
14
|
+
LANGS = ["tr", "fr", "de", "es", "it", "pt", "ru", "ja", "zh", "ar", "ko", "nl"]
|
|
15
|
+
US_AREAS = ("US", "PR", "GU", "VI", "AS", "MP")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Ctx:
|
|
19
|
+
"""Collects attributions and per-part problems while a tool runs."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, client):
|
|
22
|
+
self.client = client
|
|
23
|
+
self.attribution = []
|
|
24
|
+
self.unavailable = {}
|
|
25
|
+
|
|
26
|
+
def fetch(self, path, params=None, optional=False, label=None):
|
|
27
|
+
try:
|
|
28
|
+
body = self.client.get(path, params)
|
|
29
|
+
except ApiError as e:
|
|
30
|
+
if optional and e.code not in ("not_configured", "unauthorized"):
|
|
31
|
+
self.unavailable[label or path] = str(e)
|
|
32
|
+
return None
|
|
33
|
+
raise
|
|
34
|
+
meta = body.get("meta") if isinstance(body, dict) else None
|
|
35
|
+
att = meta.get("attribution") if isinstance(meta, dict) else None
|
|
36
|
+
if isinstance(att, (list, tuple)): # the travel endpoints return a list of credit lines
|
|
37
|
+
att = " ".join(str(x) for x in att)
|
|
38
|
+
if att and att not in self.attribution:
|
|
39
|
+
self.attribution.append(str(att))
|
|
40
|
+
return body
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _need(args, name):
|
|
44
|
+
v = args.get(name)
|
|
45
|
+
if v is None or (isinstance(v, str) and not v.strip()):
|
|
46
|
+
raise ApiError(f"Missing required argument '{name}'.", code="bad_arguments")
|
|
47
|
+
return v
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def airport_code(args, name="code"):
|
|
51
|
+
v = str(_need(args, name)).strip()
|
|
52
|
+
if not CODE_RE.match(v):
|
|
53
|
+
raise ApiError(f"'{name}' must be an airport IATA or ICAO code such as YUL or CYUL.", code="bad_arguments")
|
|
54
|
+
return urllib.parse.quote(v.upper())
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def country_code(args, name="country"):
|
|
58
|
+
v = str(_need(args, name)).strip()
|
|
59
|
+
if not COUNTRY_RE.match(v):
|
|
60
|
+
raise ApiError(f"'{name}' must be an ISO country code such as CA or CAN.", code="bad_arguments")
|
|
61
|
+
return v.upper()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def lang(args):
|
|
65
|
+
v = args.get("language")
|
|
66
|
+
if v in (None, ""):
|
|
67
|
+
return None
|
|
68
|
+
v = str(v).lower()
|
|
69
|
+
if v not in LANGS:
|
|
70
|
+
raise ApiError("'language' must be one of: " + ", ".join(LANGS) + ".", code="bad_arguments")
|
|
71
|
+
return v
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def num(args, name, default=None, lo=None, hi=None):
|
|
75
|
+
v = args.get(name, default)
|
|
76
|
+
if v is None:
|
|
77
|
+
return None
|
|
78
|
+
try:
|
|
79
|
+
f = float(v)
|
|
80
|
+
except (TypeError, ValueError):
|
|
81
|
+
raise ApiError(f"'{name}' must be a number.", code="bad_arguments")
|
|
82
|
+
if (lo is not None and f < lo) or (hi is not None and f > hi):
|
|
83
|
+
raise ApiError(f"'{name}' must be between {lo} and {hi}.", code="bad_arguments")
|
|
84
|
+
return int(f) if f == int(f) else f
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def pick(d, keys):
|
|
88
|
+
return {k: d[k] for k in keys if isinstance(d, dict) and k in d and d[k] is not None}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def trim_text(d, keys=("text",), n=1800):
|
|
92
|
+
d = dict(d)
|
|
93
|
+
for k in keys:
|
|
94
|
+
if isinstance(d.get(k), str) and len(d[k]) > n:
|
|
95
|
+
d[k] = d[k][:n].rstrip() + " ... [shortened; the url has the full text]"
|
|
96
|
+
return d
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
# ---------------------------------------------------------------- handlers
|
|
100
|
+
def search_airports(ctx, a):
|
|
101
|
+
limit = num(a, "limit", 10, 1, 25)
|
|
102
|
+
lg = lang(a)
|
|
103
|
+
if a.get("city"):
|
|
104
|
+
b = ctx.fetch("/v1/cities/airports", {"q": a["city"], "country": a.get("country"), "radius_km": num(a, "radius_km", 100, 1, 500), "limit": limit, "lang": lg,
|
|
105
|
+
"scheduled": a.get("scheduled_only", True)})
|
|
106
|
+
return b["data"]
|
|
107
|
+
if a.get("lat") is not None and a.get("lon") is not None:
|
|
108
|
+
b = ctx.fetch("/v1/airports/nearby", {"lat": num(a, "lat", None, -90, 90), "lon": num(a, "lon", None, -180, 180), "radius_km": num(a, "radius_km", 100, 1, 500),
|
|
109
|
+
"limit": limit, "scheduled": "true" if a.get("scheduled_only", True) else None, "has_iata": "true", "lang": lg})
|
|
110
|
+
return {"airports": [pick(x, ["distance_km", "iata_code", "icao_code", "name", "municipality", "country", "type", "latitude", "longitude", "localized_name"]) for x in b["data"]]}
|
|
111
|
+
if a.get("query"):
|
|
112
|
+
b = ctx.fetch("/v1/airports", {"q": a["query"], "country": a.get("country"), "limit": limit, "lang": lg, "scheduled": "true" if a.get("scheduled_only", True) else None})
|
|
113
|
+
return {"airports": [pick(x, ["iata_code", "icao_code", "name", "municipality", "country", "type", "latitude", "longitude", "scheduled_service", "localized_name"]) for x in b["data"]],
|
|
114
|
+
"total": (b.get("paging") or {}).get("total")}
|
|
115
|
+
raise ApiError("Give one of: city, lat and lon, or query.", code="bad_arguments")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def airport_overview(ctx, a):
|
|
119
|
+
c = airport_code(a)
|
|
120
|
+
lg = lang(a)
|
|
121
|
+
ap = ctx.fetch(f"/v1/airports/{c}", {"include": "advisory", "lang": lg})["data"]
|
|
122
|
+
out = {"airport": pick(ap, ["name", "localized_name", "iata_code", "icao_code", "municipality", "country", "country_name", "region_name", "type", "latitude", "longitude",
|
|
123
|
+
"elevation_ft", "time_zone", "utc_offset", "scheduled_service", "advisory"])}
|
|
124
|
+
t = ctx.fetch(f"/v1/airports/{c}/time", optional=True, label="local_time")
|
|
125
|
+
if t:
|
|
126
|
+
out["local_time"] = pick(t["data"], ["local_time", "utc_offset", "abbreviation", "is_dst", "next_transition"])
|
|
127
|
+
s = ctx.fetch(f"/v1/airports/{c}/stats", optional=True, label="statistics")
|
|
128
|
+
if s:
|
|
129
|
+
out["statistics"] = s["data"]
|
|
130
|
+
w = ctx.fetch(f"/v1/airports/{c}/metar", optional=True, label="current_weather")
|
|
131
|
+
if w:
|
|
132
|
+
out["current_weather"] = pick(w["data"], ["raw", "observed_at", "age_minutes", "flight_category", "temperature_c", "dewpoint_c", "wind", "visibility_sm", "weather", "clouds"])
|
|
133
|
+
if ap.get("country") in US_AREAS:
|
|
134
|
+
d = ctx.fetch(f"/v1/airports/{c}/delays", optional=True, label="faa_delays")
|
|
135
|
+
if d:
|
|
136
|
+
out["faa_delays"] = d["data"]
|
|
137
|
+
p = ctx.fetch(f"/v1/airports/{c}/performance", optional=True, label="us_flight_performance")
|
|
138
|
+
if p:
|
|
139
|
+
out["us_flight_performance_12m"] = pick(p["data"], ["departures", "arrivals", "delay_cause_share_pct"])
|
|
140
|
+
at = ctx.fetch(f"/v1/airports/{c}/attractions", {"limit": 5, "radius_km": 150, "lang": lg}, optional=True, label="nearby_unesco_sites")
|
|
141
|
+
if at and at["data"]:
|
|
142
|
+
out["nearby_unesco_sites"] = [pick(x, ["name", "localized_name", "distance_km"]) for x in at["data"]]
|
|
143
|
+
return out
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def airport_weather(ctx, a):
|
|
147
|
+
c = airport_code(a)
|
|
148
|
+
parts = a.get("parts") or ["observation", "forecast"]
|
|
149
|
+
if isinstance(parts, str):
|
|
150
|
+
parts = [parts]
|
|
151
|
+
valid = {"observation", "taf", "forecast", "forecast_hourly", "climate"}
|
|
152
|
+
bad = [p for p in parts if p not in valid]
|
|
153
|
+
if bad:
|
|
154
|
+
raise ApiError("parts may contain: " + ", ".join(sorted(valid)) + ".", code="bad_arguments")
|
|
155
|
+
out = {}
|
|
156
|
+
if "observation" in parts:
|
|
157
|
+
b = ctx.fetch(f"/v1/airports/{c}/metar", optional=True, label="observation")
|
|
158
|
+
if b:
|
|
159
|
+
out["observation_metar"] = b["data"]
|
|
160
|
+
if "taf" in parts:
|
|
161
|
+
b = ctx.fetch(f"/v1/airports/{c}/taf", optional=True, label="taf")
|
|
162
|
+
if b:
|
|
163
|
+
out["taf"] = {k: v for k, v in b["data"].items() if k != "periods"} | {"periods": b["data"].get("periods", [])[:8]}
|
|
164
|
+
if "forecast" in parts or "forecast_hourly" in parts:
|
|
165
|
+
b = ctx.fetch(f"/v1/airports/{c}/forecast", {"view": "hourly" if "forecast_hourly" in parts else "daily"}, optional=True, label="forecast")
|
|
166
|
+
if b:
|
|
167
|
+
d = b["data"]
|
|
168
|
+
out["forecast"] = {"updated_at": d.get("updated_at"), "daily": d.get("daily"), **({"hourly_next_24h": d.get("hourly", [])[:24]} if "forecast_hourly" in parts else {})}
|
|
169
|
+
if "climate" in parts:
|
|
170
|
+
b = ctx.fetch(f"/v1/airports/{c}/climate", optional=True, label="climate")
|
|
171
|
+
if b:
|
|
172
|
+
out["climate"] = b["data"]
|
|
173
|
+
if not out:
|
|
174
|
+
raise ApiError("No weather data is available for this airport: " + "; ".join(f"{k}: {v}" for k, v in ctx.unavailable.items()), code="no_data")
|
|
175
|
+
return out
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def best_time_to_visit(ctx, a):
|
|
179
|
+
c = airport_code(a)
|
|
180
|
+
act = a.get("activity") or "sightseeing"
|
|
181
|
+
return ctx.fetch(f"/v1/airports/{c}/best-time", {"activity": act})["data"]
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def flight_info(ctx, a):
|
|
185
|
+
f, t = airport_code(a, "from"), airport_code(a, "to")
|
|
186
|
+
r = ctx.fetch("/v1/route", {"from": f, "to": t, "class": a.get("cabin_class"), "passengers": num(a, "passengers", None, 1, 500), "round_trip": a.get("round_trip")})["data"]
|
|
187
|
+
out = {"route": {"from": pick(r["from"], ["iata_code", "name", "municipality", "country", "time_zone"]), "to": pick(r["to"], ["iata_code", "name", "municipality", "country", "time_zone"]),
|
|
188
|
+
**pick(r, ["distance_km", "distance_mi", "flight_category", "estimated_flight_time", "time_difference_hours", "emissions", "method"])}}
|
|
189
|
+
rc = ctx.fetch("/v1/routes", {"from": f, "to": t}, optional=True, label="carriers")
|
|
190
|
+
if rc and rc["data"].get("served"):
|
|
191
|
+
out["carriers_domestic_us"] = rc["data"]["carriers"]
|
|
192
|
+
out["carriers_international"] = rc["data"]["international_carriers"]
|
|
193
|
+
return out
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def country_brief(ctx, a):
|
|
197
|
+
c = country_code(a)
|
|
198
|
+
lg = lang(a)
|
|
199
|
+
out = {}
|
|
200
|
+
out["country"] = ctx.fetch(f"/v1/countries/{c}", {"lang": lg})["data"]
|
|
201
|
+
ind = ctx.fetch(f"/v1/countries/{c}/indicators", optional=True, label="indicators")
|
|
202
|
+
if ind:
|
|
203
|
+
out["indicators"] = {k: pick(v, ["value", "year"]) for k, v in ind["data"].items()}
|
|
204
|
+
adv = ctx.fetch(f"/v1/travel/countries/{c}", optional=True, label="travel_advisory")
|
|
205
|
+
if adv:
|
|
206
|
+
out["travel_advisory"] = {k: v for k, v in adv["data"].items() if k not in ("sources", "attribution")}
|
|
207
|
+
hn = ctx.fetch(f"/v1/countries/{c}/health-notices", optional=True, label="health_notices")
|
|
208
|
+
if hn and hn["data"]:
|
|
209
|
+
out["cdc_health_notices"] = [pick(x, ["level", "topic", "published", "url"]) for x in hn["data"]][:5]
|
|
210
|
+
ho = ctx.fetch(f"/v1/countries/{c}/holidays", {"upcoming": "true", "days": num(a, "holiday_days", 120, 1, 365)}, optional=True, label="upcoming_holidays")
|
|
211
|
+
if ho:
|
|
212
|
+
out["upcoming_holidays"] = ho["data"]
|
|
213
|
+
return out
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def travel_advisory(ctx, a):
|
|
217
|
+
c = country_code(a)
|
|
218
|
+
sections = a.get("sections") or ["summary"]
|
|
219
|
+
if isinstance(sections, str):
|
|
220
|
+
sections = [sections]
|
|
221
|
+
valid = {"summary", "entry", "health", "laws", "hazards", "emergency"}
|
|
222
|
+
bad = [s for s in sections if s not in valid]
|
|
223
|
+
if bad:
|
|
224
|
+
raise ApiError("sections may contain: " + ", ".join(sorted(valid)) + ".", code="bad_arguments")
|
|
225
|
+
out = {}
|
|
226
|
+
for s in sections:
|
|
227
|
+
path = f"/v1/travel/countries/{c}" + ("" if s == "summary" else f"/{s}")
|
|
228
|
+
b = ctx.fetch(path, optional=len(sections) > 1, label=s)
|
|
229
|
+
if b:
|
|
230
|
+
d = b["data"]
|
|
231
|
+
out[s] = {k: v for k, v in trim_text(d).items() if k not in ("sources", "attribution")} if s == "summary" else trim_text(d)
|
|
232
|
+
return out
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def holidays(ctx, a):
|
|
236
|
+
c = country_code(a)
|
|
237
|
+
reg = a.get("region")
|
|
238
|
+
out = {}
|
|
239
|
+
if a.get("upcoming_days"):
|
|
240
|
+
b = ctx.fetch(f"/v1/countries/{c}/holidays", {"upcoming": "true", "days": num(a, "upcoming_days", None, 1, 365), "region": reg})
|
|
241
|
+
out["holidays"] = b["data"]
|
|
242
|
+
else:
|
|
243
|
+
b = ctx.fetch(f"/v1/countries/{c}/holidays", {"year": num(a, "year", None, 1900, 2200), "region": reg})
|
|
244
|
+
out["holidays"] = b["data"]
|
|
245
|
+
out["regions_available"] = b.get("regions_available")
|
|
246
|
+
if a.get("long_weekends"):
|
|
247
|
+
lw = ctx.fetch(f"/v1/countries/{c}/long-weekends", {"year": num(a, "year", None, 1900, 2200), "region": reg}, optional=True, label="long_weekends")
|
|
248
|
+
if lw:
|
|
249
|
+
out["long_weekends"] = lw["data"]
|
|
250
|
+
return out
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def convert_time(ctx, a):
|
|
254
|
+
b = ctx.fetch("/v1/time/convert", {"from": _need(a, "from"), "to": _need(a, "to"), "time": a.get("time")})
|
|
255
|
+
d = b["data"]
|
|
256
|
+
return {"from": pick(d["from"], ["time_zone", "local_time", "utc_offset", "abbreviation", "is_dst"]), "to": pick(d["to"], ["time_zone", "local_time", "utc_offset", "abbreviation", "is_dst", "next_transition"]),
|
|
257
|
+
"difference_hours": d["difference_hours"]}
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def convert_currency(ctx, a):
|
|
261
|
+
return ctx.fetch("/v1/fx/convert", {"from": _need(a, "from"), "to": _need(a, "to"), "amount": num(a, "amount", 1, 0, 1e12)})["data"]
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def us_flight_performance(ctx, a):
|
|
265
|
+
if a.get("from") and a.get("to"):
|
|
266
|
+
return ctx.fetch("/v1/routes", {"from": airport_code(a, "from"), "to": airport_code(a, "to")})["data"]
|
|
267
|
+
if a.get("airport"):
|
|
268
|
+
c = airport_code(a, "airport")
|
|
269
|
+
out = {}
|
|
270
|
+
p = ctx.fetch(f"/v1/airports/{c}/performance")
|
|
271
|
+
out["performance"] = p["data"]
|
|
272
|
+
r = ctx.fetch(f"/v1/airports/{c}/routes", {"limit": num(a, "limit", 10, 1, 50), "scope": a.get("scope")}, optional=True, label="routes")
|
|
273
|
+
if r:
|
|
274
|
+
out["busiest_routes"] = r["data"]
|
|
275
|
+
return out
|
|
276
|
+
if a.get("airline"):
|
|
277
|
+
code = str(a["airline"]).strip().upper()
|
|
278
|
+
if not re.match(r"^[A-Z0-9]{2}$", code):
|
|
279
|
+
raise ApiError("'airline' must be a two-character IATA airline code such as DL.", code="bad_arguments")
|
|
280
|
+
return ctx.fetch(f"/v1/airlines/{code}/performance")["data"]
|
|
281
|
+
raise ApiError("Give one of: airport, airline, or from and to.", code="bad_arguments")
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def natural_events(ctx, a):
|
|
285
|
+
params = {"radius_km": num(a, "radius_km", 300, 1, 1000), "days": num(a, "days", 7, 1, 30), "type": a.get("type"), "min_magnitude": num(a, "min_magnitude", None, 0, 10), "limit": num(a, "limit", 20, 1, 100)}
|
|
286
|
+
if a.get("airport"):
|
|
287
|
+
b = ctx.fetch(f"/v1/airports/{airport_code(a, 'airport')}/events", params)
|
|
288
|
+
elif a.get("lat") is not None and a.get("lon") is not None:
|
|
289
|
+
b = ctx.fetch("/v1/events", {**params, "lat": num(a, "lat", None, -90, 90), "lon": num(a, "lon", None, -180, 180)})
|
|
290
|
+
else:
|
|
291
|
+
raise ApiError("Give an airport code, or lat and lon.", code="bad_arguments")
|
|
292
|
+
return {"events": b["data"], "found": b.get("found"), "data_updated_at": b.get("data_updated_at")}
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def data_sources(ctx, a):
|
|
296
|
+
return ctx.fetch("/v1/meta")["data"]
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def api_request(ctx, a):
|
|
300
|
+
path = str(_need(a, "path")).strip()
|
|
301
|
+
if not path.startswith("/v1/") or ".." in path or "?" in path or "#" in path or re.search(r"\s", path) or "//" in path:
|
|
302
|
+
raise ApiError("path must be a plain API path starting with /v1/ (put query parameters in 'query').", code="bad_arguments")
|
|
303
|
+
q = a.get("query") or {}
|
|
304
|
+
if not isinstance(q, dict) or any(not isinstance(v, (str, int, float, bool)) for v in q.values()):
|
|
305
|
+
raise ApiError("query must be an object of simple values.", code="bad_arguments")
|
|
306
|
+
return ctx.fetch(path, q)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
# ---------------------------------------------------------------- registry
|
|
310
|
+
def _schema(props, required=()):
|
|
311
|
+
return {"type": "object", "properties": props, "required": list(required), "additionalProperties": False}
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
S = {"type": "string"}
|
|
315
|
+
LANG_P = {"type": "string", "enum": LANGS, "description": "Optional language for names (adds localized_name where available)."}
|
|
316
|
+
CODE_P = {"type": "string", "description": "Airport IATA (YUL) or ICAO (CYUL) code."}
|
|
317
|
+
TOOLS = [
|
|
318
|
+
{"name": "search_airports", "title": "Search airports", "handler": search_airports,
|
|
319
|
+
"description": "Find airports by city name (nearest airports to a city), by coordinates, or by name/code text. Returns IATA/ICAO codes, names and distances. Use this first when the user names a city or place instead of an airport code.",
|
|
320
|
+
"inputSchema": _schema({"city": {"type": "string", "description": "City name, e.g. Paris. Returns the nearest airports with scheduled service."}, "country": {"type": "string", "description": "ISO 3166-1 alpha-2 code to disambiguate (e.g. FR)."},
|
|
321
|
+
"query": {"type": "string", "description": "Airport name or code text, e.g. heathrow."}, "lat": {"type": "number"}, "lon": {"type": "number"},
|
|
322
|
+
"radius_km": {"type": "number", "description": "Search radius, default 100 (max 500)."}, "scheduled_only": {"type": "boolean", "description": "Only airports with scheduled passenger service (default true)."},
|
|
323
|
+
"limit": {"type": "integer", "description": "Default 10, max 25."}, "language": LANG_P})},
|
|
324
|
+
{"name": "airport_overview", "title": "Airport overview", "handler": airport_overview,
|
|
325
|
+
"description": "One call for the essentials of an airport: identity and location, country travel advisory level, local time, passenger/runway statistics, current weather (METAR), nearby UNESCO sites, and for US airports live FAA delays and 12-month on-time performance.",
|
|
326
|
+
"inputSchema": _schema({"code": CODE_P, "language": LANG_P}, ["code"])},
|
|
327
|
+
{"name": "airport_weather", "title": "Airport weather", "handler": airport_weather,
|
|
328
|
+
"description": "Weather for an airport: current METAR, TAF, multi-day forecast (daily or next 24 hours hourly) and monthly climate normals. METAR/TAF only exist for airports with a weather station; forecasts cover about 1,150 large airports.",
|
|
329
|
+
"inputSchema": _schema({"code": CODE_P, "parts": {"type": "array", "items": {"type": "string", "enum": ["observation", "taf", "forecast", "forecast_hourly", "climate"]}, "description": "Default: observation and forecast."}}, ["code"])},
|
|
330
|
+
{"name": "best_time_to_visit", "title": "Best time to visit", "handler": best_time_to_visit,
|
|
331
|
+
"description": "Monthly comfort score (0-100) for the area around an airport from climate normals, with the three best and worst months. A heuristic, not an official rating.",
|
|
332
|
+
"inputSchema": _schema({"code": CODE_P, "activity": {"type": "string", "enum": ["sightseeing", "beach", "city-break"], "description": "Default sightseeing."}}, ["code"])},
|
|
333
|
+
{"name": "flight_info", "title": "Flight distance, time and CO2", "handler": flight_info,
|
|
334
|
+
"description": "Between two airports: great-circle distance, rough flight time, time difference, and per-passenger CO2 estimate (UK government factors). For routes touching the US it also lists the carriers that fly the route (with passengers, load factor, on-time rate). It is not live flight status or a schedule.",
|
|
335
|
+
"inputSchema": _schema({"from": CODE_P, "to": CODE_P, "cabin_class": {"type": "string", "enum": ["average", "economy", "premium_economy", "business", "first"]},
|
|
336
|
+
"passengers": {"type": "integer"}, "round_trip": {"type": "boolean"}}, ["from", "to"])},
|
|
337
|
+
{"name": "country_brief", "title": "Country brief", "handler": country_brief,
|
|
338
|
+
"description": "A destination briefing for a country: facts (capital, currency with rate per euro, languages, driving side, calling code, neighbours), indicators (price level, Big Mac price, safety and infrastructure), the government travel advisory level, CDC health notices and upcoming public holidays.",
|
|
339
|
+
"inputSchema": _schema({"country": {"type": "string", "description": "ISO country code, e.g. JP or JPN."}, "language": LANG_P, "holiday_days": {"type": "integer", "description": "Look-ahead for holidays, default 120."}}, ["country"])},
|
|
340
|
+
{"name": "travel_advisory", "title": "Government travel advisory", "handler": travel_advisory,
|
|
341
|
+
"description": "Official government travel advice for a country (UK, Canada, US sources merged into one 1-4 level): summary, entry requirements, health, local laws, natural hazards and emergency numbers. Pick the sections you need.",
|
|
342
|
+
"inputSchema": _schema({"country": {"type": "string", "description": "ISO country code."}, "sections": {"type": "array", "items": {"type": "string", "enum": ["summary", "entry", "health", "laws", "hazards", "emergency"]}, "description": "Default: summary."}}, ["country"])},
|
|
343
|
+
{"name": "holidays", "title": "Public holidays and long weekends", "handler": holidays,
|
|
344
|
+
"description": "Public holidays for a country and year (2026-2028), or the upcoming ones; optional regional holidays (e.g. QC) and long weekends / one-day bridge opportunities.",
|
|
345
|
+
"inputSchema": _schema({"country": {"type": "string"}, "year": {"type": "integer"}, "upcoming_days": {"type": "integer", "description": "If set, list holidays in the next N days instead of a year."},
|
|
346
|
+
"region": {"type": "string", "description": "Region/subdivision code such as QC (see regions_available)."}, "long_weekends": {"type": "boolean"}}, ["country"])},
|
|
347
|
+
{"name": "convert_time", "title": "Convert time between places", "handler": convert_time,
|
|
348
|
+
"description": "Convert a local time between two airports or IANA time zones with the real daylight-saving rules for that date. 'time' is local time in the 'from' place, like 2026-12-01T09:30; omit for now.",
|
|
349
|
+
"inputSchema": _schema({"from": {"type": "string", "description": "Airport code or IANA zone, e.g. YUL or America/Toronto."}, "to": {"type": "string"}, "time": {"type": "string"}}, ["from", "to"])},
|
|
350
|
+
{"name": "convert_currency", "title": "Convert currency", "handler": convert_currency,
|
|
351
|
+
"description": "Convert an amount using European Central Bank reference rates (about 30 currencies). Indicative, not for trading.",
|
|
352
|
+
"inputSchema": _schema({"from": {"type": "string", "description": "ISO 4217 code, e.g. USD."}, "to": {"type": "string"}, "amount": {"type": "number"}}, ["from", "to"])},
|
|
353
|
+
{"name": "us_flight_performance", "title": "US flight performance and routes", "handler": us_flight_performance,
|
|
354
|
+
"description": "On-time statistics and routes from the US Bureau of Transportation Statistics: for an airport (delays, cancellations, causes, busiest routes), an airline (large US carriers), or a route (carriers, frequency, passengers). Covers domestic flights of the large US carriers plus international routes with a US end. Not live status.",
|
|
355
|
+
"inputSchema": _schema({"airport": CODE_P, "airline": {"type": "string", "description": "Two-letter IATA code of a US carrier, e.g. DL."}, "from": CODE_P, "to": CODE_P,
|
|
356
|
+
"scope": {"type": "string", "enum": ["all", "domestic", "international"]}, "limit": {"type": "integer"}})},
|
|
357
|
+
{"name": "natural_events", "title": "Earthquakes and natural events", "handler": natural_events,
|
|
358
|
+
"description": "Recent earthquakes (USGS) and open natural events (NASA EONET: wildfires, storms, volcanoes, floods) near an airport or a coordinate. Not an official warning service.",
|
|
359
|
+
"inputSchema": _schema({"airport": CODE_P, "lat": {"type": "number"}, "lon": {"type": "number"}, "radius_km": {"type": "number"}, "days": {"type": "integer"},
|
|
360
|
+
"type": {"type": "string", "description": "earthquake, wildfires, volcanoes, severeStorms, floods, ..."}, "min_magnitude": {"type": "number"}, "limit": {"type": "integer"}})},
|
|
361
|
+
{"name": "data_sources", "title": "Data sources and freshness", "handler": data_sources,
|
|
362
|
+
"description": "Lists every dataset behind the tools with its source, licence rhythm and last update. Use it to answer 'where does this come from' or 'how fresh is it'.",
|
|
363
|
+
"inputSchema": _schema({})},
|
|
364
|
+
{"name": "api_request", "title": "Raw API request", "handler": api_request,
|
|
365
|
+
"description": "Escape hatch: GET any LuftFly API path (e.g. /v1/airports/YUL/runways, /v1/rankings/airports?country=US). Prefer the specific tools; use this only when none fits. See https://api.nanxor.com/docs/ for the endpoint list.",
|
|
366
|
+
"inputSchema": _schema({"path": {"type": "string", "description": "Path starting with /v1/."}, "query": {"type": "object", "description": "Query parameters.", "additionalProperties": {"type": ["string", "number", "boolean"]}}}, ["path"])},
|
|
367
|
+
]
|
|
368
|
+
TOOLS_BY_NAME = {t["name"]: t for t in TOOLS}
|
|
369
|
+
|
|
370
|
+
PROMPTS = [
|
|
371
|
+
{"name": "plan_trip", "title": "Plan a trip", "description": "Build a trip briefing between two places using the LuftFly tools.",
|
|
372
|
+
"arguments": [{"name": "origin", "description": "Origin city or airport code", "required": True}, {"name": "destination", "description": "Destination city or airport code", "required": True},
|
|
373
|
+
{"name": "month", "description": "Month or dates of travel", "required": False}]},
|
|
374
|
+
]
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def prompt_text(name, args):
|
|
378
|
+
if name != "plan_trip":
|
|
379
|
+
return None
|
|
380
|
+
o, d, m = args.get("origin", "?"), args.get("destination", "?"), args.get("month")
|
|
381
|
+
return (f"Plan a trip from {o} to {d}" + (f" in {m}" if m else "") + ". Use the LuftFly tools: search_airports to find airport codes if I gave city names; "
|
|
382
|
+
"flight_info for distance, flight time, time difference and CO2; best_time_to_visit and airport_weather for the destination; country_brief and travel_advisory "
|
|
383
|
+
"(entry, health, emergency) for the destination country; holidays for dates that matter. Summarise clearly, mention what you could not find, and include the data attributions.")
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
# ---------------------------------------------------------------- execution
|
|
387
|
+
def run_tool(client, name, arguments):
|
|
388
|
+
"""Returns (text, is_error)."""
|
|
389
|
+
tool = TOOLS_BY_NAME.get(name)
|
|
390
|
+
if tool is None:
|
|
391
|
+
return f"Unknown tool '{name}'.", True
|
|
392
|
+
ctx = Ctx(client)
|
|
393
|
+
try:
|
|
394
|
+
data = tool["handler"](ctx, arguments or {})
|
|
395
|
+
except ApiError as e:
|
|
396
|
+
return str(e), True
|
|
397
|
+
payload = {"data": data}
|
|
398
|
+
if ctx.unavailable:
|
|
399
|
+
payload["not_available"] = ctx.unavailable
|
|
400
|
+
if ctx.attribution:
|
|
401
|
+
payload["attribution"] = " ".join(ctx.attribution)
|
|
402
|
+
payload["notice"] = DISCLAIMER
|
|
403
|
+
text = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
|
404
|
+
if len(text) > MAX_CHARS:
|
|
405
|
+
text = text[:MAX_CHARS] + '... [output shortened: narrow the request, for example with a smaller limit or fewer parts]'
|
|
406
|
+
return text, False
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: luftfly-mcp
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: MCP server for the LuftFly Data API: airports, weather, forecasts, climate, US flight performance, holidays, time zones, currencies and travel advisories for AI assistants
|
|
5
|
+
Author-email: NaNXOR Enterprise <info@nanxor.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://api.nanxor.com/docs/
|
|
8
|
+
Project-URL: Documentation, https://api.nanxor.com/docs/
|
|
9
|
+
Keywords: mcp,model-context-protocol,travel,airports,weather,aviation,ai-agents
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# LuftFly MCP server
|
|
19
|
+
|
|
20
|
+
<!-- mcp-name: com.nanxor/luftfly-mcp -->
|
|
21
|
+
|
|
22
|
+
Give your AI assistant (Claude, Cursor, any MCP client) real travel and airport data: airports and airlines, weather and forecasts, climate and best time to visit,
|
|
23
|
+
US flight performance and routes, time zones, holidays, currencies, country facts and government travel advisories. It talks to the
|
|
24
|
+
[LuftFly Data API](https://api.nanxor.com/docs/) with your own API key.
|
|
25
|
+
|
|
26
|
+
- **Zero dependencies** (Python 3.9+ standard library only), no telemetry, read-only (every tool only reads data).
|
|
27
|
+
- **14 tools** shaped for assistants: compact answers, the data attribution carried along, and clear messages when something is not available.
|
|
28
|
+
- Works with RapidAPI and api.market keys.
|
|
29
|
+
|
|
30
|
+
## 1. Get a key
|
|
31
|
+
Subscribe to a plan (a free plan exists) on [RapidAPI](https://rapidapi.com/nanxor-enterprise-data-hub/api/luftfly-data-api) or [api.market](https://api.market/store/nanxor/luftfly).
|
|
32
|
+
|
|
33
|
+
## 2. Install and configure
|
|
34
|
+
|
|
35
|
+
### Claude Code
|
|
36
|
+
```
|
|
37
|
+
claude mcp add luftfly -e LUFTFLY_API_KEY=your_key -- uvx luftfly-mcp
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
### Claude Desktop, Cursor and other clients (`mcpServers` JSON)
|
|
41
|
+
```json
|
|
42
|
+
{
|
|
43
|
+
"mcpServers": {
|
|
44
|
+
"luftfly": {
|
|
45
|
+
"command": "uvx",
|
|
46
|
+
"args": ["luftfly-mcp"],
|
|
47
|
+
"env": { "LUFTFLY_API_KEY": "your_key" }
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
Without `uvx`: `pip install luftfly-mcp` and use `"command": "luftfly-mcp"`.
|
|
53
|
+
|
|
54
|
+
### Environment variables
|
|
55
|
+
| Variable | Meaning |
|
|
56
|
+
|---|---|
|
|
57
|
+
| `LUFTFLY_API_KEY` | Your key (required) |
|
|
58
|
+
| `LUFTFLY_PROVIDER` | `rapidapi` (default) or `apimarket` (for an api.market key) or `custom` |
|
|
59
|
+
| `LUFTFLY_BASE_URL`, `LUFTFLY_KEY_HEADER` | Only for `custom`: base URL and the header that carries the key |
|
|
60
|
+
| `LUFTFLY_TIMEOUT` | Request timeout in seconds (default 25) |
|
|
61
|
+
|
|
62
|
+
If the key is missing the server still starts and its tools explain how to get one.
|
|
63
|
+
|
|
64
|
+
## Tools
|
|
65
|
+
| Tool | What it answers |
|
|
66
|
+
|---|---|
|
|
67
|
+
| `search_airports` | Find airports by city, coordinates or name/code text |
|
|
68
|
+
| `airport_overview` | Identity, advisory level, local time, statistics, current weather, nearby UNESCO sites; for US airports also FAA delays and on-time performance |
|
|
69
|
+
| `airport_weather` | METAR, TAF, daily or hourly forecast, climate normals |
|
|
70
|
+
| `best_time_to_visit` | Monthly comfort score and the best and worst months |
|
|
71
|
+
| `flight_info` | Distance, rough flight time, time difference, CO2 per passenger, carriers on routes touching the US |
|
|
72
|
+
| `country_brief` | Country facts, currency and rate, indicators (prices, safety), advisory level, CDC notices, upcoming holidays |
|
|
73
|
+
| `travel_advisory` | Government advice: summary, entry, health, laws, hazards, emergency numbers |
|
|
74
|
+
| `holidays` | Public holidays, regional holidays, long weekends and bridge days |
|
|
75
|
+
| `convert_time` | A local time between airports or zones with the right daylight-saving rules |
|
|
76
|
+
| `convert_currency` | ECB reference rates (indicative) |
|
|
77
|
+
| `us_flight_performance` | On-time, delay and route statistics for a US airport, airline or route |
|
|
78
|
+
| `natural_events` | Recent earthquakes and natural events near an airport or point |
|
|
79
|
+
| `data_sources` | Every dataset, its source, licence rhythm and freshness |
|
|
80
|
+
| `api_request` | Escape hatch for any other `GET /v1/...` endpoint |
|
|
81
|
+
|
|
82
|
+
There is also a `plan_trip` prompt that tells the assistant how to combine them.
|
|
83
|
+
|
|
84
|
+
## Try it
|
|
85
|
+
- "What is the weather like at Istanbul airport and when is the best time to visit?"
|
|
86
|
+
- "I fly Montreal to Istanbul on 1 December. How long, how much CO2, and what is the time difference for a call at 9:30?"
|
|
87
|
+
- "Give me a briefing for Japan: currency, holidays in the next months, travel advisory and health notices."
|
|
88
|
+
- "How reliable is JFK for on-time departures, and who flies JFK to Los Angeles?"
|
|
89
|
+
|
|
90
|
+
## Good to know
|
|
91
|
+
- Data comes from open and official sources (OurAirports, Wikidata, NOAA/NWS, MET Norway, NASA, FAA, US BTS, ECB, World Bank, government travel advisories, ...). Each result carries an `attribution` line: keep it when you show the data to people. `data_sources` lists everything.
|
|
92
|
+
- Informational only: not an official source, not for navigation or flight planning. There is **no live flight status or schedule data**.
|
|
93
|
+
- Your key is sent only to the LuftFly API; the server makes no other network requests.
|
|
94
|
+
|
|
95
|
+
## Develop
|
|
96
|
+
```
|
|
97
|
+
python -m unittest discover -s tests # unit tests (no network)
|
|
98
|
+
LUFTFLY_SECRET_FILE=... python tests/live_test.py # live test over stdio (maintainers)
|
|
99
|
+
```
|
|
100
|
+
The server implements MCP over stdio (newline-delimited JSON-RPC, protocol versions 2025-06-18, 2025-03-26, 2024-11-05) and is verified against the official MCP SDK client.
|
|
101
|
+
|
|
102
|
+
MIT licence. Operated by NaNXOR Enterprise, info@nanxor.com.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
luftfly_mcp/__init__.py,sha256=0tD2Y87hJPYG3T0-c1LXy4PT7bQ1H4s3S9kD15t_8I0,252
|
|
2
|
+
luftfly_mcp/__main__.py,sha256=9it1my_mM7xBpDh79QSi7FAvZD3Vki3GQFPJIDZw_zs,64
|
|
3
|
+
luftfly_mcp/client.py,sha256=SHMXCJlteBhZzrvZVYh_H1KGPYGQYii2FeMwrYBcPPU,4783
|
|
4
|
+
luftfly_mcp/server.py,sha256=JoEkjgQC0D_dz4UIlDXkjvTEISW4SgrDjap2kbLFzA4,5859
|
|
5
|
+
luftfly_mcp/tools.py,sha256=40EpeL1vi-omy6SPs9MmkGCuuvUp1xzKwjQXIam1SYs,26101
|
|
6
|
+
luftfly_mcp-1.0.0.dist-info/licenses/LICENSE,sha256=Y7VCKUAHu6zPKmzY1zSPjGvmTAKfWhTO0I0J2fnQGd8,1087
|
|
7
|
+
luftfly_mcp-1.0.0.dist-info/METADATA,sha256=VXdi0h7R6FqLTDH_pBWJjQ9gS-cXrAKzgB-3vM9_DYU,5509
|
|
8
|
+
luftfly_mcp-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
luftfly_mcp-1.0.0.dist-info/entry_points.txt,sha256=uzvJNLqElYwuDB-UGnNpP_027ehaw9N1g9CY7dHvfIc,56
|
|
10
|
+
luftfly_mcp-1.0.0.dist-info/top_level.txt,sha256=dRhgsv1y6F69t5GtANmD_CNn7KuVJ-ZYrX5qi-hB8A4,12
|
|
11
|
+
luftfly_mcp-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 NaNXOR Enterprise
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software
|
|
6
|
+
without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
|
|
7
|
+
persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
8
|
+
|
|
9
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
10
|
+
|
|
11
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
|
12
|
+
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
|
|
13
|
+
OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
luftfly_mcp
|