mcp-server-template
MCP Server Template
Plantilla genérica de servidor MCP — Plantilla de integración FastAPI + FastMCP.
¿Qué es esto?
Un punto de partida limpio para construir rápidamente un servicio MCP (Model Context Protocol).
MCP es el estándar de protocolo para que los modelos de IA llamen a herramientas externas. Esta plantilla te permite exponer cualquier funcionalidad como una herramienta invocable por IA con una configuración mínima.
你的业务代码 → MCP Server → AI 智能体(Cursor / Claude / 自定义应用)Related MCP server: Simple Remote MCP Server
Arquitectura
FastAPI(主容器)
├── CORS 中间件
├── 生命周期管理
├── FastAPI 路由(传统 HTTP)
└── FastMCP 子应用(MCP 协议)
└── @mcp.tool() 工具Características principales:
Un decorador = soporte simultáneo para protocolo MCP + interfaz HTTP
Múltiples módulos montados de forma independiente, sin interferencias entre sí
Registro, configuración e implementación Docker listos para usar
Inicio rápido
Requisitos previos
Python >= 3.12
Instalación
# 克隆模板
git clone <your-repo-url> my-mcp-server
cd my-mcp-server
# 安装依赖
uv sync
# 配置环境变量
cp .env-sample .envInicio
# 方式一:uvicorn(推荐)
uv run uvicorn app.main:app --reload
# 方式二:python
uv run python -m app.main
# 方式三:fastapi CLI
uv run fastapi dev app/main.pyVerificación
# HTTP 端点
curl http://127.0.0.1:8000/example/hello
# => "Hello, World! Running mcp-server-template v0.1.0"
# MCP 协议端点(返回 MCP 端点信息,非 404 即挂载成功)
curl http://127.0.0.1:8000/exampleEstructura del proyecto
mcp-server-template/
│
├── app/ # 应用主目录
│ ├── routers/ # MCP 工具 + FastAPI 路由
│ │ ├── example.py # 示例模块(供复制参考)
│ │ └── __init__.py
│ ├── utils/ # 工具函数
│ │ └── log.py # 日志(loguru)
│ ├── __init__.py
│ ├── config.py # 配置管理(pydantic-settings)
│ ├── dependencies.py # 依赖注入
│ └── main.py # 应用入口
│
├── docs/ # 文档
├── migrations/ # Alembic 数据库迁移(可选)
├── scripts/ # 开发脚本
├── tests/ # 测试
│
├── .env-sample # 环境变量模板
├── .gitignore
├── .python-version
├── alembic.ini
├── docker-compose.yaml
├── Dockerfile
├── pyproject.toml
└── README.mdAñadir un nuevo módulo de negocio
La plantilla incluye example.py como referencia. Para crear un nuevo módulo:
Copia
app/routers/example.pycomoapp/routers/your_module.pyModifica el contenido del módulo — cambia el nombre, el prefijo de ruta y escribe tus funciones de herramienta
Regístralo en
app/main.py
# app/main.py
from app.routers import your_module
from fastmcp.utilities.lifespan import combine_lifespans
your_module_app = your_module.mcp.http_app(path="/", stateless_http=True)
app.include_router(your_module.router)
app.mount("/your_module", app=your_module_app)
# 同时把 your_module_app.lifespan 合并进 FastAPI 的 lifespan:
# app = FastAPI(lifespan=combine_lifespans(lifespan, your_module_app.lifespan))Las funciones de herramienta pueden ser invocadas tanto por IA (a través de MCP) como por navegador (a través de HTTP):
@mcp.tool()
@router.get("/search")
async def search(query: str) -> list:
"""搜索知识库(此描述会暴露给 AI)"""
# 你的业务逻辑
return resultsPruebas
uv run pytest tests/ -vDespliegue con Docker
# 构建
docker build -t mcp-server:latest .
# 启动
docker compose up -dConfiguración
Toda la configuración se gestiona mediante variables de entorno o el archivo .env. Consulta .env-sample para más detalles.
Elementos de configuración clave:
Variable | Descripción | Por defecto |
| Entorno de ejecución |
|
| Dirección de escucha |
|
| Puerto de escucha |
|
| Conexión a base de datos (opcional) |
|
| Nivel de registro |
|
Referencias
This server cannot be deployed
Maintenance
Related MCP Connectors
Primarily to be used as a template repository for developing MCP servers with FastMCP in Python, P…
Nifty's MCP server — exposes tasks, projects, messages, and files as tools for AI agents.
MCP server for your apps' tools and custom tools, plus hosted AI agents and approval-gated workflows
MCP server for OpenAI API (chat completions, image generation, embeddings) via AceDataCloud
Related MCP Servers
- FlicenseNot gradedqualityFmaintenanceA production-ready MCP server built with FastAPI, providing an enhanced tool registry for creating, managing, and documenting AI tools for Large Language Models (LLMs).34-
- FlicenseBqualityDmaintenanceA template and demonstration project for building, testing, and deploying remote MCP servers using FastMCP and uv. It provides a foundational structure for creating MCP-compliant tools that can be hosted publicly and integrated with LLM agents.2-
- AlicenseNot gradedqualityDmaintenanceA bare-bones FastMCP server template designed to serve as a starting point for building custom Model Context Protocol servers. It provides a foundational structure for implementing tools over HTTP and includes a built-in health check utility.GPL 3.0
- FlicenseNot gradedqualityDmaintenanceA plugin-based MCP server built on FastAPI that supports dynamic tool loading, hot reloading, and API key authentication for extensible AI tool integrations.-