This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: mcp-server-sdk-python

Python FastMCP Protocol & Tool Server Standard

Conventions for Python FastMCP servers: async tool definitions with @mcp.tool(), Pydantic v2 argument models, typed Context injection for client progress/logging, and clean shutdown handling.

Prohibited Anti-Pattern: AI uses print statements that corrupt stdout JSON-RPC, writes sync blocking handlers without threadpool delegation, or forgets Pydantic v2 field descriptions needed by LLM planners.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Python FastMCP Protocol & Tool Server Standard - Conventions for Python FastMCP servers: async tool definitions with @mcp.tool(), Pydantic v2 argument models, typed Context injection for client progress/logging, and clean shutdown handling.
globs: mcp_server/**/*.py, server.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/mcp-server-sdk-python"
---

# Python FastMCP Protocol & Tool Server Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: AI uses print statements that corrupt stdout JSON-RPC, writes sync blocking handlers without threadpool delegation, or forgets Pydantic v2 field descriptions needed by LLM planners.

## System Constraints
You are an expert Python engineer building MCP servers with FastMCP. Never use print statements in stdio servers; use sys.stderr.write or logging to a dedicated file to prevent corrupting JSON-RPC streams. Implement async def for all tool functions and decorate with @mcp.tool(). Provide explicit type annotations and Pydantic Field(description=...) descriptions on every argument so host LLMs can generate accurate tool calls without hallucinations.

## Strict Guidelines
- Never invoke built-in print(); stdout is exclusively reserved for JSON-RPC message framing. Log via sys.stderr or logging.getLogger().
- Equip all tool parameters with Pydantic Field(description=...) to ensure LLMs understand constraints and valid ranges.
- Inject Context into long-running tools to report progress and log structured messages directly back to the client host.
- Use anyio.to_thread.run_sync or asyncio.to_thread for any legacy CPU-intensive or blocking synchronous operations.

## Bad vs Good Implementations
### Async FastMCP Tool with Typed Context & Field Descriptions

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: print() outputs into the JSON-RPC pipe crashing the host client, and synchronous requests.get freezes server event handling.
```python
# Anti-pattern: print() corrupts stdio; sync requests blocks event loop; missing parameter docs
from mcp.server.fastmcp import FastMCP
import requests

mcp = FastMCP("demo")

@mcp.tool()
def search_catalog(query):
    print(f"Searching for {query}") # CRITICAL BUG: Corrupts stdio JSON-RPC stream
    # Blocking sync call freezes entire MCP server
    res = requests.get(f"https://internal-api/search?q={query}")
    return res.json()
```

#### Production Standard (Correct)
> **Standard**: Preserves JSON-RPC integrity, utilizes non-blocking async HTTP, informs the client via Context progress events, and documents parameters for LLM planners.
```python
# Production Standard: Async I/O, Context logging, rich Pydantic descriptions
import sys
import httpx
from pydantic import Field
from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("catalog-server")

@mcp.tool()
async def search_catalog(
    query: str = Field(..., description="Target keyword to search across internal documentation"),
    limit: int = Field(default=10, ge=1, le=50, description="Maximum number of search results to return"),
    ctx: Context = None,
) -> str:
    # Searches the company knowledge base for technical references
    if ctx:
        await ctx.info(f"Executing search for query='{query}' limit={limit}")
        await ctx.report_progress(0.2, 1.0)

    async with httpx.AsyncClient(timeout=10.0) as client:
        resp = await client.get("https://internal-api/search", params={"q": query, "limit": limit})
        resp.raise_for_status()
        data = resp.json()

    if ctx:
        await ctx.report_progress(1.0, 1.0)
    return str(data)
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Python FastMCP Protocol & Tool Server Standard

Python FastMCP Protocol & Tool Server Standard defines an industrial-grade behavioral standard for backend engineering. Conventions for Python FastMCP servers: async tool definitions with @mcp.tool(), Pydantic v2 argument models, typed Context injection for client progress/logging, and clean shutdown handling. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: AI uses print statements that corrupt stdout JSON-RPC, writes sync blocking handlers without threadpool delegation, or forgets Pydantic v2 field descriptions needed by LLM planners. Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftAI uses print statements that corrupt stdout JSON-RPC, writes sync blocking handlers without threadpool delegation, or forgets Pydantic v2 field descriptions needed by LLM planners.Critical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Never invoke built-in print()

Never invoke built-in print(); stdout is exclusively reserved for JSON-RPC message framing. Log via sys.stderr or logging.getLogger().

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Equip all tool parameters with Pydantic Field(description=...) to ensure LLMs understand constraints and valid ranges.

Equip all tool parameters with Pydantic Field(description=...) to ensure LLMs understand constraints and valid ranges.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Inject Context into long-running tools to report progress and log structured messages directly back to the client host.

Inject Context into long-running tools to report progress and log structured messages directly back to the client host.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Use anyio.to_thread.run_sync or asyncio.to_thread for any legacy CPU-intensive or blocking synchronous operations.

Use anyio.to_thread.run_sync or asyncio.to_thread for any legacy CPU-intensive or blocking synchronous operations.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Python FastMCP Protocol & Tool Server Standard critical for AI coding assistants?

Conventions for Python FastMCP servers: async tool definitions with @mcp.tool(), Pydantic v2 argument models, typed Context injection for client progress/logging, and clean shutdown handling. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (AI uses print statements that corrupt stdout JSON-RPC, writes sync blocking handlers without threadpool delegation, or forgets Pydantic v2 field descriptions needed by LLM planners.) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Python