fastmcp
FastMCP Python framework for MCP servers with tools, resources, storage backends (memory/disk/Redis/DynamoDB). Use for Claude tool exposure, OAuth Proxy, cloud deployment, or encountering storage, lifespan, middleware, circular import, async errors.
What this skill does
# FastMCP - Build MCP Servers in Python
FastMCP is a Python framework for building Model Context Protocol (MCP) servers that expose tools, resources, and prompts to Large Language Models like Claude.
## Quick Start
### Installation
```bash
pip install fastmcp
# or: uv pip install fastmcp
```
### Minimal Server
```python
from fastmcp import FastMCP
# MUST be at module level for FastMCP Cloud
mcp = FastMCP("My Server")
@mcp.tool()
async def hello(name: str) -> str:
"""Say hello to someone."""
return f"Hello, {name}!"
if __name__ == "__main__":
mcp.run()
```
**Run:**
```bash
python server.py # Local development
fastmcp dev server.py # With FastMCP CLI
python server.py --transport http --port 8000 # HTTP mode
```
**Copy-Paste Template**: See `templates/basic-server.py`
## Core Concepts
### Tools
Functions that LLMs can call:
```python
@mcp.tool()
def calculate(operation: str, a: float, b: float) -> float:
"""Perform mathematical operations."""
operations = {
"add": lambda x, y: x + y,
"subtract": lambda x, y: x - y,
"multiply": lambda x, y: x * y,
"divide": lambda x, y: x / y if y != 0 else None
}
return operations.get(operation, lambda x, y: None)(a, b)
```
**Best Practices:**
- Clear, descriptive function names
- Comprehensive docstrings (LLMs read these!)
- Strong type hints (Pydantic validates automatically)
- Return structured data (dicts/lists)
- Handle errors gracefully
### Resources
Expose static or dynamic data:
```python
@mcp.resource("data://config")
def get_config() -> dict:
"""Provide application configuration."""
return {"version": "1.0.0", "features": ["auth", "api"]}
# Dynamic resource with parameters
@mcp.resource("user://{user_id}/profile")
async def get_user_profile(user_id: str) -> dict:
"""Get user profile by ID."""
return {"id": user_id, "name": f"User {user_id}"}
```
**URI Schemes**: `data://`, `file://`, `resource://`, `info://`, `api://`, or custom
### Prompts
Pre-configured prompts for LLMs:
```python
@mcp.prompt("analyze")
def analyze_prompt(topic: str) -> str:
"""Generate analysis prompt."""
return f"""Analyze {topic} considering:
1. Current state
2. Challenges
3. Opportunities
4. Recommendations"""
```
### Context Features
**Progress Tracking:**
```python
from fastmcp import Context
@mcp.tool()
async def batch_process(items: list, context: Context) -> dict:
"""Process items with progress updates."""
for i, item in enumerate(items):
await context.report_progress(i + 1, len(items), f"Processing {item}")
await process_item(item)
return {"processed": len(items)}
```
**User Input:**
```python
@mcp.tool()
async def confirm_action(action: str, context: Context) -> dict:
"""Perform action with user confirmation."""
confirmed = await context.request_elicitation(
prompt=f"Confirm {action}? (yes/no)",
response_type=str
)
return {"confirmed": confirmed.lower() == "yes"}
```
## Storage Backends
Choose storage based on deployment:
```python
from key_value.stores import DiskStore, RedisStore
from key_value.encryption import FernetEncryptionWrapper
from cryptography.fernet import Fernet
# Memory (default) - Development only
mcp = FastMCP("Dev Server")
# Disk - Single instance
mcp = FastMCP(
"Production Server",
storage=FernetEncryptionWrapper(
key_value=DiskStore(path="/var/lib/mcp/storage"),
fernet=Fernet(os.getenv("STORAGE_ENCRYPTION_KEY"))
)
)
# Redis - Multi-instance
mcp = FastMCP(
"Production Server",
storage=FernetEncryptionWrapper(
key_value=RedisStore(
host=os.getenv("REDIS_HOST"),
password=os.getenv("REDIS_PASSWORD")
),
fernet=Fernet(os.getenv("STORAGE_ENCRYPTION_KEY"))
)
)
```
## Server Lifespans
Initialize resources on server startup:
```python
from contextlib import asynccontextmanager
@asynccontextmanager
async def app_lifespan(server: FastMCP):
"""Runs ONCE when server starts (v2.13.0+)."""
db = await Database.connect()
print("Server starting")
try:
yield {"db": db}
finally:
await db.disconnect()
print("Server stopping")
mcp = FastMCP("My Server", lifespan=app_lifespan)
```
**Critical**: v2.13.0+ lifespans run per-server (not per-session). For per-session logic, use middleware.
## Middleware System
8 built-in middleware types:
```python
from fastmcp.middleware import (
LoggingMiddleware,
TimingMiddleware,
RateLimitingMiddleware,
ResponseCachingMiddleware
)
# Order matters!
mcp.add_middleware(LoggingMiddleware())
mcp.add_middleware(TimingMiddleware())
mcp.add_middleware(RateLimitingMiddleware(max_requests=100, window_seconds=60))
mcp.add_middleware(ResponseCachingMiddleware(ttl_seconds=3600))
```
**Custom Middleware:**
```python
from fastmcp.middleware import BaseMiddleware
class CustomMiddleware(BaseMiddleware):
async def on_call_tool(self, tool_name, arguments, context):
print(f"Before: {tool_name}")
result = await self.next(tool_name, arguments, context) # MUST call next()
print(f"After: {tool_name}")
return result
```
## Server Composition
**Import Server** (static, one-time copy):
```python
main_server.import_server(vendor_server) # Static bundle
```
**Mount Server** (dynamic, runtime delegation):
```python
main_server.mount(api_server, prefix="api") # Changes appear immediately
```
## Cloud Deployment
**FastMCP Cloud Requirements:**
1. Server MUST be at module level
2. Use disk/Redis storage (not memory)
3. No import-time execution
```python
# ✅ Cloud-ready pattern
mcp = FastMCP("My Server") # Module level
@mcp.tool()
async def my_tool(): pass
if __name__ == "__main__":
mcp.run()
```
**Deploy:**
```bash
fastmcp deploy server.py
```
## Top 5 Critical Errors
### 1. Missing Server Object
**Error:** `RuntimeError: No server object found at module level`
**Fix:**
```python
# ❌ WRONG
def create_server():
return FastMCP("server")
# ✅ CORRECT
mcp = FastMCP("server") # At module level
```
### 2. Async/Await Confusion
**Error:** `RuntimeError: no running event loop`
**Fix:**
```python
# ❌ WRONG: Sync function calling async
@mcp.tool()
def bad_tool():
result = await async_function() # Error!
# ✅ CORRECT: Async tool
@mcp.tool()
async def good_tool():
result = await async_function()
return result
```
### 3. Context Not Injected
**Error:** `TypeError: missing 1 required positional argument: 'context'`
**Fix:**
```python
from fastmcp import Context
# ❌ WRONG: No type hint
@mcp.tool()
async def bad_tool(context): # Missing type!
await context.report_progress(...)
# ✅ CORRECT: Proper type hint
@mcp.tool()
async def good_tool(context: Context):
await context.report_progress(0, 100, "Starting")
```
### 4. Storage Backend Not Configured
**Error:** `RuntimeError: OAuth tokens lost on restart`
**Fix:** Use disk or Redis storage in production (see Storage Backends section above)
### 5. Circular Import Errors
**Error:** `ImportError: cannot import name 'X' from partially initialized module`
**Fix:**
```python
# ❌ WRONG: Factory function creating circular dependency
# shared/__init__.py
def get_client():
from .api_client import APIClient # Circular!
return APIClient()
# ✅ CORRECT: Direct imports
# shared/__init__.py
from .api_client import APIClient
from .cache import CacheManager
# shared/monitoring.py
from .api_client import APIClient
client = APIClient()
```
**See all 25 errors**: `references/error-catalog.md`
## Client Configuration
### Claude Desktop
```json
{
"mcpServers": {
"my-server": {
"command": "python",
"args": ["/path/to/server.py"]
}
}
}
```
### Claude Code CLI
```json
{
"mcpServers": {
"my-server": {
"command": "python",
"args": ["server.py"]
}
}
}
```
## CLI Commands
```bash
fastmcp dev servRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.