本文介紹我如何使用 Python、FastAPI 實作一個 MCP Server,透過一個簡化的電子雞養成遊戲作為案例。主要目的是探索和學習 MCP Server 的功能,而非深入開發遊戲本身。因此,遊戲設計保持簡單,僅作為展示 MCP Server 應用的基礎。
背景與目標
MCP 是什麼? MCP 是一種開放協定,讓 AI 透過標準化方式與外部工具互動,存取所需的服務與數據,適合用於構建工具化的服務,透過定義工具(Tools)和資源(Resources)實現與 Client 端的互動。
本次我選擇以一個虛擬小雞養成遊戲為原型,來實作 MCP Server,旨在熟悉其架構和應用方式。該遊戲靈感源自電子雞(Tamagotchi),包含基本的狀態管理和玩家互動,但僅實現核心功能以支持學習目標。
本次目標:
- 利用 FastAPI 作為後端,開發遊戲所需 API,提供狀態儲存與更新。
- 開發遊戲用 MCP Server 存取遊戲所需的服務與數據。
- 使用 AI 搭配 MCP Server 提供前端互動介面,達成遊玩效果。
實作過程
環境設置與架構
本次選用 Python 作為開發語言,開始前確保本地已有 Python 3 環境。
專案分為兩個主要部分:
- tamagotchi.py:FastAPI 後端,負責資料管理和 API 端點。
- server.py:MCP Server,負責作為串接 AI 的命令處理與回應生成。
環境設置
1 2 3 4 5 6 7 8 9
| python3 -m venv tamagotchi-mcp-env
source tamagotchi-mcp-env/bin/activate
pip install fastapi uvicorn requests aiohttp mcp pip install "mcp[cli]"
|
FastAPI 遊戲功能實作
遊戲設計只加入了基本的養成元素:
- 屬性:飢餓、快樂、能量、健康、髒亂。
- 時間機制:根據 last_interaction 計算時間變化,增減各項屬性,如若超過 12 小時未互動,健康下降。
- 回應:簡單的遊戲化訊息。
FastAPI 後端負責管理小雞的狀態,並將資料儲存於 tamagotchi.json
文件檔案。
功能包括:
- 狀態初始化:建立初始小雞資料,預設名稱為「小雞」,從蛋階段開始。
- 狀態更新:根據時間差計算屬性變化,例如飢餓隨時間增加。
- 動作處理:支援基本的玩家動作,如餵食和改名。
核心程式碼如下(簡化版本):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| from fastapi import FastAPI import json import os from datetime import datetime
app = FastAPI() PET_FILE = "pet_state.json"
def init_pet(): if not os.path.exists(PET_FILE): default_pet = { "name": "小雞", "stage": "egg", "hunger": 0, "happiness": 0, "energy": 100, "health": 100, "mess": 0, "age": 0, "last_updated": datetime.now().isoformat(), "last_interaction": datetime.now().isoformat(), "last_event": "蛋正在孵化中...", "runaway": False } with open(PET_FILE, "w") as f: json.dump(default_pet, f)
@app.get("/pet/status") def get_pet_status(): init_pet() pet = json.load(open(PET_FILE, "r")) json.dump(pet, open(PET_FILE, "w")) return pet
@app.post("/pet/update") def update_pet_status(action: dict): init_pet() pet = json.load(open(PET_FILE, "r")) json.dump(pet, open(PET_FILE, "w")) return pet
|
後端啟動指令:
1
| uvicorn tamagotchi:app --host 0.0.0.0 --port 8000
|
MCP Server 的實作
MCP Server 是客戶端的互動介面,使用 FastMCP 類定義功能。我實現了以下工具和資源:
- get_pet_status:查詢小雞狀態。
- update_pet_status:處理玩家動作。
- set_pet_name:更改小雞名稱。
- get_game_instructions:提供簡要遊戲說明。
資源 (Resource)
- discovery://info:返回服務資訊和小雞狀態概覽。
MCP Server 程式碼(server.py)如下(簡化版本):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| from mcp.server.fastmcp import FastMCP import aiohttp
FASTAPI_BASE_URL = "http://localhost:8000" mcp = FastMCP("VirtualPetServer", description="A virtual chick game")
@mcp.tool() async def get_pet_status() -> dict: async with aiohttp.ClientSession() as session: async with session.get(f"{FASTAPI_BASE_URL}/pet/status") as response: pet_data = await response.json() return {"message": f"【{pet_data['name']}】\n狀態: ...", "data": pet_data}
@mcp.tool() async def update_pet_status(action: str, value: int = 20) -> dict: payload = {"action": action, "value": value} async with aiohttp.ClientSession() as session: async with session.post(f"{FASTAPI_BASE_URL}/pet/update", json=payload) as response: pet_data = await response.json() return {"message": f"【行動結果】\n{pet_data['last_event']}", "data": pet_data}
@mcp.resource("discovery://info") async def mcp_discovery() -> dict: async with aiohttp.ClientSession() as session: async with session.get(f"{FASTAPI_BASE_URL}/mcp/discovery") as response: base_info = await response.json() async with session.get(f"{FASTAPI_BASE_URL}/pet/status") as status_response: pet_data = await status_response.json() return { "message": f"歡迎來到 {pet_data['name']} 的世界!\n狀態概覽: ...", "technical_info": base_info }
if __name__ == "__main__": mcp.run()
|
配置 Claude Desktop
為了讓 MCP Server 與 AI 工具(如 Claude Desktop)整合,需要配置於 Claude Desktop 的設定檔中。以下是配置步驟:
- 編輯 Claude Desktop 配置檔案:
在 Claude Desktop 的設定檔,添加以下內容,將我們的 MCP Server 註冊為可用服務:
MacOS: ~/Library/Application Support/Claude/claude_desktop_config.json
Windows: %APPDATA%\Claude\claude_desktop_config.json
1 2 3 4 5 6 7 8
| { "mcpServers": { "tamagotchi-mcp-server": { "command": "/path/to/your/tamagotchi-mcp-server/tamagotchi-mcp-env/bin/python3", "args": ["/path/to/your/tamagotchi-mcp-server/server.py"] } } }
|
- command:指向虛擬環境中的 Python 可執行檔路徑。
- args:指定 MCP Server 的程式檔案路徑。
- 需將 /path/to/your/tamagotchi-mcp-server 替換為實際專案目錄。
- 啟動 Claude Desktop:
配置完成後,啟動 Claude Desktop,它會自動載入並運行 MCP Server,讓 AI 能夠透過命令與遊戲互動。
ps. 請注意,每次修改設定檔都必須要重啟 Claude Desktop 才會生效
實作成果
完成配置後,我可以透過 Claude Desktop 直接輸入這些自然語言指令,AI 會解析並呼叫對應的 MCP 工具,實現互動。
以下是支援的基本動作及其對應功能,包含:
- 「幫小雞取名字」:更改小雞名稱。
- 「查看小雞狀況」:查詢當前狀態。
- 「搖晃蛋」:加速蛋的孵化。
- 「餵小雞吃飯」:降低飢餓。
- 「跟小雞玩」:提升快樂。
- 「讓小雞休息」:恢復能量。
- 「幫小雞洗澡」:減少髒亂。
- 「帶小雞看醫生」:恢復健康。
- 「清理小雞的窩」:減少髒亂。
成果出來感覺還不錯,遊戲雖然簡單,但用來摸索 MCP 已經很夠用了,之後可以再來試點新東西。
GitHub 完整版:tamagotchi-mcp-server