Back to Skills

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.

pythonredisdeploymentrag
By secondsky
17928Updated 1 day agoTypeScriptMIT

Skill Content

# 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 server.py              # Development mode with hot reload
fastmcp run server.py              # Production mode
fastmcp deploy server.py           # Deploy to FastMCP Cloud
fastmcp test server.py             # Run tests
```

## Best Practices

1. **Server Structure**: Keep module-level server, organize tools in separate files
2. **Type Hints**: Use Pydantic models for complex validation
3. **Documentation**: Write detailed docstrings (LLMs read them!)
4. **Error Handling**: Catch and return structured errors
5. **Storage**: Use encrypted disk/Redis in production
6. **Lifespans**: Initialize connections once per server
7. **Middleware**: Order matters (error handling → timing → logging → rate limiting → caching)
8. **Testing**: Unit test tools with `FastMCP.test_tool()`

## Bundled Resources

**References** (`references/`):
- `cli-commands.md` - Complete CLI command reference (dev, run, deploy, test)
- `cloud-deployment.md` - FastMCP Cloud deployment guide with module-level requirements
- `common-errors.md` - All 25 documented errors with solutions and prevention
- `context-features.md` - Progress tracking, user input, and Context API patterns
- `error-catalog.md` - Comprehensive error catalog with fixes
- `integration-patterns.md` - Server composition (import/mount), OAuth Proxy, OpenAPI
- `production-patterns.md` - Storage backends, lifespans, middleware, architecture patterns

**Templates** (`templates/`):
- `basic-server.py` - Minimal MCP server with tools, resources, prompts
- `client-example.py` - MCP client integration examples
- `api-client-pattern.py` - API integration patterns
- `error-handling.py` - Error handling best practices
- `openapi-integration.py` - OpenAPI schema integration
- `prompts-examples.py` - Prompt template patterns
- `resources-examples.py` - Resource URI patterns and examples
- `tools-examples.py` - Tool definition patterns
- `self-contained-server.py` - Complete production-ready self-contained server
- `.env.example` - Environment variables template
- `requirements.txt` - Python dependencies
- `pyproject.toml` - Python project configuration

## Dependencies

```json
{
  "dependencies": {
    "fastmcp": ">=2.13.0",
    "pydantic": ">=2.0.0"
  },
  "optionalDependencies": {
    "py-key-value-aio": ">=0.1.0",  // For storage backends
    "cryptography": ">=41.0.0",     // For encryption
    "redis": ">=5.0.0"              // For Redis storage
  }
}
```

## Official Documentation

- FastMCP GitHub: https://github.com/jlowin/fastmcp
- MCP Protocol: https://modelcontextprotocol.io
- FastMCP Cloud: https://fastmcp.com

## Verification Checklist

- [ ] FastMCP installed (`fastmcp>=2.13.0`)
- [ ] Server object at module level
- [ ] Tool docstrings comprehensive
- [ ] Context type hints for context parameters
- [ ] Resource URIs have schemes
- [ ] Storage backend configured (production)
- [ ] Lifespan pattern correct (v2.13.0+)
- [ ] Middleware order logical
- [ ] Client configuration tested
- [ ] Production deployment successful

**Token Savings**: 90-95% vs learning from scratch
**Errors Prevented**: 25 documented issues
**Production Tested**: ✅ Multiple deployments

How to use

  1. Copy the skill content above
  2. Create a .claude/skills directory in your project
  3. Save as .claude/skills/claude-skills-fastmcp.md
  4. Use /claude-skills-fastmcp in Claude Code to invoke this skill

Claude Code Skills Collection

170 production-ready skills for Claude Code CLI

Version 3.3.1 | Last Updated: 2026-05-14

<div align="center">

🔌 Platform Support

This repository uses Claude Plugin Patterns — natively supported by:

PlatformStatusNotes
Claude CodeNativeFull marketplace support
Factory DroidNativeFull marketplace support
</div> **For all other Platforms like opencode, codex and others, you can use https://github.com/enulus/OpenPackage **

A curated collection of battle-tested skills for building modern web applications with Cloudflare, AI integrations, React, Tailwind, and more.

PS: if skills.sh warns about any skill: Their scan process is a outdated LLM which flags newest versions pins (like in ZOD) as non existent and by that potentially malicous.


Quick Start

Marketplace Installation (Recommended)

# Add the marketplace
/plugin marketplace add https://github.com/secondsky/claude-skills

# Install individual skills as needed
/plugin install cloudflare-d1@claude-skills
/plugin install tailwind-v4-shadcn@claude-skills
/plugin install ai-sdk-core@claude-skills

See MARKETPLACE.md for complete catalog of all 170 skills.

Bulk Installation (Contributors)

# Clone the repository
git clone https://github.com/secondsky/claude-skills.git
cd claude-skills

# Install all 170 skills at once
./scripts/install-all.sh

# Or install individual skills
./scripts/install-skill.sh cloudflare-d1

Repository Structure

This repository contains 170 production-tested skills for Claude Code, each focused on a specific technology or capability.

Individual Skills: Each skill is a standalone unit with:

  • SKILL.md - Core knowledge and guidance
  • Templates - Working code examples
  • References - Extended documentation
  • Scripts - Helper utilities

Installation Options:

  1. Individual - Install only the skills you need via marketplace
  2. Bulk - Install all 170 skills using ./scripts/install-all.sh

Available Skills (170 Individual Skills)

Each skill is individually installable. Install only the skills you need.

Full Catalog: See MARKETPLACE.md for detailed listings.

Categories

CategorySkillsExamples
tooling29turborepo, plan-interview, code-review
frontend26nuxt-v4, nuxt-v5, tailwind-v4-shadcn, tanstack-query, nuxt-studio, maz-ui, threejs
cloudflare21cloudflare-d1, cloudflare-workers-ai, cloudflare-agents
ai20openai-agents, claude-api, ai-sdk-core
api16api-design-principles, graphql-implementation
web10hono-routing, firecrawl-scraper, web-performance
mobile7swift-best-practices, react-native-app, react-native-skills
database6drizzle-orm-d1, neon-vercel-postgres, supabase-postgres-best-practices
security6csrf-protection, access-control-rbac
auth4better-auth
testing4vitest-testing, playwright-testing
design4design-review, design-system-creation
woocommerce4woocommerce-backend-dev
cms4hugo, sveltia-cms, wordpress-plugin-core
architecture3microservices-patterns, architecture-patterns
data3sql-query-optimization, recommendation-engine
seo2seo-optimizer, seo-keyword-cluster-builder
documentation1technical-specification

How It Works

Auto-Discovery

Claude Code automatically checks ~/.claude/skills/ for relevant skills before planning tasks:

User: "Set up a Cloudflare Worker with D1 database"
           ↓
Claude: [Checks skills automatically]
           ↓
Claude: "Found cloudflare-d1 skills.
         These prevent 12 documented errors. Use them?"
           ↓
User: "Yes"
           ↓
Result: Production-ready setup, zero errors, ~65% token savings

Note: Due to token limits, not all skills may be visible at once. See ⚠️ Important: Token Limits below.

Skill Structure

Each skill includes:

skills/[skill-name]/
├── SKILL.md              # Complete documentation
├── .claude-plugin/
│   └── plugin.json       # Plugin metadata
├── templates/            # Ready-to-copy templates
├── scripts/              # Automation scripts
└── references/           # Extended documentation

Recent Additions

May 2026

Supply Chain Security (cross-cutting):

  • dependency-upgrade expanded with Socket CLI integration — proactive malicious package detection, typosquatting alerts, and CI/CD security gates. New 418-line reference guide, 2 GitHub Actions templates, and expanded supply chain security comparison (3 tools)
  • 31 skills now include "Secure Installation" guidance — contextually-tailored security sections across all high-risk skill categories (scaffolding, MCP/agent SDKs, multi-provider installs, Docker, CI/CD). Covers 8 Bun skills, 5 Nuxt skills, 6 Cloudflare skills, 4 AI/agent skills, and 8 frontend/tooling skills
  • Supply chain security is now a first-class cross-cutting concern woven into the skill collection — not a standalone topic

February - April 2026

Full-Stack Frameworks:

  • nuxt-v5 (v1.0.0) - Full Nuxt 5 support with 4 skills (core, data, server, production), 3 diagnostic agents, and interactive setup wizard
  • supabase-postgres-best-practices - 30 Postgres optimization rules from Supabase across 8 categories
  • threejs (v1.0.0) - 3D web graphics: scenes, geometries, shaders, animations, post-processing

Infrastructure:

  • JSON schema validation - Automated plugin.json validation with CI support
  • GitHub issue templates - Skill-specific issue templates for bug reports, feature requests, and submissions

Plugin Enhancements:

  • mutation-testing - Added Bun native runner support
  • dependency-upgrade - Added supply chain security content

December 2025 - January 2026

Frontend Expansion:

  • nuxt-studio (v1.0.0) - Visual CMS for Nuxt Content with live preview, OAuth auth, and R2 storage integration
  • maz-ui (v1.0.0) - 50+ Vue/Nuxt components with theming, i18n, form generation, and 14 composables

Developer Workflow:

  • plan-interview (v2.0.0) - Adaptive interview-driven spec generation with autonomous quality review
  • turborepo (v2.8.0) - Updated to official Vercel skill with enhanced monorepo build optimization

Mobile Development:

  • react-native-skills (v1.0.0) - React Native & Expo best practices with performance optimization patterns

Enhanced Authentication:

  • better-auth (v2.2.0) - Expanded to 18 framework integrations with 30+ authentication plugins

⚠️ Important: Token Limits

Skill Visibility Constraint

Claude Code has a 15,000 character limit for the total size of skill descriptions in the system prompt. This limit also applies to commands and agents.

What this means:

  • Not all 170 skills may be visible in Claude's context at once
  • Skills are loaded based on relevance and available token budget
  • You can verify how many skills Claude currently sees by asking: "How many skills do you see in your system prompt?"

Checking Visible Skills

To verify which skills are currently loaded:

# Ask Claude Code directly
"Check what skills/plugins you see in your system prompt"

Claude will report something like: "85 of 170 skills visible due to token limits"

Workaround: Increase Token Budget

You can double the headroom for skill descriptions by setting an environment variable:

# Increase limit to 30,000 characters
export SLASH_COMMAND_TOOL_CHAR_BUDGET=30000

# Then launch Claude Code
claude

This gives you approximately 2x more skill visibility in the system prompt.

Note: This is a temporary workaround. The Claude Code team is working on better solutions for skill discovery and loading.


Token Efficiency

MetricManual SetupWith SkillsSavings
Average Tokens12,000-15,0004,000-5,000~65%
Typical Errors2-4 per service0 (prevented)100%
Setup Time2-4 hours15-45 minutes~80%

Across all 170 skills: 400+ documented errors prevented.


Contributing

Prerequisites for Contributors

Install the official plugin development toolkit:

/plugin install plugin-dev@claude-code-marketplace

This provides:

  • /plugin-dev:create-plugin command (8-phase guided workflow)
  • 7 comprehensive skills (hooks, MCP, structure, agents, commands, skills)
  • 2 specialized agents (agent-creator, plugin-validator)

Quick Steps

  1. Create skill directory in plugins/
  2. Add SKILL.md with YAML frontmatter
  3. Run ./scripts/sync-plugins.sh
  4. Submit pull request

See CONTRIBUTING.md and PLUGIN_DEV_BEST_PRACTICES.md for detailed guidelines.


Documentation

DocumentPurpose
START_HERE.mdStart here! Quick navigation guide
PLUGIN_DEV_BEST_PRACTICES.mdRepository-specific best practices (marketplace, budget, quality)
MARKETPLACE.mdFull skill catalog and installation guide
MARKETPLACE_MANAGEMENT.mdTechnical infrastructure (plugin.json, scripts, validation)
CLAUDE.mdProject context and development standards
CONTRIBUTING.mdContribution guidelines

Links


Built with ❤️ by Claude Skills Maintainers

View source on GitHub