跳转到主要内容
模型上下文协议 (MCP) 由两个通过 HTTP 或 stdio 通信的进程组成。以下是调试它们的方法。

tmux 模式

在分屏终端中同时运行服务器和 Client:
tmux new-session -d -s mcp
tmux split-window -h
tmux send-keys -t mcp:0.0 'python server.py' C-m
sleep 2
tmux send-keys -t mcp:0.1 'python client.py' C-m
tmux attach -t mcp
并排查看两个输出。完成后结束该会话:tmux kill-session -t mcp

结构化日志

在 tool 内部记录日志:
from dedalus_mcp import get_context, tool

@tool(description="Process data")
async def process(data: str) -> dict:
    ctx = get_context()
    await ctx.debug("Starting", data={"length": len(data)})
    # ... 执行工作 ...
    await ctx.info("Done", data={"result": 42})
    return {"ok": True}

详细日志模式

await server.serve(verbose=True, log_level="debug")
或通过环境变量:
LOG_LEVEL=debug python server.py

客户端日志采集

from dedalus_mcp.client import MCPClient, ClientCapabilitiesConfig

def log_handler(params):
    print(f"[{params.level}] {params.data}")

config = ClientCapabilitiesConfig(logging=log_handler)
client = await MCPClient.connect(url, capabilities=config)

常见问题

“Client does not advertise the sampling capability” 传入一个采样处理程序:
config = ClientCapabilitiesConfig(sampling=sampling_handler)  # 配置客户端能力
client = await MCPClient.connect(url, capabilities=config)
“在服务器启动后尝试修改工具” 启用动态工具:
server = MCPServer("my-server", allow_dynamic_tools=True)
连接被拒绝 检查端口:lsof -i :8000 结束占用端口的孤立进程:lsof -ti :8000 | xargs kill -9 错误的 URL 正确的端点是 http://127.0.0.1:8000/mcp,而不只是 :8000

遇到卡住时

  1. 缩减为最小可复现示例
  2. 检查是否符合模型上下文协议(MCP)规范
  3. 使用 MCP Inspector 进行测试:npx @anthropic/mcp-inspector
  4. 查看服务器日志