MCP Server Cookiecutter Template
创建一个你自己的 Minecraft 服务器的简单易管理的方法: (Chuàngjiàn yī gè nǐ zìjǐ de Minecraft fúwùqì de jiǎndān yì guǎnlǐ de fāngfǎ:)
shubhamgupta-dat
README
MCP Server Cookiecutter 模板
一个全面的 Cookiecutter 模板,用于使用 Python 创建模型上下文协议 (MCP) 服务器。
什么是 MCP?
模型上下文协议 (MCP) 是一个开放标准,允许应用程序以标准化方式为大型语言模型 (LLM)(如 Claude)提供上下文。 MCP 服务器可以暴露:
- 工具 (Tools):LLM 可以执行以执行操作的函数
- 资源 (Resources):LLM 可以访问以获取上下文的数据源
- 提示词 (Prompts):用于 LLM 交互的可重用模板
特性
- 🚀 完整的项目结构,预配置了所有必要的组件
- 🔧 工具、资源和提示词的示例实现
- 📦 FastMCP 集成,用于简单的基于装饰器的开发
- 🧩 生命周期管理,具有适当的资源初始化和清理
- 🐍 现代 Python 实践,带有类型提示和文档
- 🛠️ 开发工具,包括 Makefile、测试和类型检查
- 🐋 Docker 支持,用于容器化部署
- 🔌 Claude Desktop 集成,用于与 Claude 进行无缝测试
快速开始
要求
- Python 3.12+
- Cookiecutter
创建项目
# 如果需要,安装 cookiecutter
pip install cookiecutter
# 从模板生成一个新的 MCP 服务器项目
cookiecutter gh:shubhamgupta-dat/mcp-server-cookiecutter
# 或者从本地副本
cookiecutter path/to/mcp-server-cookiecutter
开始使用您的新服务器
# 导航到您的新项目
cd your-project-name
# 设置环境 (底层使用 uv)
make setup
# 激活虚拟环境
source .venv/bin/activate # 在 Unix/MacOS 上
# 或
.venv\Scripts\activate # 在 Windows 上
# 在开发模式下使用 MCP Inspector 运行服务器
make dev
# 在 Claude Desktop 中安装服务器(用于本地测试)
make install
文件结构
mcp-server-template/
├── cookiecutter.json
└── {{cookiecutter.project_name}}/
├── README.md
├── Makefile
├── Dockerfile
├── .gitignore
├── pyproject.toml
└── {{cookiecutter.module_name}}/
├── __init__.py
├── server.py
├── config.py
├── tools/
│ ├── __init__.py
│ └── sample_tools.py
├── resources/
│ ├── __init__.py
│ └── sample_resources.py
└── prompts/
├── __init__.py
└── sample_prompts.py
文件内容
cookiecutter.json
{
"project_name": "mcp-server",
"module_name": "{{ cookiecutter.project_name.lower().replace('-', '_') }}",
"project_description": "A Model Context Protocol (MCP) server",
"author_name": "Your Name",
"author_email": "your.email@example.com",
"version": "0.1.0",
"python_version": "3.10"
}
{{cookiecutter.project_name}}/README.md
# {{cookiecutter.project_name}}
{{cookiecutter.project_description}}
## 概述
这是一个模型上下文协议 (MCP) 服务器,它公开了工具、资源和提示词,以便与 Claude 等 LLM 应用程序一起使用。 MCP 服务器允许您使用自定义功能、数据源和模板化交互来扩展 AI 应用程序。
## 快速开始
### 使用 uv 设置 (推荐)
```bash
# 设置环境
make setup
# 激活虚拟环境
source .venv/bin/activate # 在 Unix/MacOS 上
# 或
.venv\Scripts\activate # 在 Windows 上
# 在开发模式下使用 MCP Inspector 运行服务器
make dev
# 在 Claude Desktop 中安装服务器
make install
手动设置
# 如果您没有 uv,请安装它
pip install uv
# 创建一个虚拟环境
uv venv
# 激活虚拟环境
source .venv/bin/activate # 在 Unix/MacOS 上
# 或
.venv\Scripts\activate # 在 Windows 上
# 在开发模式下安装包
uv pip install -e .
# 在开发模式下运行
mcp dev {{cookiecutter.module_name}}.server
# 在 Claude Desktop 中安装
mcp install {{cookiecutter.module_name}}.server
Docker
使用 Docker 构建和运行:
# 构建 Docker 镜像
make docker-build
# 或
docker build -t {{cookiecutter.project_name}} .
# 运行容器
make docker-run
# 或
docker run -p 8000:8000 {{cookiecutter.project_name}}
服务器架构
服务器被组织成几个组件:
server.py
: 主要的 MCP 服务器设置和配置config.py
: 配置管理tools/
: 工具实现(LLM 可以执行的函数)resources/
: 资源实现(LLM 可以访问的数据)prompts/
: 提示词模板实现(可重用的对话模板)
MCP 特性
此服务器实现了所有三个 MCP 原语:
-
工具 (Tools):LLM 可以调用以执行操作的函数
- 示例:
calculate
、fetch_data
、long_task
- 示例:
-
资源 (Resources):为 LLM 提供上下文的数据源
- 示例:
static://example
、dynamic://{parameter}
、config://{section}
- 示例:
-
提示词 (Prompts):用于 LLM 交互的可重用模板
- 示例:
simple_prompt
、structured_prompt
、data_analysis_prompt
- 示例:
添加您自己的组件
添加新工具
在 tools/
目录中创建或修改文件:
@mcp.tool()
def my_custom_tool(param1: str, param2: int = 42) -> str:
"""
一个执行一些有用的自定义工具。
Args:
param1: 第一个参数的描述
param2: 带有默认值的第二个参数的描述
Returns:
返回值的描述
"""
# 在这里实现您的代码
return f"Result: {param1}, {param2}"
添加新资源
在 resources/
目录中创建或修改文件:
@mcp.resource("my-custom-resource://{param}")
def my_custom_resource(param: str) -> str:
"""
一个提供有用数据的自定义资源。
Args:
param: 参数的描述
Returns:
资源内容
"""
# 在这里实现您的代码
return f"Resource content for: {param}"
添加新提示词
在 prompts/
目录中创建或修改文件:
@mcp.prompt()
def my_custom_prompt(param: str) -> str:
"""
一个自定义提示词模板。
Args:
param: 参数的描述
Returns:
格式化的提示词
"""
return f"""
# 自定义提示词模板
Context: {param}
请回复您对上述上下文的分析。
"""
配置
服务器支持通过以下方式进行配置:
-
环境变量:以
MCP_
为前缀(例如,MCP_API_KEY=xyz123
)- 嵌套配置:使用双下划线 (
MCP_DATABASE__HOST=localhost
)
- 嵌套配置:使用双下划线 (
-
配置文件:通过
MCP_CONFIG_FILE
环境变量指定
示例配置:
{
"api": {
"key": "xyz123",
"url": "https://api.example.com"
},
"database": {
"host": "localhost",
"port": 5432
}
}
开发
# 运行测试
make test
# 格式化代码
make format
# 类型检查
make type-check
# 清理构建工件
make clean
许可证
[在此处包含您的许可证信息]
### {{cookiecutter.project_name}}/Makefile
```makefile
.PHONY: setup run dev install deploy test clean format type-check
# 从 cookiecutter 设置 Python 版本,或者默认为 3.10
PYTHON_VERSION := {{cookiecutter.python_version}}
# 使用 uv 设置
setup:
# 检查是否安装了 uv,如果没有安装则安装
@which uv >/dev/null || pip install uv
# 创建一个虚拟环境
uv venv
# 安装带有开发扩展的依赖项
uv pip install -e ".[dev]"
@echo "✅ 环境设置完成。使用 'source .venv/bin/activate' (Unix/macOS) 或 '.venv\\Scripts\\activate' (Windows) 激活它"
# 直接运行服务器
run:
python -m {{cookiecutter.module_name}}.server
# 在开发模式下使用 MCP inspector 运行
dev:
mcp dev {{cookiecutter.module_name}}.server
# 在 Claude Desktop 中安装
install:
mcp install {{cookiecutter.module_name}}.server
# 运行测试
test:
pytest
# 使用 black 和 isort 格式化代码
format:
black {{cookiecutter.module_name}}
isort {{cookiecutter.module_name}}
# 使用 mypy 检查类型
type-check:
mypy {{cookiecutter.module_name}}
# 清理构建工件
clean:
rm -rf build/
rm -rf dist/
rm -rf *.egg-info/
find . -type d -name __pycache__ -exec rm -rf {} +
find . -type f -name "*.pyc" -delete
# Docker 构建
docker-build:
docker build -t {{cookiecutter.project_name}}:latest .
# 使用 Docker 运行
docker-run:
docker run -p 8000:8000 {{cookiecutter.project_name}}:latest
{{cookiecutter.project_name}}/Dockerfile
# 使用特定的 Python 版本
FROM python:{{cookiecutter.python_version}}-slim AS builder
# 设置构建参数
ARG APP_USER=mcp
ARG APP_UID=1000
ARG APP_GID=1000
# 安装系统依赖项
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential \
&& rm -rf /var/lib/apt/lists/*
# 设置应用程序用户
RUN groupadd -g $APP_GID $APP_USER && \
useradd -m -u $APP_UID -g $APP_GID -s /bin/bash $APP_USER
# 设置工作目录
WORKDIR /app
# 安装 uv 以进行依赖项管理
RUN pip install --no-cache-dir uv
# 复制项目文件
COPY pyproject.toml README.md ./
# 复制应用程序代码
COPY {{cookiecutter.module_name}} ./{{cookiecutter.module_name}}
# 在开发模式下安装应用程序
RUN uv pip install --no-cache-dir -e .
# 切换到更小的最终镜像
FROM python:{{cookiecutter.python_version}}-slim
# 从 builder 复制
COPY --from=builder /usr/local/lib/python{{cookiecutter.python_version}}/site-packages /usr/local/lib/python{{cookiecutter.python_version}}/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin
COPY --from=builder /app /app
# 设置工作目录
WORKDIR /app
# 设置环境变量
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
ENV MCP_ENV=production
# 公开用于基于 HTTP 的传输(SSE)的端口
EXPOSE 8000
# 使用生产传输(SSE)运行服务器
CMD ["python", "-m", "{{cookiecutter.module_name}}.server"]
{{cookiecutter.project_name}}/.gitignore
# Python 字节码
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
# 分发/打包
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# 虚拟环境
venv/
env/
ENV/
.venv/
.env/
# 单元测试/覆盖率报告
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
pytest_cache/
# 编辑器文件
.idea/
.vscode/
*.swp
*.swo
*~
# 操作系统特定
.DS_Store
Thumbs.db
# 项目特定
*.log
.env
.env.*
!.env.example
# MCP 特定
claude_desktop_config.json
{{cookiecutter.project_name}}/pyproject.toml
[build-system]
requires = ["setuptools>=42", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "{{cookiecutter.project_name}}"
version = "{{cookiecutter.version}}"
description = "{{cookiecutter.project_description}}"
authors = [
{name = "{{cookiecutter.author_name}}", email = "{{cookiecutter.author_email}}"},
]
readme = "README.md"
requires-python = ">=3.10"
dependencies = [
"mcp>=1.0",
"httpx>=0.24.0",
]
[project.optional-dependencies]
dev = [
"pytest>=7.0",
"black>=23.0",
"isort>=5.0",
"mypy>=1.0",
"ruff>=0.2.0",
]
[tool.setuptools]
packages = ["{{cookiecutter.module_name}}"]
[tool.black]
line-length = 88
target-version = ["py310"]
[tool.isort]
profile = "black"
line_length = 88
[tool.mypy]
python_version = "3.10"
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
disallow_incomplete_defs = true
[tool.ruff]
line-length = 88
target-version = "py310"
select = ["E", "F", "I"]
{{cookiecutter.module_name}}/init.py
"""{{cookiecutter.project_description}}"""
__version__ = "{{cookiecutter.version}}"
{{cookiecutter.module_name}}/server.py
"""
主要的 MCP 服务器实现。
此文件初始化 FastMCP 服务器并导入所有工具、资源和提示词。
"""
from contextlib import asynccontextmanager
from collections.abc import AsyncIterator
from dataclasses import dataclass
from mcp.server.fastmcp import Context, FastMCP
# 导入配置管理
from .config import load_config
@dataclass
class AppContext:
"""
类型安全的应用程序上下文容器。
在此处存储任何应用程序范围的状态或连接。
"""
config: dict
@asynccontextmanager
async def app_lifespan(server: FastMCP) -> AsyncIterator[AppContext]:
"""
应用程序生命周期管理器。
使用适当的资源管理处理启动和关闭操作。
Args:
server: FastMCP 服务器实例
Yields:
带有已初始化资源的应用程序上下文
"""
# 加载配置
config = load_config()
# 初始化连接和资源
print("🚀 服务器启动中...")
try:
# 创建并生成应用程序上下文
yield AppContext(config=config)
finally:
# 在关闭时清理资源
print("🛑 服务器关闭中...")
# 创建具有生命周期支持的 MCP 服务器
mcp = FastMCP(
"{{cookiecutter.project_name}}", # 服务器名称
lifespan=app_lifespan, # 生命周期管理器
dependencies=["mcp>=1.0"], # 必需的依赖项
)
# 导入所有工具、资源和提示词
# 这些导入必须在 MCP 服务器初始化后进行
from .tools.sample_tools import *
from .resources.sample_resources import *
from .prompts.sample_prompts import *
# 使服务器实例可供其他模块访问
server = mcp
if __name__ == "__main__":
# 直接执行时,运行服务器
mcp.run()
{{cookiecutter.module_name}}/config.py
"""
MCP 服务器的配置管理。
处理从环境变量和/或配置文件加载配置。
"""
import os
import json
from pathlib import Path
from typing import Dict, Any, Optional
def load_config(config_path: Optional[str] = None) -> Dict[str, Any]:
"""
从环境变量和/或配置文件加载配置。
带有前缀 MCP_ 的环境变量会自动包含在配置中
(删除前缀并将名称小写)。
Args:
config_path: JSON 配置文件的可选路径
Returns:
包含配置值的字典
"""
# 从空配置开始
config = {
"server": {
"name": "{{cookiecutter.project_name}}",
"version": "{{cookiecutter.version}}"
}
}
# 如果提供,则从文件加载
if config_path:
config_file = Path(config_path)
if config_file.exists():
try:
with open(config_file, 'r') as f:
file_config = json.load(f)
# 深度合并配置
_deep_merge(config, file_config)
except Exception as e:
print(f"Warning: Failed to load config file: {e}")
# 还要检查来自环境的配置文件路径
env_config_path = os.environ.get("MCP_CONFIG_FILE")
if env_config_path and env_config_path != config_path:
try:
with open(env_config_path, 'r') as f:
file_config = json.load(f)
# 深度合并配置
_deep_merge(config, file_config)
except Exception as e:
print(f"Warning: Failed to load config file from environment: {e}")
# 使用环境变量覆盖(将 MCP_* 转换为配置条目)
env_config = {}
for key, value in os.environ.items():
if key.startswith('MCP_') and key != "MCP_CONFIG_FILE":
# 删除 MCP_ 前缀,转换为小写,并按双下划线分割
config_key_parts = key[4:].lower().split('__')
# 转换为嵌套字典
current = env_config
for part in config_key_parts[:-1]:
if part not in current:
current[part] = {}
current = current[part]
# 尝试将值转换为适当的类型
value = _convert_value(value)
# 设置值
current[config_key_parts[-1]] = value
# 合并环境配置
_deep_merge(config, env_config)
return config
def _convert_value(value: str) -> Any:
"""
尝试将字符串值转换为适当的类型。
Args:
value: 要转换的字符串值
Returns:
转换后的值
"""
# 处理布尔值
if value.lower() in ('true', 'yes', '1'):
return True
if value.lower() in ('false', 'no', '0'):
return False
# 处理 null
if value.lower() in ('null', 'none'):
return None
# 处理数字
try:
# 尝试作为 int
return int(value)
except ValueError:
try:
# 尝试作为 float
return float(value)
except ValueError:
# 保留为字符串
return value
def _deep_merge(target: Dict[str, Any], source: Dict[str, Any]) -> None:
"""
深度合并两个字典。
Args:
target: 要合并到的目标字典
source: 要从中合并的源字典
"""
for key, value in source.items():
if key in target and isinstance(target[key], dict) and isinstance(value, dict):
# 递归合并字典
_deep_merge(target[key], value)
else:
# 否则,只需覆盖该值
target[key] = value
{{cookiecutter.module_name}}/tools/init.py
"""MCP 工具包。"""
{{cookiecutter.module_name}}/tools/sample_tools.py
"""
示例 MCP 工具实现。
此文件包含示例工具实现,以演示不同的模式。
"""
from .. import server
from ..server import mcp, Context
import asyncio
@mcp.tool()
def echo(message: str) -> str:
"""
回显一条消息。
这是一个简单的示例工具,用于将消息回显给调用者。
Args:
message: 要回显的消息
Returns:
提供的同一条消息
"""
return f"Echo: {message}"
@mcp.tool()
async def calculate(a: float, b: float, operation: str = "add") -> float:
"""
对两个数字执行计算。
这是一个执行带有多个参数和默认值的计算的工具的示例。
Args:
a: 第一个数字
b: 第二个数字
operation: 要执行的操作(add、subtract、multiply、divide)
Returns:
计算结果
"""
if operation == "add":
return a + b
elif operation == "subtract":
return a - b
elif operation == "multiply":
return a * b
elif operation == "divide":
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
else:
raise ValueError(f"Unknown operation: {operation}")
@mcp.tool()
async def long_task(iterations: int, ctx: Context) -> str:
"""
一个报告进度的长时间运行的任务。
此示例演示如何使用 Context 对象在长时间运行的操作期间报告进度。
Args:
iterations: 要执行的迭代次数
ctx: Context 对象(自动注入)
Returns:
完成消息
"""
# 记录操作的开始
ctx.info(f"Starting long task with {iterations} iterations")
for i in range(iterations):
# 记录进度以进行调试
ctx.debug(f"Processing iteration {i+1}/{iterations}")
# 向客户端报告进度
await ctx.report_progress(
i,
iterations,
message=f"Processing iteration {i+1}/{iterations}"
)
# 模拟工作
await asyncio.sleep(0.1)
# 记录完成
ctx.info("Long task completed")
return f"Completed {iterations} iterations"
@mcp.tool()
async def fetch_data(url: str, ctx: Context) -> str:
"""
从 URL 获取数据。
此示例演示如何发出 HTTP 请求和处理错误。
Args:
url: 要从中获取数据的 URL
ctx: Context 对象(自动注入)
Returns:
获取的数据或错误消息
"""
import httpx
try:
# 记录请求
ctx.info(f"Fetching data from {url}")
# 发出 HTTP 请求
async with httpx.AsyncClient() as client:
response = await client.get(url, timeout=10.0)
response.raise_for_status()
# 返回响应文本
return response.text
except httpx.RequestError as e:
# 处理连接错误
error_msg = f"Connection error: {str(e)}"
ctx.error(error_msg)
return error_msg
except httpx.HTTPStatusError as e:
# 处理 HTTP 错误
error_msg = f"HTTP error {e.response.status_code}: {e.response.reason_phrase}"
ctx.error(error_msg)
return error_msg
except Exception as e:
# 处理意外错误
error_msg = f"Unexpected error: {str(e)}"
ctx.error(error_msg)
return error_msg
{{cookiecutter.module_name}}/resources/init.py
"""MCP 资源包。"""
{{cookiecutter.module_name}}/resources/sample_resources.py
"""
示例 MCP 资源实现。
此文件包含示例资源实现,以演示不同的模式。
"""
from .. import server
from ..server import mcp
import json
import datetime
@mcp.resource("static://example")
def static_resource() -> str:
"""
一个示例静态资源。
这演示了一个基本的静态资源,它始终返回相同的内容。
Returns:
静态内容
"""
return """
# 示例静态资源
这是一个静态资源的示例,它每次都返回相同的内容。
* 它可以包含 Markdown
* 带有列表
* 和其他格式
```python
# 甚至代码块
def hello():
return "world"
```
"""
@mcp.resource("dynamic://{parameter}")
def dynamic_resource(parameter: str) -> str:
"""
一个带有参数的示例动态资源。
这演示了如何创建带有动态 URI 的参数化资源。
Args:
parameter: 从 URI 提取的参数
Returns:
基于参数的内容
"""
return f"""
# 动态资源: {parameter}
此资源是使用参数生成的:**{parameter}**
当前时间:{datetime.datetime.now().isoformat()}
"""
@mcp.resource("config://{section}")
def config_resource(section: str) -> str:
"""
一个使用应用程序上下文的示例资源。
这演示了如何在资源中访问应用程序上下文。
Args:
section: 要返回的配置部分
Returns:
配置部分内容
"""
# 访问应用程序上下文
ctx = mcp.get_request_context()
config = ctx.lifespan_context.config
# 检查该部分是否存在
if section in config:
return f"""
# 配置: {section}
```json
{json.dumps(config[section], indent=2)}
```
"""
else:
return f"""
# 配置: {section}
未找到该部分。 可用部分:
{', '.join(config.keys()) if config else 'No configuration sections available'}
"""
@mcp.resource("file://{path}.md")
def file_resource(path: str) -> str:
"""
一个从文件系统读取的示例资源。
这演示了如何创建从文件系统读取的资源。
注意:在生产环境中,您应该验证路径并限制访问。
Args:
path: 文件路径
Returns:
文件内容
"""
import os
from pathlib import Path
# 为了安全起见,限制为一个子目录
base_dir = os.environ.get("RESOURCE_DIR", "resources")
file_path = Path(base_dir) / f"{path}.md"
# 验证路径(防止目录遍历)
if not file_path.is_file() or ".." in path:
return f"File not found: {path}.md"
# 读取并返回文件内容
try:
with open(file_path, "r", encoding="utf-8") as f:
return f.read()
except Exception as e:
return f"Error reading file: {str(e)}"
{{cookiecutter.module_name}}/prompts/init.py
"""MCP 提示词包。"""
{{cookiecutter.module_name}}/prompts/sample_prompts.py
"""
示例 MCP 提示词实现。
此文件包含示例提示词模板,以演示不同的模式。
"""
from .. import server
from ..server import mcp
from mcp.server.fastmcp.prompts import base
@mcp.prompt()
def simple_prompt(query: str) -> str:
"""
一个简单的文本提示词。
这演示了提示词的最简单形式,它返回一个字符串模板。
Args:
query: 用户的查询或输入
Returns:
格式化的提示词字符串
"""
return f"""
请提供以下问题的详细答案:
{query}
花时间逐步思考并提供全面的回复。
"""
@mcp.prompt()
def structured_prompt(code: str, language: str = "python") -> list[base.Message]:
"""
一个使用 Message 对象的更结构化的提示词。
这演示了如何创建带有序列中多个消息的结构化对话提示词。
Args:
code: 要审查的代码
language: 代码的编程语言
Returns:
提示词消息列表
"""
return [
base.UserMessage(f"我需要帮助审查此 {language} 代码:"),
base.UserMessage(f"```{language}\n{code}\n```"),
base.AssistantMessage("我将为您分析此代码。您希望我关注哪些特定方面?"),
base.UserMessage("请关注代码质量、潜在错误和性能问题。")
]
@mcp.prompt()
def data_analysis_prompt(data: str, objective: str) -> list[base.Message]:
"""
一个用于数据分析任务的提示词。
这演示了一个更复杂的数据分析提示词。
Args:
data: 要分析的数据
objective: 分析目标
Returns:
提示词消息列表
"""
return [
base.UserMessage("我需要帮助分析一些数据。"),
base.UserMessage(f"目标:{objective}"),
base.UserMessage("这是数据:"),
base.UserMessage(data),
base.UserMessage("请分析此数据并提供解决我的目标的见解。")
]
@mcp.prompt()
def image_analysis_prompt(image_description: str, analysis_type: str = "general") -> str:
"""
一个用于图像分析的提示词。
这演示了一个可以与图像数据一起使用的提示词。
Args:
image_description: 图像的描述
analysis_type: 要执行的分析类型
Returns:
格式化的提示词字符串
"""
analysis_instructions = {
"general": "提供对您在图像中看到的内容的一般描述和分析。",
"technical": "提供对图像的技术分析,重点关注构图、光照和使用的技术。",
"content": "分析图像的内容,识别对象、人物和活动。",
"sentiment": "分析图像的情绪和情感影响。"
}
instruction = analysis_instructions.get(
analysis_type,
analysis_instructions["general"]
)
return f"""
我正在向您展示一张带有以下描述的图像:
{image_description}
{instruction}
"""
使用说明
要使用此 cookiecutter 模板:
-
安装 Cookiecutter:
pip install cookiecutter
-
创建一个新项目: 使用此模板的本地副本或将其上传到 GitHub 并使用:
cookiecutter path/to/template/directory # 或者如果托管在 GitHub 上: cookiecutter gh:username/mcp-server-template
-
回答提示以自定义您的项目。
-
设置您的环境:
cd your-project-name make setup source .venv/bin/activate # 在 Unix/MacOS 上 # 或 .venv\Scripts\activate # 在 Windows 上
-
在开发模式下运行:
make dev
-
在 Claude Desktop 中安装:
make install
祝您构建 MCP 服务器愉快!
推荐服务器
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
MCP Package Docs Server
促进大型语言模型高效访问和获取 Go、Python 和 NPM 包的结构化文档,通过多语言支持和性能优化来增强软件开发。
Claude Code MCP
一个实现了 Claude Code 作为模型上下文协议(Model Context Protocol, MCP)服务器的方案,它可以通过标准化的 MCP 接口来使用 Claude 的软件工程能力(代码生成、编辑、审查和文件操作)。
@kazuph/mcp-taskmanager
用于任务管理的模型上下文协议服务器。它允许 Claude Desktop(或任何 MCP 客户端)在基于队列的系统中管理和执行任务。
mermaid-mcp-server
一个模型上下文协议 (MCP) 服务器,用于将 Mermaid 图表转换为 PNG 图像。
Jira-Context-MCP
MCP 服务器向 AI 编码助手(如 Cursor)提供 Jira 工单信息。

Linear MCP Server
一个模型上下文协议(Model Context Protocol)服务器,它与 Linear 的问题跟踪系统集成,允许大型语言模型(LLM)通过自然语言交互来创建、更新、搜索和评论 Linear 问题。

Sequential Thinking MCP Server
这个服务器通过将复杂问题分解为顺序步骤来促进结构化的问题解决,支持修订,并通过完整的 MCP 集成来实现多条解决方案路径。
Curri MCP Server
通过管理文本笔记、提供笔记创建工具以及使用结构化提示生成摘要,从而实现与 Curri API 的交互。