Python MCP Server
生成一个 Python Model Context Protocol (MCP) 服务器,用于向大型语言模型 (LLM) 提供上下文,并可选择将其部署到 Amazon Bedrock AgentCore。
什么是 MCP?
Section titled “什么是 MCP?”Model Context Protocol (MCP) 是一个开放标准,允许 AI 助手与外部工具和资源进行交互。它为 LLM 提供了一种一致的方式来:
- 执行工具(函数)以执行操作或检索信息
- 访问提供上下文或数据的资源
生成 MCP Server
Section titled “生成 MCP Server”您可以通过两种方式生成 Python MCP 服务器:
pnpm nx g @aws/nx-plugin:py#mcp-serveryarn nx g @aws/nx-plugin:py#mcp-servernpx nx g @aws/nx-plugin:py#mcp-serverbunx nx g @aws/nx-plugin:py#mcp-server- 安装 Nx Console VSCode Plugin 如果您尚未安装
- 在VSCode中打开Nx控制台
- 点击
Generate (UI)在"Common Nx Commands"部分 - 搜索
@aws/nx-plugin - py#mcp-server - 填写必需参数
- 点击
Generate
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| project 必需 | string | - | 要添加 MCP 服务器的项目 |
| name | string | - | MCP 服务器的名称(默认:mcp-server) |
| auth | iam | cognito | iam | 用于对 MCP 服务器进行身份验证的方法。仅在设置了 infra 时适用(当 infra 为 none 时忽略)。 |
| iac | inherit | cdk | terraform | inherit | 首选的 IaC 提供商。默认情况下,这继承自您的初始选择。 |
| infra | agentcore | none | agentcore | 托管 MCP 服务器的基础设施类型。选择 none 表示不托管。 |
| preferInstallDependencies | boolean | true | 是否在生成器运行后优先安装依赖项。设置为 false 可在批量运行多个生成器时延迟安装(如果后续生成器需要计算 Nx 项目图,仍会运行安装);在最后统一安装一次。 |
生成器将向您现有的 Python 项目添加以下文件:
文件夹your-project/
文件夹your_module/
文件夹mcp_server/ (or custom name if specified)
- __init__.py Python package initialization
- server.py Main server definition with sample tools and resources
- stdio.py Entry point for STDIO transport, useful for simple local MCP servers
- http.py Entry point for Streamable HTTP transport, useful for hosting your MCP server
- Dockerfile Entry point for hosting your MCP server (excluded when
infrais set toNone)
- pyproject.toml Updated with MCP dependencies
- project.json Updated with MCP server serve targets
由于此生成器根据您选择的 iac 提供基础设施即代码,它将在 packages/common 中创建一个项目,其中包含相关的 CDK 构造或 Terraform 模块。
通用基础设施即代码项目的结构如下:
文件夹packages/common/constructs
文件夹src
文件夹app/ Constructs for infrastructure specific to a project/generator
- …
文件夹core/ Generic constructs which are reused by constructs in
app- …
- index.ts Entry point exporting constructs from
app
- project.json Project build targets and configuration
文件夹packages/common/terraform
文件夹src
文件夹app/ Terraform modules for infrastructure specific to a project/generator
- …
文件夹core/ Generic modules which are reused by modules in
app- …
- project.json Project build targets and configuration
为了部署您的 MCP Server,会生成以下文件:
文件夹packages/common/constructs/src
文件夹app
文件夹mcp-servers
文件夹<mcp-server-name>
- <mcp-server-name>.ts CDK construct for deploying your MCP Server
文件夹packages/common/terraform/src
文件夹app
文件夹mcp-servers
文件夹<mcp-server-name>
- <mcp-server-name>.tf Module for deploying your MCP Server
文件夹core
文件夹agent-core
- runtime.tf Generic module for deploying to Bedrock AgentCore Runtime
如果您为 infra 选择了 none,则不会生成 CDK 构造或 Terraform 模块 — MCP 服务器仅配置为本地 STDIO / HTTP 使用。在此模式下,auth 选项将被忽略,因为没有需要进行身份验证的托管端点。
当部署到 Bedrock AgentCore Runtime 时,MCP server 会被构建为容器镜像,推送到 Amazon ECR,并在 AgentCore Runtime 中运行。AI 助手调用 AgentCore Runtime 数据平面端点,该端点通过 streamable HTTP transport 将 tools/* 和 resources/* 调用转发到您的服务器。
使用 infra: none 时,不会生成 AWS 基础设施。MCP server 仅配置为本地 STDIO 和 HTTP 传输,并由运行在同一台机器上的 AI 助手使用。
使用您的 MCP Server
Section titled “使用您的 MCP Server”工具是 AI 助手可以调用以执行操作的函数。Python MCP 服务器使用 MCP Python SDK (FastMCP) 库,该库提供了一种基于装饰器的简单方法来定义工具。
您可以在 server.py 文件中添加新工具:
@mcp.tool(description="Your tool description")def your_tool_name(param1: str, param2: int) -> str: """Tool implementation with type hints""" # Your tool logic here return f"Result: {param1} with {param2}"FastMCP 库自动处理:
- 基于函数类型提示的类型验证
- MCP 协议的 JSON schema 生成
- 错误处理和响应格式化
资源为 AI 助手提供上下文。您可以使用 @mcp.resource 装饰器添加资源:
@mcp.resource("example://static-resource", description="Static resource example")def static_resource() -> str: """Return static content""" return "This is static content that provides context to the AI"
@mcp.resource("dynamic://resource/{item_id}", description="Dynamic resource example")def dynamic_resource(item_id: str) -> str: """Return dynamic content based on parameters""" # Fetch data based on item_id data = fetch_data_for_item(item_id) return f"Dynamic content for {item_id}: {data}"配置 AI 助手
Section titled “配置 AI 助手”大多数支持 MCP 的 AI 助手使用类似的配置方法。您需要创建或更新配置文件,添加您的 MCP 服务器详细信息:
{ "mcpServers": { "your-mcp-server": { "command": "uv", "args": [ "run", "python", "-m", "my_module.mcp_server.stdio" ], "env": { "VIRTUAL_ENV": "/path/to/your/project/.venv" } } }}特定助手的配置
Section titled “特定助手的配置”请参阅以下文档以配置特定 AI 助手的 MCP:
运行您的 MCP Server
Section titled “运行您的 MCP Server”要在本地运行您的 MCP 服务器(以及与其连接的所有内容,例如本地数据库),请使用项目的 dev 目标:
pnpm nx dev your-projectyarn nx dev your-projectnpx nx dev your-projectbunx nx dev your-project如果您已向项目添加了多个组件(MCP 服务器、代理等),这将启动所有组件。要仅运行此 MCP 服务器,请以其 <your-server-name>-dev 目标为目标:
pnpm nx your-server-name-dev your-projectyarn nx your-server-name-dev your-projectnpx nx your-server-name-dev your-projectbunx nx your-server-name-dev your-projectInspector
Section titled “Inspector”生成器配置了一个名为 <your-server-name>-inspect 的目标,该目标在本地启动您的 MCP 服务器(通过 <your-server-name>-dev 目标,包括任何连接的依赖项,例如本地数据库),并启动预配置为通过 Streamable HTTP 传输连接到它的 MCP Inspector。
pnpm nx your-server-name-inspect your-projectyarn nx your-server-name-inspect your-projectnpx nx your-server-name-inspect your-projectbunx nx your-server-name-inspect your-project这将在 http://localhost:6274 启动检查器。点击”Connect”按钮开始使用。
测试和使用 MCP 服务器的最简单方法是使用检查器或将其配置为 AI 助手(如上所述)。
但是,您可以使用 <your-server-name>-serve-stdio 目标直接使用 STDIO 传输 运行服务器。
pnpm nx your-server-name-serve-stdio your-projectyarn nx your-server-name-serve-stdio your-projectnpx nx your-server-name-serve-stdio your-projectbunx nx your-server-name-serve-stdio your-project此命令使用 uv run 以 STDIO 传输执行您的 MCP 服务器。
Streamable HTTP
Section titled “Streamable HTTP”如果您想使用 Streamable HTTP 传输 在本地运行 MCP 服务器,可以使用 <your-server-name>-serve 目标。
pnpm nx your-server-name-serve your-projectyarn nx your-server-name-serve your-projectnpx nx your-server-name-serve your-projectbunx nx your-server-name-serve your-project此命令使用 uv run uvicorn --reload 以 HTTP 传输运行您的 MCP 服务器(通常在端口 8000 上),并在文件更改时自动重启。
将您的 MCP Server 部署到 Bedrock AgentCore Runtime
Section titled “将您的 MCP Server 部署到 Bedrock AgentCore Runtime”基础设施即代码
Section titled “基础设施即代码”如果您为 infra 选择了 agentcore,将生成相关的 CDK 或 Terraform 基础设施,您可以使用它将 MCP 服务器部署到 Amazon Bedrock AgentCore Runtime。
将为您的 MCP Server 生成一个 CDK 构造,根据您运行生成器时选择的 name 命名,或默认为 <ProjectName>McpServer。
您可以在 CDK 应用程序中使用此 CDK 构造:
import { MyProjectMcpServer } from '@my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { // Add the MCP server to your stack new MyProjectMcpServer(this, 'MyProjectMcpServer'); }}将为您生成一个 Terraform 模块,根据您运行生成器时选择的 name 命名,或默认为 <ProjectName>-mcp-server。
将共享的 runtime_config_appconfig 模块的输出传递到 MCP 服务器模块:
module "my_project_mcp_server" { source = "../../common/terraform/src/app/mcp-servers/my-project-mcp-server"
appconfig_application_id = module.runtime_config_appconfig.application_id appconfig_application_arn = module.runtime_config_appconfig.application_arn}生成器提供了一个 auth 选项来配置 MCP 服务器的身份验证。在生成 MCP 服务器时,您可以在 IAM(默认)或 Cognito 身份验证之间进行选择。
默认情况下,您的 MCP 服务器将使用 IAM 身份验证进行保护,只需在不带任何参数的情况下部署它:
import { MyProjectMcpServer } from '@my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { new MyProjectMcpServer(this, 'MyProjectMcpServer'); }}您可以使用 grantInvokeAccess 方法授予在 Bedrock AgentCore Runtime 上调用 MCP 服务器的访问权限。例如,您可能希望使用 py#agent 生成器生成的代理来调用您的 MCP 服务器:
import { MyProjectAgent, MyProjectMcpServer } from '@my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const agent = new MyProjectAgent(this, 'MyProjectAgent'); const mcpServer = new MyProjectMcpServer(this, 'MyProjectMcpServer');
mcpServer.grantInvokeAccess(agent); }}# MCP Servermodule "my_project_mcp_server" { # Relative path to the generated module in the common/terraform project source = "../../common/terraform/src/app/mcp-servers/my-project-mcp-server"
appconfig_application_id = module.runtime_config_appconfig.application_id appconfig_application_arn = module.runtime_config_appconfig.application_arn}要授予调用 MCP 服务器的访问权限,您需要添加如下策略,引用 module.my_project_mcp_server.agent_core_runtime_arn 输出:
{ Effect = "Allow" Action = [ "bedrock-agentcore:InvokeAgentRuntime" ] Resource = [ module.my_project_mcp_server.agent_core_runtime_arn, "${module.my_project_mcp_server.agent_core_runtime_arn}/*" ]}Cognito 身份验证
Section titled “Cognito 身份验证”当您选择 Cognito 身份验证时,生成器会将 MCP 服务器配置为使用 Cognito 进行身份验证。
生成的构造接受一个 identity 属性,用于配置 Cognito 身份验证:
import { MyProjectMcpServer, UserIdentity } from '@my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const identity = new UserIdentity(this, 'Identity');
new MyProjectMcpServer(this, 'MyProjectMcpServer', { identity, }); }}UserIdentity 构造可以使用 ts#website#auth 生成器生成,或者您可以创建自己的 CDK UserPool 和 UserPoolClient。
生成的模块接受 user_pool_id 和 user_pool_client_ids 变量用于 Cognito 身份验证:
module "user_identity" { source = "../../common/terraform/src/core/user-identity"}
module "my_project_mcp_server" { source = "../../common/terraform/src/app/mcp-servers/my-project-mcp-server"
appconfig_application_id = module.runtime_config_appconfig.application_id appconfig_application_arn = module.runtime_config_appconfig.application_arn
user_pool_id = module.user_identity.user_pool_id user_pool_client_ids = [module.user_identity.user_pool_client_id]}Bundle 和 Docker 目标
Section titled “Bundle 和 Docker 目标”为了为 Bedrock AgentCore Runtime 构建您的 MCP 服务器,会向您的项目添加一个 bundle 目标,该目标:
- 使用
uv export将 Python 依赖项导出到requirements.txt文件 - 使用
uv pip install为目标平台(aarch64-manylinux_2_28)安装依赖项
还会添加一个特定于您的 MCP 服务器的 docker 目标,该目标将 Dockerfile 和打包的工件复制到 docker 上下文目录中。这将 Dockerfile 与构建输出放在一起,允许 CDK 使用 AgentRuntimeArtifact.fromAsset 直接构建 Docker 镜像。
为此项目构建的 Docker 镜像可以使用 Trivy 进行漏洞扫描,该工具从 ECR 托管的 Trivy 镜像运行。
项目中会添加一个 trivy 目标,用于扫描构建的镜像,如果发现任何 HIGH 或 CRITICAL 严重级别的漏洞,将以非零状态退出。生成的 Dockerfile 使用的基础镜像在生成时没有已知的可修复漏洞(这些严重级别),并升级捆绑的工具(如 npm)以保持这种状态。
扫描使用与镜像构建相同的容器引擎(docker 或 finch),因此不需要额外的工具。由于扫描仅在镜像更改时重新运行,未更改的镜像不会被重新扫描。提供的 trivy 根脚本会扫描工作区中的每个镜像:
pnpm trivyyarn trivynpm run trivybun trivy抑制 Trivy 发现
Section titled “抑制 Trivy 发现”在某些情况下,您可能希望抑制特定的漏洞,例如当尚无可用修复且您已评估风险为可接受时。
将漏洞 ID(每行一个)添加到项目根目录中的 .trivyignore 文件(即 project.json 旁边):
# node-tar arbitrary file write - not exploitable in our usageCVE-2024-XXXXX有关过滤发现的更多详细信息,请参阅 Trivy 过滤文档。
您的 MCP 服务器通过在 Dockerfile 中配置自动检测,使用 AWS Distro for Open Telemetry (ADOT) 自动配置了可观测性。
您可以在 CloudWatch AWS 控制台中找到跟踪信息,方法是在菜单中选择”GenAI Observability”。请注意,要填充跟踪信息,您需要启用 Transaction Search。
有关更多详细信息,请参阅 AgentCore 可观测性文档。
使用 connection 生成器将此项目与工作区中的其他项目集成。以下连接涉及此项目: