SkilVaultSign inStart free

Catalogue / python-mcp-server-playbook

python-mcp-server-playbook

Older skill: source not recordedSignedDesigns, codes, tests and ships Model Context Protocol servers in Python on the FastMCP library — choosing tools, resources and prompts, wrapping existing HTTP APIs (by hand, from an OpenAPI document, or from a FastAPI app), using context features such as progress and user prompts, running the CLI,…
---
name: python-mcp-server-playbook
description: Designs, codes, tests and ships Model Context Protocol servers in Python on the FastMCP library — choosing tools, resources and prompts, wrapping existing HTTP APIs (by hand, from an OpenAPI document, or from a FastAPI app), using context features such as progress and user prompts, running the CLI, writing client-driven tests, and diagnosing the usual startup, schema, transport and import failures. Use when a user wants to build, extend, debug or deploy a Python MCP server. Do not use for MCP servers written in TypeScript or other languages, for plain REST services with no MCP layer, or for configuring an MCP client unrelated to server code.
---

Python MCP Server Playbook

A working method for turning "I want an assistant to be able to do X" into a tested FastMCP server, plus a reference of the patterns and fixes that come up repeatedly.

1. Intake: what to settle before coding

Ask (or infer and confirm) five things, in one short message:

  1. Which actions should the assistant be able to *perform* (these become tools)?
  2. Which information should it be able to *read* (these become resources)?
  3. Are there repeatable instruction templates worth shipping (these become prompts)?
  4. Where will it run: a local process driven by a desktop client over stdio, or a network service over HTTP?
  5. Does it call an upstream service? If so, how does that service authenticate, and does it publish an OpenAPI document?

A one-line brief such as "let the assistant check out equipment from our community tool library" is enough to begin. State your reading back to the user before building.

2. Project skeleton and dependencies

tool-library-mcp/
├── server.py            # entry file, server object lives here
├── requirements.txt     # registry-published packages only
├── .gitignore           # must exclude the local environment file
└── tests/smoke_client.py

Typical requirements.txt (pin to what you actually tested):

fastmcp>=2.12.0
httpx>=0.27.0
python-dotenv>=1.0.0
pydantic>=2.0.0
psutil>=5.9.0        # only if you expose host health numbers

Optional extras, only when needed: a key-value storage package for persistence (with redis, boto3, pymongo or elasticsearch for those backends), cryptography for encrypting stored tokens, and pytest, pytest-asyncio, ruff, mypy for development. A pyproject.toml for a packaged server needs requires-python = ">=3.10", the dependency list, an optional dev group, ruff/mypy settings, and asyncio_mode = "auto" under the pytest options.

Install with pip install fastmcp (or uv pip install fastmcp) and confirm with fastmcp --version. Ask before installing into an environment the user did not create for this task.

3. The three primitives

from datetime import datetime, timezone
from fastmcp import FastMCP

mcp = FastMCP(
    name="Tool Library",
    instructions="Lend, find and track shared workshop equipment.",
)

@mcp.tool()
async def find_tools(query: str, category: str | None = None, limit: int = 10) -> dict:
    """Search the equipment catalog by keyword, optionally within one category."""
    return {"query": query, "category": category, "limit": limit, "matches": []}

@mcp.resource("library://hours")
def opening_hours() -> dict:
    """Static facts: when the library is staffed."""
    return {"weekdays": "16:00-20:00", "saturday": "10:00-14:00"}

@mcp.resource("tool://{tool_id}/status")
async def tool_status(tool_id: str) -> dict:
    """Template resource: availability of one item."""
    return {"tool_id": tool_id, "checked_at": datetime.now(timezone.utc).isoformat()}

@mcp.prompt("overdue_notice")
def overdue_notice(member_name: str, days_late: int) -> str:
    """Reusable text the user can invoke from the client."""
    return f"Draft a polite reminder to {member_name}, whose loan is {days_late} days overdue."

if __name__ == "__main__":
    mcp.run()          # stdio by default

Choosing between them:

  • Tool — the assistant takes an action or runs a computation. Sync (def) and async (async def) both work; prefer async whenever I/O is involved.
  • Resource — read-only data addressed by a URI. Static (fixed URI), dynamic (recomputed on each read) or a template (scheme://{param}/…). List-style resources may return a list.
  • Prompt — a function returning text (optionally parameterised) that a user can pick from the client's menu.

4. Rules that prevent most failures

  1. Create the server object at import scope. Hosting platforms import your file and look for a variable named mcp, server or app. A factory is fine only if its result is assigned to a top-level name (mcp = build_server()); returning the object from a function that is called inside __main__ is invisible to the host.
  2. Annotate every parameter. The tool's JSON schema is generated from type hints, and the docstring becomes its description. Optional parameters need defaults.
  3. Resource URIs need a scheme (data://, file://, info://, api://, or your own such as library://). Template placeholders must match the function's parameter names exactly.
  4. Return JSON-safe values. Convert datetime with .isoformat(), NumPy arrays with .tolist(), frames with .to_dict(); do not return bytes or custom class instances.
  5. Do not do async work at import time. No event loop exists yet. Build connections lazily inside the first call.
  6. Never block the loop. Use await asyncio.sleep(), not time.sleep(); use async HTTP clients.
  7. Avoid shared mutable globals. A bare module-level list that tools append to invites race conditions; use a lock-protected manager (section 6).
  8. Prefer returned error text or structured error dicts over raised exceptions for expected failures, so the client sees a readable message rather than an opaque failure.
  9. Read configuration through `os.getenv` — the old mcp.settings accessor was removed in v2.
  10. Keep helpers in one importable module, or in the entry file. Factory functions inside a package __init__.py create circular imports that surface only on hosted platforms; import classes directly instead.
  11. Use timezone-aware timestamps (datetime.now(timezone.utc)); datetime.utcnow() is deprecated from Python 3.12.

5. Tool design patterns

Validated inputs

from pydantic import BaseModel, Field, field_validator

class LoanQuery(BaseModel):
    member_id: str = Field(min_length=3, max_length=40)
    status: str = Field(default="open", description="open, returned or overdue")
    limit: int = Field(default=20, ge=1, le=100)

    @field_validator("member_id")
    @classmethod
    def trim(cls, v: str) -> str:
        return v.strip()

@mcp.tool()
async def list_loans(params: LoanQuery) -> dict:
    """List a member's loans, validated before the body runs."""
    return {"member": params.member_id, "status": params.status, "loans": []}

Type mismatches otherwise surface as a validation error: fix the annotation or switch to a model.

Structured results and errors

from enum import Enum

class Code(Enum):
    VALIDATION = "VALIDATION_ERROR"
    NOT_FOUND = "NOT_FOUND"
    UNAUTHORIZED = "UNAUTHORIZED"
    RATE_LIMITED = "RATE_LIMITED"
    UPSTREAM = "API_ERROR"
    TIMEOUT = "TIMEOUT"
    NETWORK = "NETWORK_ERROR"
    UNKNOWN = "UNKNOWN_ERROR"

def ok(data, message="ok"):
    return {"success": True, "message": message, "data": data,
            "timestamp": datetime.now(timezone.utc).isoformat()}

def fail(code: Code, message: str, details: dict | None = None):
    return {"success": False,
            "error": {"code": code.value, "message": message, "details": details or {}},
            "timestamp": datetime.now(timezone.utc).isoformat()}

Return fail(Code.VALIDATION, "member_id is required", {"field": "member_id"}) for bad input, and wrap the body of any tool that touches the network or disk in try/except, mapping each exception family to a code. Reject obviously dangerous input at the tool boundary (for example, refuse write or schema-changing SQL in a query tool) rather than trusting the caller.

Batches that tolerate partial failure

import asyncio

@mcp.tool()
async def reserve_many(tool_ids: list[str], member_id: str) -> dict:
    """Try each reservation independently and report per-item outcomes."""
    async def one(tid: str):
        try:
            return {"tool_id": tid, "success": True, "result": await reserve(tid, member_id)}
        except Exception as exc:
            return {"tool_id": tid, "success": False, "error": str(exc)}

    results = await asyncio.gather(*(one(t) for t in tool_ids))
    done = sum(r["success"] for r in results)
    return {"total": len(results), "succeeded": done, "failed": len(results) - done, "results": results}

Resilience toolkit for upstream calls

import asyncio, os
import httpx

class Upstream:
    """One pooled HTTP client, created on first use and closed on shutdown."""
    _client: httpx.AsyncClient | None = None

    @classmethod
    async def get(cls) -> httpx.AsyncClient:
        if cls._client is None:
            cls._client = httpx.AsyncClient(
                base_url=os.getenv("UPSTREAM_URL", ""),
                timeout=httpx.Timeout(30.0),
                limits=httpx.Limits(max_keepalive_connections=5, max_connections=10),
            )
        return cls._client

    @classmethod
    async def close(cls):
        if cls._client:
            await cls._client.aclose()
            cls._client = None

async def with_retries(call, attempts=3, delay=1.0, factor=2.0):
    """Retry transient network failures with exponentially growing pauses."""
    last = None
    for n in range(attempts):
        try:
            return await call()
        except (httpx.TimeoutException, httpx.NetworkError) as exc:
            last = exc
            if n < attempts - 1:
                await asyncio.sleep(delay)
                delay *= factor
    raise last

Other building blocks worth reaching for:

  • TTL cache: store (value, timestamp) per key, expire after CACHE_TTL seconds, offer invalidate(pattern=None), and surface a from_cache flag plus a small clear_cache tool and a cache-stats resource. Skip caching for real-time data.
  • Sliding-window rate limiter: keep a deque of request times; when the window is full, sleep until the oldest entry expires. Use it when the upstream publishes limits.
  • Locked state: a manager holding a dict plus one asyncio.Lock per key, with an update(key, fn) method, replaces ad-hoc globals.
  • Lazy resource manager: a class whose get_db() / get_cache() create the pool on first call.
  • Environment profiles: an enum (development, staging, production) selecting cache TTL, debug flag and log level from one config class.
  • Parallel batch fetch: asyncio.gather over per-endpoint helpers that each catch their own errors.
  • Health resource: expose health://status returning an overall healthy / degraded flag, upstream reachability, optional database ping, and (if psutil is installed) memory and CPU percentages; degrade above roughly 90%.
  • Server-wide config class: read name, version, base URL, credentials, cache TTL and retry count from the environment in one place and validate required values at startup.

Always say in the tool docstring when a tool changes data. Any tool that deletes, overwrites or sends something outside the system should require an explicit confirmation argument or an elicitation step (section 6) and must only be exposed if the user asked for that capability.

6. Context features: progress, user prompts, model sampling

Inject the context by annotating a parameter with the Context type — without the annotation, injection does not happen and the call fails with a missing-argument error.

Preview shortened. The full SKILL.md is in the pack.