# MCP Server 啟動機制說明
## 📋 啟動流程
### 1. 客戶端呼叫工具
```python
from weather_mcp import WeatherMCPClient
client = WeatherMCPClient()
result = client.geocode_city("Tokyo") # ← 觸發伺服器啟動
```
### 2. 客戶端啟動伺服器子程序
```python
# client.py (第 86-89 行)
params = StdioServerParameters(
command=sys.executable, # Python 解釋器
args=[str(server_script)] # server.py 路徑
)
# 啟動子程序並建立 stdio 連線
async with stdio_client(params, errlog=err) as (read, write):
async with ClientSession(read, write) as session:
# 呼叫工具...
```
### 3. 伺服器啟動並等待請求
```python
# server.py (第 162-172 行)
def main():
server = WeatherMCPServer()
server.run() # 啟動並監聽 stdio
```
## 🔍 啟動時序圖
```
Client Server
│ │
│ 1. call_tool("geocode_city") │
│─────────────────────────────→ │
│ │
│ 2. Launch subprocess │
│ python server.py │
│─────────────────────────────→ │
│ │
│ 📦 Loading module...
│ 🚀 Server Starting
│ ✅ Server ready
│ │
│ 3. Initialize session │
│←─────────────────────────────│
│ │
│ 4. List tools │
│←─────────────────────────────│
│ │
│ 5. Call tool │
│─────────────────────────────→│
│ │
│ 6. Return result │
│←─────────────────────────────│
│ │
│ 7. Close session & shutdown │
│ │
│ 💤 Server exits
```
## 📊 新增的啟動日誌
### 客戶端日誌 (stderr)
```
============================================================
🔌 Client launching MCP server
============================================================
📅 Time: 2025-10-02 12:09:53
🎯 Tool: geocode_city
📋 Args: {'city': 'Tokyo'}
🔖 Trace ID: trace_c1e7ff0c
📂 Server: /home/alex/projects/weather_mcp/src/weather_mcp/server.py
⏱️ Timeout: 30.0s
============================================================
```
### 伺服器日誌 (mcp_server.log)
```
📦 Loading weather-mcp-server module...
Called by: /home/alex/projects/weather_mcp/src/weather_mcp/server.py
============================================================
🚀 MCP Weather Server Starting
============================================================
📅 Time: 2025-10-02 12:09:54
🔢 PID: 66046
🐍 Python: /home/alex/projects/weather_mcp/.venv/bin/python
📂 Script: /home/alex/projects/weather_mcp/src/weather_mcp/server.py
🔧 Tools: geocode_city, get_weather, get_alerts
📡 Transport: stdio
============================================================
✅ Server ready - waiting for client requests...
============================================================
```
## 🔑 重要特性
### 1. 短生命週期
- ✅ 每次工具呼叫都會啟動新的伺服器實例
- ✅ 工具執行完成後,伺服器自動關閉
- ✅ 不需要手動管理伺服器生命週期
### 2. Stdio 通訊
- ✅ 透過標準輸入/輸出 (stdin/stdout) 通訊
- ✅ 日誌輸出到標準錯誤 (stderr)
- ✅ 日誌儲存在 `mcp_server.log`
### 3. 隔離性
- ✅ 每次呼叫使用獨立的伺服器程序
- ✅ 不同呼叫之間互不影響
- ✅ 避免狀態累積問題
## 📝 修改的檔案
### 1. `server.py` (第 137-172 行)
新增詳細的伺服器啟動日誌:
- 啟動時間
- 程序 PID
- Python 路徑
- 腳本位置
- 可用工具列表
- 傳輸協定
### 2. `client.py` (第 91-103 行)
新增客戶端啟動日誌:
- 啟動時間
- 呼叫的工具名稱
- 傳遞的參數
- Trace ID
- 伺服器路徑
- 超時設定
## 🧪 測試啟動日誌
### 方法 1: 直接測試
```python
import sys
sys.path.insert(0, 'src')
from weather_mcp import WeatherMCPClient
client = WeatherMCPClient()
result = client.geocode_city('Tokyo')
```
觀察 stderr 輸出和 `mcp_server.log` 檔案。
### 方法 2: 使用範例
```bash
python test_quick.py
```
會看到多次伺服器啟動訊息(每個工具呼叫一次)。
### 方法 3: 查看日誌檔
```bash
cat mcp_server.log
```
## 🔍 除錯技巧
### 1. 檢查伺服器是否啟動
```bash
# 執行任何客戶端操作
python -c "from weather_mcp import WeatherMCPClient; WeatherMCPClient().geocode_city('Tokyo')"
# 檢查日誌
cat mcp_server.log
```
### 2. 追蹤多次呼叫
```bash
# 清空日誌
> mcp_server.log
# 執行測試
python test_quick.py 2>&1 | grep -E "🔌|🚀|🎯"
# 查看完整日誌
cat mcp_server.log
```
### 3. 監控程序
```bash
# 在執行期間查看程序
python -c "import time; from weather_mcp import WeatherMCPClient; client = WeatherMCPClient(); print('Starting...'); result = client.geocode_city('Tokyo'); time.sleep(2); print(result)" &
# 快速查看 Python 程序
ps aux | grep "server.py"
```
## ⚙️ 自訂設定
### 修改伺服器腳本路徑
```python
client = WeatherMCPClient(server_script="path/to/custom_server.py")
```
### 調整超時時間
```python
client = WeatherMCPClient(timeout=60.0) # 60 秒
```
### 停用日誌(生產環境)
如需停用詳細日誌,可以修改:
**client.py**:
```python
# 註解掉第 91-103 行的日誌輸出
```
**server.py**:
```python
# 將第 146-157 行改為簡單訊息
print("Server starting...", file=sys.stderr)
```
## 📊 效能影響
- **啟動開銷**: 每次約 100-200ms
- **記憶體使用**: 約 30-50MB per instance
- **日誌大小**: 每次呼叫約 1-2KB
對於正常使用影響很小,但高頻呼叫時可考慮:
1. 批次處理工具呼叫
2. 實作長生命週期伺服器
3. 快取結果
## 📚 相關文件
- [MCP Specification](https://spec.modelcontextprotocol.io/)
- [FastMCP Documentation](https://github.com/jlowin/fastmcp)
- [client.py](../src/weather_mcp/client.py)
- [server.py](../src/weather_mcp/server.py)
---
**更新日期**: 2024-10-02
**狀態**: ✅ 已加入詳細啟動日誌