亚马逊基岩代理核心网关(MCP服务器)
  
使用Amazon Bedrock AgentCore网关实现生产就绪的模型上下文协议服务器。Bedrock AI代理和自定义工具之间的安全、OAuth身份验证桥梁,具有自动天气查找和个性化问候功能。
目录
建筑
┌───────────┐ ┌───────────┐ ┌─────────────────────────────────────────────────┐
│ MCP │────▶│ Entra ID │ │ AWS Cloud │
│ Client │◀────│ (PKCE) │ │ │
└───────────┘ └───────────┘ │ ┌───────────────────────────────────────────┐ │
│ │ │ │ Bedrock AgentCore Gateway │ │
│ OAuth Token │ │ • JWT validation (OIDC) │ │
│ │ │ │ • Semantic tool search │ │
│ ▼ │ │ • Interceptor: JWT → User Info │ │
└───────────▶ Gateway ────────┼──│ • Target: tool_schema.json routing │ │
URL │ └──────────────────────┬────────────────────┘ │
│ │ │
│ ┌──────────────────────▼────────────────────┐ │
│ │ Main Lambda (Rust) + Interceptor │ │
│ │ • Weather lookup (Open-Meteo API) │ │
│ │ • Personalized greetings │ │
│ └──────────────────────┬────────────────────┘ │
│ │ │
│ ┌────────────────┴────────┐ │
│ │ CloudWatch Logs │ │
│ └─────────────────────────┘ │
└─────────────────────────┬───────────────────────┘
▼
┌─────────────────┐
│ Open-Meteo API │
└─────────────────┘
**Stack**: ARM64 Lambdas (128MB, ~1.3MB UPX) | Entra ID OAuth | CloudWatch (3d retention)
**Features**: JWT token decoding, automatic weather lookup, personalized user greetings, secure header propagation, dynamic schema generation
**License**: MIT
## Model Context Protocol Implementation
This is a **Model Context Protocol (MCP) server** implemented as an AWS Lambda function for Amazon Bedrock AgentCore. MCP is an open-source specification that enables AI agents to discover and interact with external tools and APIs in a standardized way. This server uses the `rmcp` crate's `#[tool]` macro for MCP-compliant schema generation.
The Bedrock AgentCore Gateway is configured with a `SEMANTIC` search type, which enables intelligent tool selection. This means it can understand natural language queries, match tool descriptions and parameters, and provide context-aware tool recommendations, significantly improving the agent's ability to utilize available tools effectively.
## Features
- **ARM64/Graviton** - 20% cheaper, UPX compressed to 1.3MB per Lambda
- **Secretless OAuth** - PKCE flow, no client secrets
- **JWT Token Decoding** - Automatic user information extraction from Entra ID tokens with expiry validation
- **Gateway Interceptor** - Header propagation and identity resolution between gateway and tools
- **Dynamic Schema Generation** - Tool schemas automatically generated and deployed
- **Regional NAT Gateway** - Auto HA across AZs, stable egress IP
- **Zero Unsafe** - No `unwrap/expect/panic/unsafe`, strict lints
- **Concurrency Limits** - Function-level concurrent execution limits to prevent cost overruns
- **Event Notifications** - SNS notifications for infrastructure events
- **Structured Logging** - JSON logs for CloudWatch
- **Dead Letter Queue** - Failed invocations stored in encrypted SQS for debugging
- **Auto Schemas** - Generated from code annotations
- **Fast Cold Start** - Minimal deps, optimized binary
- **Cost Optimized** - Minimum memory (128MB), conservative timeouts, low concurrency limits
- **Principle of Least Privilege** - IAM policies scoped to specific resources
- **Resource Cleanup** - Terraform properly manages all resources
- **Free Tier** - Typical usage $0/month
- **Smart Weather Lookup** - Automatic geocoding and weather data retrieval from Open-Meteo
- **Personalized Greetings** - Context-aware user greetings with automatic name extraction
## One-Time Backend Setup
Before you can deploy, you need to run a one-time setup command to create the Terraform backend infrastructure:
make setup-backend
此命令将:
1. 提示您输入唯一的S3存储桶名称
1. 为Terraform状态存储创建S3存储桶
1. 在bucket上启用版本控制和加密
1. 配置本机S3状态锁定(Terraform 1.10+)
1. 生成 `iac/backend.config` 文件
安装后,您可以使用以下工具部署基础架构:
make deploy
**重要**:The `backend.config` 该文件对于所有Terraform操作都是必不可少的。Makefiles现在包括智能后端检查,如果此文件丢失,它将为您提供指导。
## 快速开始
make setup-backend # One-time backend setup (S3 with native locking) make deploy # Build and deploy to AWS make test-token # Get OAuth token + launch MCP Inspector
这 `test-token` 命令会自动将令牌复制到剪贴板(macOS/Linux/WSL),并提供使用MCP检查器进行测试的说明。
## 临时拉取请求环境
此存储库会自动为每个pull请求创建隔离的测试环境:
- 🌱 **自动部署**:打开非草稿PR时,会自动创建一个临时环境
- 🔗 **隔离测试**:每个PR都有自己的网关URL和后端资源
- 🧪 **易于测试**:使用相同的 `make test-token` 测试更改的工作流
- 🗑️ **自动清理**:当PR关闭或合并时,环境会被破坏
### 手动环境管理
要手动触发环境部署或销毁,请执行以下操作:
Deploy a manual environment (replace 123 with your PR number)
gh workflow run preview-environment.yml -f action=deploy -f pr_number=123
Destroy a manual environment
gh workflow run preview-environment.yml -f action=destroy -f pr_number=123
**备注**:手动运行时 `pr_number` 需要输入来命名环境资源(例如。, `preview-123`).如果您正在调试特定的PR,请使用实际的PR编号,或者在划痕环境中使用任何唯一的编号。
## 自动依赖关系更新
Dependabot自动为以下对象创建PR:
- 🦀 **Rust依赖关系** -Cargo.toml更新
- 🏗️ **地形提供者** -AWS、Entra ID和其他提供商
- ⚙️ **GitHub操作** -工作流操作更新
所有检查通过后,更新将自动进行测试和合并。
## 示例:天气工具
附带的工作工具展示了该模式:
- 简单的基于位置的天气查询(只需提供“加尔各答”或“悉尼”)
- 坐标的自动地理编码(Open-Meteo API)
- 智能默认天气参数(天气代码、最低/最高温度)
- 自动时区检测和定位
- API与Open-Meteo天气服务的直接集成
## 示例:个性化问候工具
新的个性化问候工具演示了:
- 零配置用户个性化
- 自动JWT令牌解析和用户身份提取
- 基于经过身份验证的用户信息的上下文响应
- 网关和工具之间的安全标头传播
- 丢失用户信息的巧妙回退
## 先决条件
- **锈** (2024年版)
- **货物λ**: `cargo install cargo-lambda`
- **法国巴黎第十大学**: `brew install upx` (macOS)| `apt install upx-ucl` (Linux)
- **之字形**: `brew install zig` (macOS)| `apt install zig` (Linux)
- **jq**: `brew install jq` (macOS)| `apt install jq` (Linux)
- **地形** (最新)
- **AWS-CLI** (已配置)
- **Azure命令行界面** (已配置)
**备注**:跑步 `make release` 将自动在本地安装缺失的工具。
## GitHub模板仓库的初始设置
当将此存储库用作GitHub模板时,您需要在存储库设置中设置几个秘密,以便GitHub Actions工作流正常运行。
**资源命名**:系统通过附加随机后缀(例如。, `aws-agentcore-gateway-a1b2c3`)以防止在同一AWS帐户中存在多个部署时发生冲突。
### 必需的GitHub机密
|密码名称|描述|安装说明|
|-------------|-------------|--------------------|
| `AWS_IAM_ROLE_ARN` |AWS IAM角色ARN用于GitHub操作OIDC身份验证| |
| `AZURE_CLIENT_ID` |Entra ID应用程序注册客户端ID| |
| `AZURE_TENANT_ID` 请输入租户ID。 |
| `TF_BACKEND_BUCKET` |用于Terraform状态存储的S3存储桶名称|运行 `make setup-backend` 设置AWS凭据后|
| `APP_PRIVATE_KEY` |GitHub应用程序的PEM私钥 `@brown-ninja-bot` (多行)。用于为CI自动化铸造短期安装令牌。|创建GitHub应用程序(设置→ 开发人员设置→ GitHub Apps),生成并下载私钥,然后将PEM内容添加为密钥 `APP_PRIVATE_KEY` 在此存储库的设置中→ 秘密和变量→ 行动。 |
| `APP_ID` |数字GitHub应用程序ID `@brown-ninja-bot`。与私钥一起使用以生成JWT。|添加数字App ID作为密钥 `APP_ID` 存储库机密。 |
要验证您的GitHub App设置,您可以使用提供的测试工作流:
Trigger the test workflow which mints an installation token and validates it
from the Actions tab: "Test: GitHub App Installation Token" → Run workflow
or via CLI:
gh workflow run test-github-app-token.yml
### 可选GitHub机密
|密码名称|描述|默认值|
|-------------|-------------|---------|
| `PROJECT_NAME_SUFFIX` |资源名称的自定义后缀(例如“prod”、“dev”)。如果未设置,则自动生成随机后缀|随机6个字符字符串|
### 设置AWS身份验证
1. 跟随 在GitHub和AWS之间配置OIDC
1. 创建具有Lambda、API网关和S3所需权限的IAM角色
1. 设置 `AWS_IAM_ROLE_ARN` 这个角色的ARN秘密
### 设置Entra ID身份验证
1. 跟随 在GitHub和Azure之间配置OIDC
1. 在Entra ID中注册GitHub Actions应用程序
1. 设置 `AZURE_CLIENT_ID` 和 `AZURE_TENANT_ID` 秘密
### 设置Terraform后端
配置AWS身份验证后:
1. 跑 `make setup-backend` 在本地创建S3存储桶。此命令还将自动添加 `TF_BACKEND_BUCKET` 对您当地的价值 `.env` 文件。
1. 使用 `make update-secrets` 将这些值推送到您的GitHub存储库机密中。
### 更新GitHub机密
更新您的GitHub存储库机密 **GitHub Actions和Dependabot**,创建一个 `.env` 项目根目录中的文件,其中包含您希望更新的秘密(例如。, `MY_SECRET="myvalue"`).您可以使用提供的 `.env.example` 文件作为必需和可选机密的模板。
然后,运行以下命令:
make update-secrets
此命令将读取 `.env` 文件和使用 `gh CLI` 为GitHub Actions和Dependabot设置或更新相应的存储库机密。
**重要**:确保您的 `.env` 文件在您的 `.gitignore` 以防止意外泄露敏感信息。
### 使用opencode.ai
此存储库已预先配置为与 [opencode.ai](https://opencode.ai),一个由人工智能驱动的开发助手,可以帮助您构建、调试和维护MCP服务器。该项目包括:
- 与opencode.ai集成的预配置GitHub Actions工作流
- 工具发现的自动模式生成
- 标准化MCP实施模式
- 内置测试和调试工具
要将opencode.ai用于此项目:
1. 访问 [opencode.ai](https://opencode.ai) 并注册一个帐户
1. 安装opencode命令行界面: `npm install -g opencode`
1. 身份验证: `opencode login`
1. 导航到项目目录并运行: `opencode`
opencode助手将自动检测您的项目结构,并为以下内容提供上下文感知帮助:
- 添加新工具和功能
- 调试部署问题
- 优化性能
- 遵循MCP最佳实践
- 与其他AI服务集成
有关更多信息,请参阅 .
## 结构
src/ ├── main.rs # Main Lambda bootstrap + tracing ├── handler.rs # Main Lambda event handler ├── lib.rs # Library crate ├── models/ # Request/response types (JsonSchema) │ ├── mod.rs │ ├── weather.rs │ └── open_meteo.rs ├── tools/ # Tool implementations (#[tool] macro) │ ├── mod.rs │ ├── weather.rs │ └── personalized.rs ├── http/ # Global HTTP client │ ├── mod.rs │ └── client.rs └── bin/ ├── generate_schema.rs # Schema generation utility └── interceptor.rs # Gateway interceptor Lambda iac/ ├── main.tf # Terraform infrastructure └── ...
## 用法
### 构建与测试
make schema # Generate tool_schema.json make build # Debug build make release # ARM64 + UPX (~1.3MB) make test # Run tests make all # Test + release build cargo clippy # Run clippy lints cargo fmt # Format code
### 部署
make setup-backend # One-time backend setup make deploy # Build and deploy to AWS make tf-destroy # Destroy infrastructure
### 发展
make test-token # OAuth + Inspector (token auto-copied) make test-lambda # Direct Lambda test make logs # Tail CloudWatch logs make login # AWS + Azure auth make clean # Remove tokens/backups
### 高级地形操作
make tf-init # Initialize Terraform make tf-plan # Plan changes make tf-apply # Apply changes make tf-destroy # Destroy infrastructure
对于完整的基础设施命令: `cd iac && make help`
## 故障排除
### 网关异常日志记录
控制网关异常日志记录冗长 `iac/terraform.tfvars`:
Disabled (default) - Minimal error information for security
gateway_exception_level = null
Error level - Only error messages
gateway_exception_level = "ERROR"
Warning level - Warning and error messages
gateway_exception_level = "WARN"
Info level - Informational, warning, and error messages
gateway_exception_level = "INFO"
Debug level - Most verbose logging (use only for troubleshooting)
gateway_exception_level = "DEBUG"
重新部署: `cd iac && terraform apply -auto-approve`
⚠️ 安全注意事项:
更高的详细程度可能会在错误响应中暴露敏感信息。
仅将DEBUG/INFO用于故障排除,而不是在生产环境中。
禁用(设置为 `null`)排除故障后,避免暴露敏感数据。
### Lambda调试日志
编辑 `iac/variables.tf`:
variable "rust_log_level" { default = "debug" # or "trace" }
重新部署和查看: `make logs`
**生产**:设置为 `"info"` 避免记录敏感有效载荷
### 常见问题
|问题|解决方案|
|-------|----------|
|“拒绝访问”|网关IAM需要两者 `bedrock.amazonaws.com` 与 `bedrock-agentcore.amazonaws.com` 校长|
|“承载令牌无效”|令牌需要 `api://CLIENT_ID/access_as_user` 范围。跑 `make test-token` |
|Lambda超时|增加 `lambda_timeout` 在 `iac/variables.tf` |
## 命令
### 主要命令
|命令|描述|
|---------|-------------|
| `make help` |用彩色输出显示所有命令|
| `make schema` |生成tool_schema.json|
| `make build` |调试构建|
| `make release` |ARM64+UPX生产构建|
| `make test` |运行测试|
| `make all` |测试+发布版本|
| `make deploy` |构建并部署到AWS(智能后端检查)|
| `make setup-backend` |一次性后端设置|
| `make test-token` |OAuth+检查器(剪贴板)|
| `make test-lambda` |直接Lambda测试|
| `make logs` |尾部CloudWatch日志|
| `make update-deps` |更新所有依赖项|
### 基础设施命令
|命令|描述|
|---------|-------------|
| `make login` |AWS+Azure身份验证|
| `make tf-init` |初始化Terraform(智能后端检查)|
| `make tf-plan` |规划地形变化|
| `make tf-apply` |应用地形更改|
| `make tf-destroy` |破坏基础架构(首先生成架构)|
| `make clean` |删除令牌/备份|
| `make oauth-config` |显示OAuth配置详细信息|
| `make add-redirect-url` |将自定义OAuth重定向URL添加到Entra ID应用程序|
| `make remove-redirect-url` |从Entra ID应用程序中删除自定义OAuth重定向URL|
对于高级基础设施命令: `cd iac && make help`
## 模式生成
使用以下代码生成Amazon Bedrock AgentCore模式 `rmcp` 板条箱 `#[tool]` 宏:
use rmcp::tool;
#[tool(description = "Get current weather for a location")] pub async fn get_weather(request: WeatherRequest) -> Result { // implementation }
跑 `make schema` → 生成 `tool_schema.json` 与:
- 工具名称来自函数名称
- 宏属性描述
- 类型的输入/输出模式(通过 `schemars`)
- 基岩兼容格式(无枚举、内联类型)
## 添加工具
**1.型号** (`src/models/your_tool.rs`):
#[derive(Debug, Deserialize, JsonSchema)] pub struct YourRequest { #[schemars(description = "Input description")] pub input: String, }
看 `src/tools/personalized.rs` 以一个完整的示例演示:
- 从拦截器传递的数据中提取用户信息
- 创建个性化响应
- 正确处理上下文错误
**2.工具** (`src/tools/your_tool.rs`):
#[tool(description = "Clear, detailed description")] pub async fn your_tool(request: YourRequest) -> Result { // implementation }
**3.注册** 在 `src/bin/generate_schema.rs`:
tool_entry!( aws_lambda_mcp::tools::your_tool::your_tool_tool_attr(), YourRequest, YourResponse ),
**4.生成**: `make schema`
**5.路线**:更新 `handler.rs` 调用您的工具
## 配置
**拉姆达** (`Cargo.toml`):
[package.metadata.lambda.deploy] memory = 128 timeout = 30 tracing = "active"
**基础设施**:编辑 `iac/terraform.tfvars` 用于自定义设置
## 编码标准
看 [代理商.md](./AGENTS.md) 获取完整指南。
**规则**:
- ✅ `Result` + `?` 和 `.context()`
- ✅ `#[must_use]` 论纯函数
- ✅ `#[derive(Debug, Serialize, Deserialize, JsonSchema)]` 关于类型
- ❌ 不 `unwrap/expect/panic/unsafe`
- ❌ 异步时无阻塞I/O
- ❌ 无通配符导入
- ❌ 没有硬编码的秘密
**依赖项**: `lambda_runtime` | `tokio` | `serde` | `schemars` | `reqwest` | `tracing` | `anyhow` | `rmcp`
## 贡献
1. 阅读 [代理商.md](./AGENTS.md)
1. `cargo clippy -- -D warnings`
1. `make schema` 如果模型发生了变化
1. `make release` 成功
1. `make test` 通过