Skip to main content
Glama
Shadhai

IndianRailwaysMCP

by Shadhai


📑 目次


🎯 目的と哲学

Indian Railways は毎日13,000以上の列車を運行していますが、そのデータは不揃いなHTMLページとレート制限のあるエンドポイントの背後にあり、「私の列車は遅れていますか?」 という単純な質問にAIエージェントが答えることを困難にしています。

Indian Railways MCP Server は、スケジュール、ライブステータス、PNR、運賃、座席データを、あらゆるAIアシスタントが直接呼び出せる単一の構造化されたMCPインターフェースへ正規化することで、この問題を解決します。

  • 🔐 認証なし・秘密情報なし — すべてのデータソースが公開されており、漏えいするものは何もありません

  • 🧩 レイヤー化されたアーキテクチャ — サーバー・クライアント・パーサーの各レイヤーは個別にテスト・差し替え可能です

  • 📊 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 クライアントが tool call を stdio 経由で送信 → Server 層が Pydantic で入力を検証 → Client 層がリトライロジック付きで HTTP リクエストを発行 → Parser 層が HTML/JSON から構造化データを抽出 → Cache 層が結果を TTL 付きで保存 → レスポンスが整形されクライアントに返されます。


✨ 機能

モジュール

機能

リアルタイム

キャッシュTTL

🔍 駅・列車検索

8,000以上の駅と10,000以上の列車を名前またはコードで検索

24時間

🚂 列車スケジュール

すべての駅・時刻・距離を含む完全なルート

1時間

📍 ライブ運行状況

リアルタイムの位置、遅延、プラットフォーム情報

2分

🎫 PNRステータス

乗客の詳細、客車・寝台の割当、旅程情報

30秒

💺 座席空き状況

クラス別空き状況 — AVAILABLE / RAC / WL

2分

💰 運賃照会

全クラスの運賃内訳

1時間

🔀 駅間の列車

2つの駅を結ぶすべての列車

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(python:3.11-slim

プロセス管理

systemd(Linux サーバー展開用)


🚀 クイックスタート

前提条件

ツール

バージョン

備考

Python

3.10+

python --version で確認してください

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 の import パスを設定するだけです:

# ── 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 ではありません)。ツールは、あなたが自分で発行する HTTP リクエストではなく、あなたのAIクライアントによって呼び出されます。各ツールは、1つ以上の上流データソース呼び出しに対応します。

発見ツール

ツール

説明

認証

search_stations

ファジー/大文字小文字区別なしの照合で、名前から駅コードを検索

search_trains

ファジー/大文字小文字区別なしの照合で、名前から列車番号を検索

get_trains_between

任意の駅を結ぶすべての列車を列挙

スケジュール・ステータスツール

ツール

説明

認証

get_train_schedule

全ルート: 全駅の到着・出発時刻と距離

get_live_status

リアルタイム位置、遅延分、最新通過駅

get_station_live

指定した駅の出発予定一覧

予約・運賃ツール

ツール

説明

認証

check_pnr

PNR ステータス、乗客リスト、客車/座席、確定状況

check_seat_availability

クラス別の座席状況(AVAILABLE / RAC / WL)

get_fare

クラス別の運賃内訳

プラットフォームツール

ツール

説明

認証

get_coach_position

指定したプラットフォームの車両配置

get_platform_locator

列車が発着するプラットフォームを特定

📖 全パラメータのスキーマは、リポジトリ内の docs/API_REFERENCE.md を参照してください。


🌐 データソース

ERail.in(プライマリ)

エンドポイント

メソッド

フォーマット

キャッシュ TTL

/js5/IRStations.js

GET

JS/JSON 配列

24時間

/js5/IRTrains.js

GET

JS/JSON 配列

24時間

/train-enquiry/{train}

GET

HTML 表

1時間

/train-running-status/{train}

GET

HTML

2分

/pnr-status/{pnr}?format=json

GET

JSON

30秒

/train-seats/{train}

POST

HTML 表

2分

/train-fare/{train}

POST

HTML 表

1時間

/trains-between-stations/{from}/{to}

POST

HTML 表

1時間

/station-live/{station}

GET

HTML 表

2分

IndianRailways.info(セカンダリ)

エンドポイント

メソッド

フォーマット

キャッシュ TTL

/coach_position/

POST

HTML 表

1時間

/platform_locator/

POST

HTML

1時間


⏱ キャッシュ戦略

| データタイプ | TTL | 理由 | | :------------------ | :------ | 2日 :| | 駅一覧 | 24時間 | ほぼ変わらない | | 列車一覧 | 24時間 | ほとんど変わらない | | 列車スケジュール | 1時間 | 時々更新される | | ライブステータス | 2分 | リアルタイムデータ | | PNR ステータス | 30秒 | リアルタイムデータ | | 座席空き状況 | 2分 | 頻繁に変わる |


🧭 ユースケース

🗺AI旅行計画アシスタント

Claude Desktop 上に構築されたチャットボットは、このサーバーを使って旅程を一括計画します — 2つの都市間列車の検索、リアルタイムの座席空き状況の確認、運賃の取得、スケジュールの確認まで、すべて1つの自然言語会話で完了します。

📍 通勤者向けライブ列車トラッカー

通勤者向けのIVR ボタン... 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.json

  • Windows: %APPDATA%\Claude\claude_desktop_config.json

  • Linux: ~/.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.target
sudo 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

カバレッジ概要

モジュール

テスト

カバレッジ

client.py

40+

~95%

parsers.py

25+

~95%

utils.py

10+

~90%

models.py

5+

~85%

合計

80+

~92%


📈 パフォーマンス

応答時間(代表値)

操作

コールド (ms)

キャッシュ済み (ms)

駅検索

800

5

列車検索

1000

5

列車時刻表

1500

100

ライブステータス

2000

200

PNRステータス

1200

50

座席空き状況

2000

100

メモリ使用量: ~50MB(基本、Python + 依存関係)・~65MB(駅/列車キャッシュがウォーム時)・~80MB(HTML解析中のピーク時)。


🔒 セキュリティに関する注意事項

  • 認証は不要 — すべてのデータソースは公開されています

  • レート制限に安全 — 組み込みの指数バックオフにより、過剰なリクエストパターンを防止します

  • 入力の検証 — すべてのツール引数はPydanticモデルを通過します

  • 永続化なし — PNRおよび乗客データはディスクに書き込まれません

  • HTTPSのみ — すべての送信リクエストは暗号化されています


🔧 トラブルシューティング

症状

考えられる原因

修正方法

Module not found

PYTHONPATHが設定されていない

export PYTHONPATH="/path/to/Railway_mcp/src:$PYTHONPATH" または pip install -e .

サーバースクリプトでPermission denied

実行ビットが不足している

chmod +x src/indian_railways_mcp/server.py

サーバーが静かに終了する

Dockerに-iフラグがない

常に docker run -i indian-railways-mcp で実行(stdioは対話モードが必要)

依存関係が不足している

新規クローンでインストールしていない

pip install -r requirements.txt

Invalid Trainエラー

列車番号が間違っている、または不正な形式

search_trainsで5桁の番号であることを確認

No Data Found

その日は列車が運行していない

列車の運行日を確認

Station Not Found

駅コードが無効

最初にsearch_stationsを実行してコードを解決

Connection Timeout

上流のネットワーク問題

自動処理 — 指数バックオフ付きで3回再試行

Parse Error

上流サイトがHTML構造を変更した

parsers.pyで手動のパーサー更新が必要

Rate Limited

短時間にリクエストが多すぎる

自動的にバックオフします。タイトなポーリングループは避けてください


🗺 ロードマップ

  • コアツールセット — 駅/列車検索、時刻表、ライブステータス

  • PNRステータス、座席空き状況、運賃照会ツール

  • TTLベースのキャッシュ層とリトライ/バックオフ

  • Docker + systemdデプロイパス

  • 80以上のテストスイート、~92%のカバレッジ

  • 🚧 リモート(非stdio)デプロイ用のStreamable 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構造の変更は、このプロジェクトで最も انزياحن (Python ... wait,.,

( after theWe need.。 (placeholders.

-
license - not tested
Not graded
quality - not tested
B
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

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).

View all MCP Connectors

Latest Blog Posts

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