Skip to main content

Python SDKs (FastMCP 4, mcp v2) & Pydantic Contract Builder

Design one strict Python tool contract with Pydantic v2 that runs identically on Azure and GCP—and handles database crashes gracefully.

Design strict Pydantic v2 input/output models, compare FastMCP 4 decorators against low-level mcp v2 server primitives, and bind typed MCP contracts cleanly into Microsoft agent-framework or Google ADK.

Key Terms in This Lab:Python & SchemaFastMCP 4In plain English: Instead of hand-writing JSON-RPC boilerplate, you write normal async Python functions with @mcp.tool() and type hints. FastMCP 4 automatically generates the JSON Schema and serves stateless HTTP over ASGI.Analogy: Like FastAPI, but specifically built to turn Python functions into standard MCP tools.On Azure Stack: Runs inside an ASGI container on Azure Container Apps with stateless_http=True.Python & SchemaOfficial mcp Python SDK v2In plain English: When you need custom middleware, manual CallToolResult formatting, or fine-grained error handling, the official mcp v2 lowlevel Server gives you direct hooks for @server.list_tools() and @server.call_tool().Analogy: Manual transmission compared to FastMCP 4 automatic transmission—same engine, full gear control.On Azure Stack: Pairs cleanly with Microsoft Agent Framework (unlike legacy semantic-kernel[mcp] which pins mcp<2.0).Python & SchemaPydantic v2 BaseModel & FieldIn plain English: AI models sometimes pass malformed dates or missing IDs. Pydantic v2 lets you declare strict types, regex patterns, and length bounds (Field(pattern=..., min_length=...)) so bad inputs are caught immediately.Analogy: A strict bouncer with a checklist at the door—if the ID format fails, it never reaches the database.On Azure Stack: Validates Course/Student payloads on ACA before touching Azure Database for PostgreSQL.Python & SchemaJSON Schema Draft 2020-12In plain English: LLMs do not read your Python source code directly; they read the JSON Schema emitted by tools/list. Draft 2020-12 encodes exact types, regex patterns, min/max bounds, and required fields.Analogy: An order form with clearly labeled boxes ("YYYY-MM-DD", "4-digit ID") so nobody writes in the wrong format.On Azure Stack: Generated by Pydantic .model_json_schema() and consumed by Microsoft Agent Framework.Python & SchemaMCP ToolAnnotationsIn plain English: Flags like readOnlyHint, idempotentHint, and destructiveHint let gateways and AI hosts make smart safety choices—for example, auto-running read-only tools while pausing destructive tools for human approval.Analogy: Color-coded labels on buttons: green "View" vs. red "Delete/Update Grade" requiring a confirmation click.On Azure Stack: Used by Educator Gate middleware and APIM policies to guard mutating tools.Python & SchemaisError: true vs. JSON-RPC -32603In plain English: An unhandled Python exception sends JSON-RPC -32603 with a raw stack trace, causing the AI host to stall. Catching domain failures and returning HTTP 200 with isError: true and a retry hint lets the AI self-correct.Analogy: Saying "Out of large cups—try medium" (-recoverable) vs. pulling the fire alarm and shutting down the café (-32603).On Azure Stack: FastMCP tool catches asyncpg errors and returns retryHint to Microsoft Agent Framework.
Microsoft Azure Stack:
Microsoft agent-framework + Azure AI FoundryAzure Container Apps (KEDA)
Details
Agent Orchestrator SDK
Microsoft agent-framework + Azure AI Foundry

Typed Python agent orchestration binding FastMCP 4 and mcp v2 tool contracts.

GCP equivalent: Google ADK
Stateless MCP Compute
Azure Container Apps (KEDA)

Scale-to-zero stateless Python FastMCP 4 workers with HTTP concurrency triggers.

GCP equivalent: Cloud Run
Concept Escalator

1. Visual Analogy · Universal Shipping Container + Typed Customs Form

Intuition First
Start Here · Plain-English Concept Brief
~5 min

How do we stop an AI from passing invalid arguments—and stop Python crashes from stalling the AI?

An AI model calls your Python code by guessing JSON arguments from a schema. If your contract is sloppy, the AI guesses wrong. If your Python code throws an unhandled exception when Postgres is busy, the AI gets stuck. Strong Pydantic contracts plus recoverable isError: true replies solve both.

How this fits: This is Piece 2 (Contract). The tool name and Pydantic model you configure here automatically carry forward into Labs 4 (Guardrails) and 6 (Production Tracing).

  • Write the Python contract once—FastMCP 4 and official mcp v2 expose the exact same tool on Azure and GCP.
  • ToolAnnotations (readOnlyHint, idempotentHint) warn hosts before running state-changing operations.
  • Catch asyncpg database errors and return isError: true with a retryHint so the model recovers on its own.

Your portable Python MCP server (FastMCP 4 / official mcp v2) is a standardized shipping container, while Pydantic v2 Field rules form the typed customs manifest compiled to JSON Schema 2020-12. Both Microsoft Agent Framework and Google Python ADK v2 crane-lift the exact same container without repacking.

Engineering Takeaway: Strict BaseModel contracts validate arguments deterministically before touching asyncpg, while isError=True domain hints let host LLMs self-correct instead of stalling on -32603 tracebacks.
Quick Concept Check (Optional)

What happens when a Python MCP server catches a DB error and returns isError: true with a retryHint?

Step 1 of 3 ready? Move on to see how the pieces connect visually.

Engineering Scratchpad

Auto-saved per lab in mcp_foundry_v1_scratchpads

0 chars saved