建構具故障防護能力的 MCP(Model Context Protocol)伺服器,避免 Agent 無限重試循環
Building Fail-Safe MCP (Model Context Protocol) Servers Without Runaway Agent Loops
MCP 工具若缺乏限制,可能令 stdio 串流損壞或觸發無限重試循環。文章建議在工具內捕捉錯誤並回傳結構化字串,限制結果數量最多為 50,並採用唯讀預設值,以免單次回應佔用過多 LLM 上下文窗口。
Model Context Protocol (MCP) makes it easy to connect Claude Desktop or Cursor to your local tools and APIs. However, poorly constrained MCP tools can crash stdio streams or trigger infinite retry loops.
1. Never Crash the Stdio Transport
In stdio MCP servers, uncaught exceptions or stray print() statements to stdout corrupt JSON-RPC framing. Always trap errors inside tools and return structured strings:
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("SafeToolServer")
@mcp.tool()
def query_records(keyword: str, limit: int = 10) -> str:
safe_limit = min(max(1, limit), 50)
try:
# Execute bounded read-only operation
return f"Found records for '{keyword}' (max {safe_limit})"
except Exception as exc:
return f"Tool error: {type(exc).__name__}"
2. Enforce Output Bounds & Read-Only Defaults
Clamp result limits (max 50) so a single tool response doesn't blow up the LLM context window in one turn.
Want Production-Ready .cursorrules & Boilerplates?
I'm a student developer in Japan funding my upcoming new life next spring by packaging strict, battle-tested AI coding setups:
-
Free Starter
.cursorrules& Reviewer Prompts ($0+): Download Free Starter Pack (or GitHub Repo) - Production AI Agent & MCP Suite ($19): Get Stack Kit
- All 10 Production Stacks Bundled ($99): 10-in-1 Ultimate Developer Suite
來源:DEV Community · dev.to