内容
# MODPC MCP Server
将 Minecraft(modpc)的游戏能力封装为 MCP (Model Context Protocol) 工具,供 LLM Agent 调用,
让大模型能够直接驱动游戏内的玩家:移动、放置/破坏方块、召唤实体、操作 UI 等。
## 架构
```
LLM Agent ←──MCP over HTTP──→ modpc MCP Server ←──TCP Socket──→ 游戏端监听服务
(Claude 等) /mcp :3002 (本项目, Python 3) 4字节长度头+JSON (:14520, 由开发包提供)
```
本项目只是 **MCP ↔ 游戏** 之间的桥接层。真正的游戏能力由游戏端实现。
## 前置条件
- **Python 3.10+**
- **modpc 开发包**:安装并进入游戏(进入任意存档)后,游戏端会**自动开启 `14520` 端口的 Socket 监听**,
本服务连接该端口与游戏通信。若游戏未运行或未进入存档,调用工具会返回 `Cannot connect to game`。
## 安装
```bash
cd modpc_mcp_server
pip install -r requirements.txt
```
## 运行
```bash
# 默认:HTTP 监听 0.0.0.0:3002,游戏端 127.0.0.1:14520
python server.py
# 自定义端口
python server.py --game-port 14520 --http-port 3002
```
启动后,MCP 端点为 `http://<host>:3002/mcp`(Streamable HTTP 传输)。
可用参数:
| 参数 | 默认值 | 说明 |
|------|--------|------|
| `--game-host` | `127.0.0.1` | 游戏端 Socket 主机 |
| `--game-port` | `14520` | 游戏端 Socket 端口 |
| `--http-host` | `0.0.0.0` | MCP HTTP 监听地址 |
| `--http-port` | `3002` | MCP HTTP 监听端口 |
## 配置到 Coding / Agent 工具
本服务使用 **Streamable HTTP** 传输,先按上面的步骤把 server 跑起来,再在工具里配置 MCP 端点。
### Claude Code
```bash
claude mcp add --transport http modpc http://127.0.0.1:3002/mcp
```
或在项目 `.mcp.json` / 用户配置中手动添加:
```json
{
"mcpServers": {
"modpc": {
"type": "http",
"url": "http://127.0.0.1:3002/mcp"
}
}
}
```
### Cursor
编辑 `~/.cursor/mcp.json`(或项目内 `.cursor/mcp.json`):
```json
{
"mcpServers": {
"modpc": {
"url": "http://127.0.0.1:3002/mcp"
}
}
}
```
### 其他支持 MCP 的工具
任意支持 **MCP Streamable HTTP** 的客户端,填入端点 `http://127.0.0.1:3002/mcp` 即可。
配置完成后,工具里会出现 `get_doc` 和 `execute_script` 两个 MCP 工具。
## 使用教程
本服务对外暴露两个 MCP 工具,**使用顺序很重要**:
### 1. 先调 `get_doc`
`get_doc()` 返回完整的游戏 API 手册(所有可用函数、示例、编码规范)。
**在第一次 `execute_script` 之前必须先调用一次 `get_doc`**——否则 `execute_script` 会被拦截并提示你先读手册。
### 2. 再调 `execute_script`
`execute_script(code, timeout=120)` 向游戏端提交 Python 代码执行,是与游戏交互的唯一入口。
支持两种模式:
- **同步模式**(代码里没有 `yield`):立即执行,用 `print()` 返回信息。
- **协程模式**(代码里有 `yield`):定义一个 generator 函数,用 `yield` 等待异步操作
(寻路、破坏方块等)。游戏逐步执行,全部完成后一次性返回结果。
参数:
- `code` (string, 必填):要执行的 Python 代码
- `timeout` (number, 可选):协程模式最长等待秒数,默认 `120`
示例——同步查询:
```python
pos = get_position()
print("pos: %s" % str(pos))
inv = get_inventory()
print("inventory: %s" % str(inv))
```
示例——协程动作(寻路后破坏方块):
```python
def mine():
blocks = find_blocks("minecraft:grass_block", radius=16, max_results=1)
if not blocks:
print("no grass found")
return
bx, by, bz = blocks[0]["abs"]
yield navigate_to(bx, by, bz)
yield destroy_block(bx, by, bz)
print("done")
mine()
```
> 完整 API 列表、场景搭建规范与更多示例,请调用 `get_doc` 获取。
## 通信协议
与游戏端之间使用 TCP Socket,消息格式为 **4 字节大端序长度头 + JSON payload**。
消息类型:
- `execute_script` → 游戏端返回(含 `coroutine_id`,协程模式下需轮询)
- `poll_coroutine` → 轮询协程状态(`running` / `completed` / `failed`)
- `heartbeat` → `heartbeat_ack`(每 10 秒一次,维持连接)