IndianRailwaysMCP
📑 目录
🎯 目的与理念
印度铁路每天运行超过 13,000 趟列车,但其数据分散在不一致的 HTML 页面和限流端点之后 —— 这使得 AI 智能体难以回答像 "我的火车晚点了吗?" 这样的简单问题。
Indian Railways MCP Server 通过将时刻表、实时状态、PNR、票价和座位数据标准化为统一的、结构化的 MCP 接口来解决这个问题,任何 AI 助手都可以直接调用。
🔐 无需认证,无密钥 —— 所有数据源均为公开数据,无泄露风险
🧩 分层架构 —— 服务器、客户端和解析器层均可独立测试和替换
📊 TTL 感知缓存 —— 每次工具调用都遵循数据新鲜度窗口,而不是频繁请求上游站点
⚡ 默认弹性 —— 指数退避重试机制可吸收上游不稳定因素,确保你的智能体在对话中不会崩溃
🏗 架构
graph TD
Client["🖥️ MCP Client<br/>(Claude Desktop / Cursor / Continue.dev)"] -->|MCP Protocol · stdio| Server
subgraph Server["🚂 Indian Railways MCP Server"]
direction TB
SL["🛠️ Server Layer<br/>Tool registration (10 tools)<br/>Pydantic input validation"]
CL["🌐 Client Layer<br/>httpx session mgmt<br/>tenacity retry logic<br/>TTL response cache"]
PL["🔎 Parser Layer<br/>BeautifulSoup HTML parsing<br/>Pydantic JSON parsing<br/>Regex extraction"]
SL --> CL --> PL
end
PL -->|HTTP/HTTPS| ERail[("🗄️ ERail.in<br/>Schedules · Live status<br/>PNR · Seats · Fares")]
PL -->|HTTP/HTTPS| IRInfo[("🗄️ IndianRailways.info<br/>Coach position<br/>Platform locator")]数据流: MCP 客户端通过 stdio 发送工具调用 → 服务器层使用 Pydantic 验证输入 → 客户端层发出带重试逻辑的 HTTP 请求 → 解析器层从 HTML/JSON 中提取结构化数据 → 缓存层存储带 TTL 的结果 → 响应被格式化并返回给客户端。
✨ 功能特性
模块 | 功能 | 实时 | 缓存 TTL |
🔍 车站与列车搜索 | 按名称或代码搜索 8,000+ 车站和 10,000+ 列车 | ❌ | 24 小时 |
🚂 列车时刻表 | 完整路线,包含所有车站、时间和距离 | ❌ | 1 小时 |
📍 实时运行状态 | 实时位置、延误和站台信息 | ✅ | 2 分钟 |
🎫 PNR 状态 | 乘客详情、车厢/铺位分配、行程信息 | ✅ | 30 秒 |
💺 座位可用性 | 按舱位等级查看可用性 —— AVAILABLE / RAC / WL | ✅ | 2 分钟 |
💰 票价查询 | 所有旅行舱位的票价明细 | ❌ | 1 小时 |
🔀 站间列车 | 连接两个车站的所有列车 | ❌ | 1 小时 |
🏢 车站实时 | 任意车站的即将出发列车 | ✅ | 2 分钟 |
🚃 车厢位置 | 任意车站站台的车厢布局 | ❌ | 1 小时 |
🧰 技术栈
层 | 技术 |
运行时 | Python 3.10+ |
协议 | Model Context Protocol (MCP) SDK 1.0+ |
HTTP 客户端 | httpx |
HTML 解析 | BeautifulSoup4 |
数据验证 | Pydantic 2.0+ |
重试逻辑 | tenacity(指数退避) |
测试 | pytest, pytest-cov, pytest-mock, pytest-asyncio |
打包 | pyproject.toml(可通过 pip 安装) |
容器化 | Docker( |
进程管理 | systemd(Linux 服务器部署) |
🚀 快速开始
前置要求
工具 | 版本 | 备注 |
Python | 3.10+ | 使用 |
pip | 最新版 | 随 Python 一起提供 |
MCP 客户端 | 任意 | Claude Desktop、Cursor 或 Continue.dev |
第 1 步 —— 克隆
git clone https://github.com/Shadhai/Railway_mcp.git
cd Railway_mcp第 2 步 —— 配置
# Create and activate a virtual environment (recommended)
python -m venv .venv
source .venv/bin/activate # Linux/Mac
# .venv\Scripts\activate # Windows
# Install dependencies
pip install mcp httpx beautifulsoup4 pydantic tenacity第 3 步 —— 运行
# Run directly
python -m src.indian_railways_mcp.server
# Or install as a package and run the entry point
pip install -e .
indian-railways-mcp✅ 成功 —— 预期输出如下:
✅ Available tools: 10
- search_stations: Search Indian Railways stations by name or code...
- search_trains: Search Indian Railways trains by number or name...
- get_train_schedule: Get complete train schedule with all stations...
...⚙️ 环境配置
无需任何凭据 —— 所有上游数据源均可公开访问。唯一使用的环境变量用于配置 Python 导入路径:
# ── Runtime ─────────────────────────────────────────────
PYTHONPATH=/path/to/Railway_mcp/src
# <!-- VERIFY: add PORT/NODE_ENV-style vars here only if you front this
# server with a custom HTTP/SSE transport wrapper. Stdio transport
# (the default) needs nothing beyond PYTHONPATH. -->🛠 MCP 工具参考
此服务器通过 MCP stdio 协议 通信,而非公共 REST API —— 工具由你的 AI 客户端调用,而非由你自行发起 HTTP 请求。每个工具对应一个或多个上游数据源调用。
发现工具
工具 | 描述 | 认证 |
| 按名称查找车站代码,支持模糊/不区分大小写匹配 | ❌ |
| 按名称查找列车车次,支持模糊/不区分大小写匹配 | ❌ |
| 列出连接两个车站的所有列车 | ❌ |
时刻表与状态工具
工具 | 描述 | 认证 |
| 完整路线:每个车站、到达/出发时间、距离 | ❌ |
| 实时位置、延误分钟数、最近经过的车站 | ❌ |
| 指定车站的即将出发列车 | ❌ |
预订与票价工具
工具 | 描述 | 认证 |
| PNR 状态、乘客列表、车厢/铺位、确认状态 | ❌ |
| 按舱位等级查看座位状态(AVAILABLE / RAC / WL) | ❌ |
| 按舱位等级查看票价明细 | ❌ |
站台工具
工具 | 描述 | 认证 |
| 指定站台的车厢布局 | ❌ |
| 定位列车到达的站台 | ❌ |
📖 完整参数模式请参阅仓库中的
docs/API_REFERENCE.md。
🌐 数据源
ERail.in(主要)
端点 | 方法 | 格式 | 缓存 TTL |
|
| JS/JSON 数组 | 24 小时 |
|
| JS/JSON 数组 | 24 小时 |
|
| HTML 表格 | 1 小时 |
|
| HTML | 2 分钟 |
|
| JSON | 30 秒 |
|
| HTML 表格 | 2 分钟 |
|
| HTML 表格 | 1 小时 |
|
| HTML 表格 | 1 小时 |
|
| HTML 表格 | 2 分钟 |
IndianRailways.info(次要)
端点 | 方法 | 格式 | 缓存 TTL |
|
| HTML 表格 | 1 小时 |
|
| HTML | 1 小时 |
⏱ 缓存策略
数据类型 | TTL | 原因 |
车站列表 | 24 小时 | 很少变化 |
列车列表 | 24 小时 | 很少变化 |
列车时刻表 | 1 小时 | 偶尔更新 |
实时状态 | 2 分钟 | 实时数据 |
PNR 状态 | 30 秒 | 实时数据 |
座位可用性 | 2 分钟 | 频繁更新 |
🧭 使用场景
🗺️ AI 旅行规划助手
基于 Claude Desktop 构建的聊天机器人使用此服务器规划端到端旅程 —— 搜索两座城市之间的列车、查看实时座位可用性、获取票价并确认时刻表,全部通过一次自然语言对话完成。
📍 通勤者实时列车追踪器
面向通勤者的 IVR 或 WhatsApp 机器人每隔几分钟轮询 get_live_status,告知乘客列车具体延误了多久以及最近经过的车站。
🎫 PNR 礼宾机器人
集成 check_pnr 的支持机器人可即时回答"我的车票确认了吗?",包括每位乘客的车厢、铺位和候补位置 —— 无需人工客服。
🎓 学术/作品集项目
一位正在构建基于 MCP 的 AI 代理的学生,将此仓库作为 Model Context Protocol 背后分层、缓存、重试安全的抓取架构的参考实现。
💡 使用示例
完整行程规划
from indian_railways_mcp.client import IndianRailwaysClient
client = IndianRailwaysClient()
trains = client.get_trains_between("NDLS", "BCT")
train = trains['trains'][0]
seats = client.check_seat_availability(
train['train_number'], "NDLS", "BCT", "20-Jul-2026"
)
if any(c['status'] == 'AVAILABLE' for c in seats['classes']):
fare = client.get_fare(train['train_number'], "NDLS", "BCT")
print(f"Fare: ₹{fare['classes'][0]['total_fare']}")
schedule = client.get_train_schedule(train['train_number'])
print(f"Travel time: {schedule['travel_time']} hours")实时列车追踪
status = client.get_live_status("04815")
if status['status'] == 'RUNNING':
print(f"{status['train_name']} last seen at {status['last_station']}, "
f"delayed {status['delay_minutes']} min")PNR 状态查询
pnr = client.check_pnr("4553137968")
for p in pnr['passengers']:
print(f"Passenger {p['serial']}: {p['current_status']} | "
f"Coach {p['coach']} | Berth {p['berth']} ({p['berth_type']})")📁 项目结构
Railway_mcp/
├── 📄 README.md # Main documentation
├── 📄 pyproject.toml # Package configuration
├── 📄 LICENSE # MIT License
├── 📄 .gitignore # Git ignore rules
├── 📁 docs/
│ ├── API_REFERENCE.md # Complete tool/API documentation
│ ├── ARCHITECTURE.md # System architecture
│ └── EXAMPLES.md # Usage examples
├── 📁 src/
│ └── 📁 indian_railways_mcp/
│ ├── __init__.py # Package init
│ ├── server.py # MCP server (10 tools)
│ ├── client.py # HTTP client (all endpoints)
│ ├── parsers.py # HTML/JSON parsers
│ ├── models.py # Pydantic data models
│ └── utils.py # Caching + retry utilities
└── 📁 tests/
├── test_client.py # Client tests
└── test_parsers.py # Parser tests🔌 客户端集成
编辑你的配置文件:
Mac:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.jsonLinux:
~/.config/Claude/claude_desktop_config.json
{
"mcpServers": {
"indian-railways": {
"command": "python",
"args": ["-m", "src.indian_railways_mcp.server"],
"cwd": "/path/to/Railway_mcp",
"env": { "PYTHONPATH": "/path/to/Railway_mcp/src" }
}
}
}重启 Claude Desktop — 你会看到一个 🔌 图标,其中列出了 Indian Railways 工具。
添加到 ~/.cursor/mcp.json:
{
"mcpServers": {
"indian-railways": {
"command": "python",
"args": ["-m", "src.indian_railways_mcp.server"],
"cwd": "/path/to/Railway_mcp"
}
}
}添加到 ~/.continue/config.json:
{
"experimental": {
"modelContextProtocolServers": [
{
"transport": {
"type": "stdio",
"command": "python",
"args": ["-m", "src.indian_railways_mcp.server"],
"cwd": "/path/to/Railway_mcp"
}
}
]
}
}npx @modelcontextprotocol/inspector python -m src.indian_railways_mcp.server🐳 Docker 部署
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY src/ ./src/
ENV PYTHONPATH=/app
CMD ["python", "-m", "src.indian_railways_mcp.server"]# Build
docker build -t indian-railways-mcp .
# Run (stdio requires interactive mode)
docker run -i indian-railways-mcp/etc/systemd/system/indian-railways-mcp.service:
[Unit]
Description=Indian Railways MCP Server
After=network.target
[Service]
Type=simple
User=mcp
WorkingDirectory=/opt/indian-railways-mcp
Environment=PYTHONPATH=/opt/indian-railways-mcp/src
ExecStart=/usr/bin/python3 -m src.indian_railways_mcp.server
Restart=on-failure
RestartSec=10
[Install]
WantedBy=multi-user.targetsudo systemctl daemon-reload
sudo systemctl enable indian-railways-mcp
sudo systemctl start indian-railways-mcp
sudo systemctl status indian-railways-mcp🧪 测试
# Install test dependencies
pip install pytest pytest-cov pytest-mock pytest-asyncio
# Run all tests
pytest tests/ -v
# Run with coverage
pytest tests/ -v --cov=src/indian_railways_mcp --cov-report=html
# Run a specific file / class / test
pytest tests/test_client.py -v
pytest tests/test_client.py::TestPNRStatus -v
pytest tests/test_client.py::TestPNRStatus::test_check_pnr_success -v覆盖率摘要
模块 | 测试 | 覆盖率 |
| 40+ | ~95% |
| 25+ | ~95% |
| 10+ | ~90% |
| 5+ | ~85% |
总计 | 80+ | ~92% |
📈 性能
响应时间(典型值)
操作 | 冷启动(毫秒) | 缓存(毫秒) |
搜索车站 | 800 | 5 |
搜索列车 | 1000 | 5 |
列车时刻表 | 1500 | 100 |
实时状态 | 2000 | 200 |
PNR 状态 | 1200 | 50 |
座位余票 | 2000 | 100 |
内存占用: 基础约 50MB(Python + 依赖)· 车站/列车缓存预热后约 65MB · HTML 解析期间峰值约 80MB。
🔒 安全说明
无需身份验证 — 所有数据源均为公开数据
限流安全 — 内置指数退避机制可防止滥用性请求模式
输入验证 — 所有工具参数均通过 Pydantic 模型校验
无持久化 — PNR 和乘客数据从不写入磁盘
仅使用 HTTPS — 所有出站请求均经过加密
🔧 故障排查
症状 | 可能原因 | 修复方法 |
|
|
|
服务器脚本权限被拒绝 | 缺少执行权限 |
|
服务器静默退出 | Docker 缺少 | 始终使用 |
依赖缺失 | 全新克隆,未安装 |
|
| 列车编号错误或格式不正确 | 通过 |
| 列车当天不运行 | 查看列车的运行日期 |
| 无效的车站代码 | 先运行 |
| 上游网络问题 | 自动处理 — 3 次重试并带指数退避 |
| 上游网站更改了 HTML 结构 | 需要在 |
| 短时间内请求过多 | 自动退避;避免紧密的轮询循环 |
🗺 路线图
核心工具集 — 车站/列车搜索、时刻表、实时状态
PNR 状态、座位余票和票价查询工具
基于 TTL 的缓存层,带重试/退避机制
Docker + systemd 部署路径
80+ 测试套件,覆盖率约 92%
🚧 用于远程(非 stdio)部署的可流式 HTTP/SSE 传输
🚧 多语言车站/列车名称匹配(印地语、地区文字)
🚧 用于延误和站台变更的 Webhook/推送提醒
🚧 基于官方
llms.txt的工具发现,以支持更广泛的代理框架
🤝 贡献指南
# 1. Fork the repository
# 2. Clone your fork
git clone https://github.com/YOUR_USERNAME/Railway_mcp.git
cd Railway_mcp
# 3. Create a feature branch
git checkout -b feature/your-feature-name
# 4. Make your changes and add tests
pytest tests/ -v
# 5. Commit and push
git commit -m "Add: your feature description"
git push origin feature/your-feature-name
# 6. Open a Pull Request against main请确保对解析器的修改在 tests/test_parsers.py 中有测试覆盖 — 上游 HTML 结构变更是此项目中最常见的回归来源。
👥 贡献者
⭐ Star 历史
🤖 AI 就绪文件
此仓库附带代理发现存根,使 AI 编码助手(以及支持 MCP 的爬虫)无需解析完整 README 即可理解项目:
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Connectors
Read and update your Everway trips and itineraries from any MCP-compatible AI assistant.
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
TravelMind: 8 MCP tools for travel (12306 trains, flights, hotels, geocode, planning, policy).
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/Shadhai/Railway_mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server