xiaohongshu
xiaohongshu
moai-connector-mcp
MCP 1.0+ Custom Server Development with FastMCP Framework
Full skill instructions
MCP Server Development Framework
What it does: Comprehensive guide to building, testing, and deploying custom MCP (Model Context Protocol) servers using FastMCP framework for exposing tools, resources, and prompts to Claude and other AI models.
Core Capabilities:
When to Use:
Installation:
pip install fastmcp
Minimum Server:
from fastmcp import FastMCP
server = FastMCP("my-server")
@server.tool()
def hello_world(name: str) -> str:
"""Greet someone."""
return f"Hello, {name}!"
if __name__ == "__main__":
server.run()
Core Concepts:
Detailed guide: getting-started.md
Three-Component Pattern:
┌─────────────────────────────────────────┐
│ MCP Server (FastMCP) │
├─────────────────────────────────────────┤
│ Tools (Functions) │
│ • @server.tool() decorator │
│ • Pydantic validation │
│ • Workflow-optimized naming │
│ │
│ Resources (Data Endpoints) │
│ • @server.resource("uri://...") decor │
│ • Streaming support │
│ • Permission-based access │
│ │
│ Prompts (Templates) │
│ • @server.prompt("name") decorator │
│ • Parameter injection │
│ • Multi-turn workflows │
└─────────────────────────────────────────┘
↓
MCP Protocol (JSON-RPC 2.0)
↓
┌─────────────────────────────────────────┐
│ Claude / LLM Client │
└─────────────────────────────────────────┘
Design Patterns: server-design.md
from fastmcp import FastMCP
from pydantic import Field
from typing import Literal, Optional
server = FastMCP("enterprise-database-server")
@server.tool()
def search_records(
query: str,
table: Literal["users", "products", "orders"],
limit: int = Field(default=10, ge=1, le=100),
filters: Optional[dict] = None
) -> dict:
"""
Search database records with pagination.
Args:
query: Search query string
table: Table to search
limit: Max results (1-100)
filters: Optional filter criteria
Returns:
Dict with results and metadata
"""
if not query or not query.strip():
raise ValueError("Query cannot be empty")
results = execute_search(query, table, limit, filters)
return {
"status": "success",
"count": len(results),
"results": results,
"total_available": get_total_count(query)
}
@server.resource("db://{table}/{id}")
def get_record(table: str, id: str) -> dict:
"""Fetch record by ID."""
record = fetch_record(table, id)
if not record:
raise ValueError(f"Record not found: {table}/{id}")
return record
if __name__ == "__main__":
server.run()
Implementation Guide: implementation.md
OAuth2 (User-Authenticated):
from fastmcp.auth import OAuth2Provider
oauth = OAuth2Provider(
authorize_url="https://auth.company.com/authorize",
token_url="https://auth.company.com/token",
scopes=["read:data", "write:data"]
)
@server.auth(oauth)
@server.tool()
def protected_action(user_id: str) -> dict:
"""Requires OAuth token."""
return execute_action(user_id)
API Key (Service-to-Service):
from fastmcp.auth import APIKeyAuth
api_auth = APIKeyAuth(header="X-API-Key")
@server.auth(api_auth)
@server.resource("secure://{resource_id}")
def secure_resource(resource_id: str) -> str:
"""Requires API key."""
return fetch_data(resource_id)
Detailed Patterns: auth-patterns.md
Unit Testing:
import pytest
from fastmcp import FastMCP
@pytest.fixture
def server():
s = FastMCP("test-server")
@s.tool()
def add(a: int, b: int) -> int:
return a + b
return s
def test_add_tool(server):
result = server.invoke_tool("add", {"a": 2, "b": 3})
assert result == 5
def test_invalid_params(server):
with pytest.raises(ValueError):
server.invoke_tool("add", {"a": "not-a-number", "b": 3})
Testing Guide: testing.md
Docker:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY server.py .
EXPOSE 8000
CMD ["python", "server.py"]
Kubernetes:
apiVersion: apps/v1
kind: Deployment
metadata:
name: mcp-server
spec:
replicas: 3
selector:
matchLabels:
app: mcp-server
template:
metadata:
labels:
app: mcp-server
spec:
containers:
- name: mcp-server
image: mcp-server:latest
ports:
- containerPort: 8000
livenessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 10
periodSeconds: 10
Deployment Guide: deployment.md
✅ DO:
❌ DON'T:
Tool Design Guide: tool-design.md
Caching Strategy:
from functools import wraps
from datetime import datetime, timedelta
class MCPCache:
def __init__(self, ttl_seconds=300):
self.cache = {}
self.ttl = ttl_seconds
def cached(self, func):
@wraps(func)
def wrapper(*args, **kwargs):
key = str((func.__name__, args, kwargs))
if key in self.cache:
value, timestamp = self.cache[key]
if (datetime.now() - timestamp).total_seconds() < self.ttl:
return value
result = func(*args, **kwargs)
self.cache[key] = (result, datetime.now())
return result
return wrapper
cache = MCPCache(ttl_seconds=600)
@cache.cached
def expensive_operation(param: str) -> dict:
return fetch_and_process(param)
Advanced Patterns:
Health Checks:
@server.resource("health://status")
def health_check() -> dict:
"""Server health status."""
return {
"status": "healthy",
"version": "1.0.0",
"uptime_seconds": get_uptime(),
"active_connections": get_connection_count()
}
Metrics & Logging:
import logging
import time
logger = logging.getLogger(__name__)
@server.tool()
def monitored_operation(params: dict) -> dict:
start = time.time()
try:
result = execute_operation(params)
duration = time.time() - start
logger.info(f"Operation completed in {duration:.2f}s")
return result
except Exception as e:
logger.error(f"Operation failed: {str(e)}")
raise
Monitoring Guide: monitoring.md
moai-context7-integration - Documentation access for API patternsmoai-cc-configuration - MCP server configuration managementmoai-essentials-debug - Server debugging and troubleshootingmoai-domain-backend - Backend service architecturemoai-domain-cloud - Cloud deployment patternsmoai-quality-security - Security validation and OWASP complianceGetting Started:
Core Development:
Deployment & Operations:
Advanced Patterns (modules/development/patterns/):
Status: Production Ready | See modules/development/ for detailed patterns | Last Updated: 2025-11-27
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience