台灣高鐵(THSR)資訊查詢 MCP 伺服器,提供時刻表、車站資訊、座位查詢等功能。
底層使用交通部 TDX 運輸資料流通服務 API。
此專案 fork 自 physictim/thsrc_mcp,已大幅優化 API 請求穩定性與錯誤處理。
- Python 3.8+
- TDX API 金鑰(請至 TDX 平臺 註冊取得)
# Clone 專案
git clone <your-repo-url>
cd thsrc_mcp
# 建立虛擬環境
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# 安裝依賴
pip install -r requirements.txt在專案目錄建立 .env 檔案:
TDX_CLIENT_ID=你的ClientID
TDX_CLIENT_SECRET=***完成安裝與環境變數設定後,即可在支援 MCP 的應用程式中使用。
在 ~/.hermes/config.yaml 中加入:
mcp_servers:
thsrc:
command: /path/to/your/python3
args:
- /path/to/your/thsrc.py
env:
TDX_CLIENT_ID: "你的ClientID"
TDX_CLIENT_SECRET: "你的ClientSecret"
enabled: true使用 openclaw mcp set 指令註冊:
openclaw mcp set thsrc '{
"command": "/path/to/your/python3",
"args": ["/path/to/your/thsrc.py"],
"env": {
"TDX_CLIENT_ID": "你的ClientID",
"TDX_CLIENT_SECRET": "你的ClientSecret"
}
}'在 claude_desktop_config.json 中加入:
{
"mcpServers": {
"thsrc": {
"command": "python",
"args": ["/path/to/your/thsrc.py"],
"env": {
"TDX_CLIENT_ID": "你的ClientID",
"TDX_CLIENT_SECRET": "你的ClientSecret"
}
}
}
}重新啟動 MCP 用戶端後,即可開始查詢高鐵資訊。
get_thsr_stations()取得所有台灣高鐵車站資訊。
get_thsr_timetable(
origin_station_id: str,
destination_station_id: str,
travel_date: str,
)查詢指定路線與日期的班次時刻表。
| 參數 | 說明 | 範例 |
|---|---|---|
origin_station_id |
起站代碼 | 1020(桃園) |
destination_station_id |
迄站代碼 | 1040(台中) |
travel_date |
乘車日期 | 2026-04-30 |
get_thsr_station_seats(station_id: str)查詢指定車站各班次的標準車廂與商務車廂座位狀況(O / L / X)。
get_thsr_train_info(train_no: str, travel_date: str)查詢特定車次的詳細停靠站與時間。
get_thsr_available_seats(
origin_station_id: str,
destination_station_id: str,
train_date: str,
)查詢指定日期起迄站之間仍有座位的車班。
get_thsr_train_seat_status(
origin_station_id: str,
destination_station_id: str,
train_date: str,
train_no: str,
)查詢特定車班的座位狀況。
| 代碼 | 說明 |
|---|---|
O |
有座位 |
L |
剩少量 |
X |
已售完 |
| 車站 | 代碼 |
|---|---|
| 南港 | 0990 |
| 台北 | 1000 |
| 板橋 | 1010 |
| 桃園 | 1020 |
| 新竹 | 1030 |
| 苗栗 | 1035 |
| 台中 | 1040 |
| 彰化 | 1043 |
| 雲林 | 1047 |
| 嘉義 | 1050 |
| 台南 | 1060 |
| 左營 | 1070 |
| 例外 | 說明 |
|---|---|
THSRCError |
通用錯誤基底 |
THSRCAuthError |
Token 認證失敗(401 重試耗盡) |
THSRCRateLimitError |
API Rate Limit 觸發(429 重試耗盡) |
THSRCAPIError |
API 回傳錯誤或 timeout |
api_request() 內建以下重試策略,最多重試 3 次:
| 情境 | 處理方式 |
|---|---|
| 401 Unauthorized | 清除 token,等待 1s 後重新取得再試 |
| 429 Rate Limit | 根據 Retry-After header 等待後重試 |
| 5xx Server Error | Exponential backoff(2s → 4s → 8s) |
| Timeout | Exponential backoff(2s → 4s → 8s) |
| 其他異常 | Exponential backoff 後重試 |
pytest test_thsrc.py -v23 個測試案例,涵蓋 token 管理、API 請求重試路徑、邊界條件。使用 mock 方式測試,不會實際呼叫 TDX API。
- TDX 座位資料非即時:更新批次為每日 10:00 / 16:00 / 22:00,查詢結果可能延遲數小時
- 此工具查的是 TDX 開放資料,並非高鐵官方售票系統,實際座位以購票頁面為準
- 所有工具參數使用 車站代碼(Station ID),不支援中文站名
MIT