MCP样品
用于扩展AI助手功能的模型上下文协议(MCP)服务器的Python实现。
概述
该项目提供了可以与Amazon Q或其他MCP兼容的AI助手一起使用的示例MCP服务器。服务器实现各种功能:
- 计算器服务器:执行基本算术运算
- RDS服务器:与Amazon RDS实例交互
- S3服务器:管理Amazon S3存储桶和对象
- PostgreSQL服务器:连接到PostgreSQL数据库并执行查询
这些服务器演示了如何使用FastMCP框架在Python中构建MCP服务器,该框架为实现模型上下文协议提供了一个高级的Python接口。
先决条件
- Python 3.12+
- FastMCP库
- uv(FastMCP的推荐Python包管理器)
- 为RDS和S3操作配置的AWS凭据(针对相应的服务器)
- 与MCP兼容的AI助手(如Amazon Q)
安装
克隆存储库并安装依赖项:
git clone
cd sample-building-mcp-servers-with-python我们建议使用 紫外线 安装依赖项,因为它比pip更快、更可靠:
# Install uv if you don't have it
curl -sSf https://install.python-poetry.org | python3 -
# Install dependencies with uv
uv pip install -r requirements.txt或者,您可以使用pip:
pip install -r requirements.txt用法
独立运行每台服务器:
# Run the calculator server
python src/calculator_server.py
# Run the RDS server
python src/rds_server.py
# Run the S3 server
python src/s3_server.py
# Run the PostgreSQL server (requires a connection string)
python src/postgresql_server.py "postgresql://username:password@hostname:port/database"与Amazon Q CLI集成
要将这些MCP服务器与Amazon Q CLI或其他MCP兼容客户端集成,请在您的 .amazon-q.json 文件:
{
"mcpServers": {
"calculator": {
"command": "python /path/to/sample-building-mcp-servers-with-python/src/calculator_server.py",
"args": []
},
"s3": {
"command": "python /path/to/sample-building-mcp-servers-with-python/src/s3_server.py",
"args": []
},
"rds": {
"command": "python /path/to/sample-building-mcp-servers-with-python/src/rds_server.py",
"args": []
},
"postgres": {
"command": "python /path/to/sample-building-mcp-servers-with-python/src/postgresql_server.py",
"args": ["postgresql://username:password@hostname:port/database"]
}
}
}替换 /path/to/sample-building-mcp-servers-with-python/ 了解项目的实际路径。配置后,Amazon Q将能够使用这些服务器来扩展其功能。
服务器描述
计算器服务器
提供基本的算术运算,如加法、减法、乘法和除法。
RDS服务器
列出并管理指定区域中的Amazon RDS实例。
S3服务器
管理S3存储桶和对象,包括按区域列出存储桶。
PostgreSQL服务器
连接到PostgreSQL数据库并执行只读查询、列出表并提供模式信息。
理解代码
每台服务器都遵循类似的模式:
- 创建FastMCP实例
- 使用定义工具
@mcp.tool()装饰器 - 使用以下命令运行服务器
mcp.run()
例如,计算器服务器看起来像这样:
from fastmcp import FastMCP
from typing import Annotated
from pydantic import Field
mcp = FastMCP("Calculator Server")
@mcp.tool()
def sum(
a: Annotated[int, Field(description="The first number")],
b: Annotated[int, Field(description="The second number")]
) -> int:
"""Calculate the sum of two numbers"""
return a + b
if __name__ == "__main__":
mcp.run()依赖项
- FastMCP:模型上下文协议的Python实现
- boto3:AWS Python SDK(适用于S3和RDS服务器)
- asyncpg:PostgreSQL客户端库(用于PostgreSQL服务器)
- pydantic:数据验证和设置管理
了解更多信息
要了解有关模型上下文协议和FastMCP的更多信息:
致谢
这个项目的灵感来自 使用rust构建mcp服务器的示例,它提供了使用Rust的MCP服务器的类似实现。我们感谢作者的工作和灵感。
