MCP Server 到 DynamoDB
connection 生成器将 TypeScript MCP Server 连接到 TypeScript DynamoDB 项目,配置本地开发环境使两者自动一起启动。
在使用此生成器之前,请确保您拥有:
- 一个
ts#mcp-server项目 - 一个
ts#dynamodb项目
- 安装 Nx Console VSCode Plugin 如果您尚未安装
- 在VSCode中打开Nx控制台
- 点击
Generate (UI)在"Common Nx Commands"部分 - 搜索
@aws/nx-plugin - connection - 填写必需参数
- 点击
Generate
pnpm nx g @aws/nx-plugin:connectionyarn nx g @aws/nx-plugin:connectionnpx nx g @aws/nx-plugin:connectionbunx nx g @aws/nx-plugin:connection选择您的 MCP server 项目作为源,选择您的 DynamoDB 项目作为目标。如果项目包含多个 MCP server 组件,请指定 sourceComponent 以消除歧义。
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| sourceProject 必需 | string | - | 源项目 |
| targetProject 必需 | string | - | 要连接到的目标项目 |
| sourceComponent | string | - | 要从其连接的源组件(组件名称、相对于源项目根目录的路径或生成器 ID)。使用 '.' 显式选择项目作为源。 |
| targetComponent | string | - | 要连接到的目标组件(组件名称、相对于目标项目根目录的路径或生成器 ID)。使用 '.' 显式选择项目作为目标。 |
| preferInstallDependencies | boolean | true | 是否在生成器运行后优先安装依赖项。设置为 false 可在批量运行多个生成器时延迟安装(如果后续生成器需要计算 Nx 项目图,仍会运行安装);在最后统一安装一次。 |
生成器会更新 MCP server 的 <mcp-server-name>-dev 目标(在 project.json 中),使其依赖于 DynamoDB 项目的 dev 目标。不会修改源文件。
在工具中使用 DynamoDB
Section titled “在工具中使用 DynamoDB”从 DynamoDB 包中导入实体工厂,并在 createServer 中使用它们:
import { createExampleEntity } from ':my-scope/my-table';
export const createServer = async () => { const server = new McpServer({ name: 'my-service', version: '1.0.0' });
server.tool('list_examples', 'List all example items', {}, async () => { const entity = await createExampleEntity(); const result = await entity.scan.go(); return { content: [{ type: 'text', text: JSON.stringify(result.data) }], }; });
return server;};要允许 MCP server 访问 DynamoDB 表,请在基础设施中授予必要的权限。
import { MyTable } from ':my-scope/common-constructs';
const table = new MyTable(this, 'Table');const myMcpServer = new MyMcpServer(this, 'MyMcpServer');
table.grantReadWriteData(myMcpServer);grantReadWriteData 向 MCP server 的执行角色授予 DynamoDB 和 KMS 权限。
module "my_table" { source = "../../common/terraform/src/app/dynamodb/my-table"}
resource "aws_iam_role_policy" "dynamodb_access" { role = module.my_mcp_server.lambda_role_name
policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Action = [ "dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:DeleteItem", "dynamodb:Query", "dynamodb:Scan", "dynamodb:BatchGetItem", "dynamodb:BatchWriteItem", ] Resource = [ module.my_table.table_arn, "${module.my_table.table_arn}/index/*", ] }, { Effect = "Allow" Action = [ "kms:Encrypt", "kms:Decrypt", "kms:ReEncrypt*", "kms:GenerateDataKey*", "kms:DescribeKey", ] Resource = [module.my_table.kms_key_arn] }, ] })}connection 生成器会配置您项目的 dev 目标,使其依赖于 DynamoDB 项目的 dev 目标。当运行 dev 时,DynamoDB Local 将与您的项目一起自动启动。
LOCAL_DEV=true 环境变量会自动设置,因此 getDynamoDBClient() 和 resolveTableName() 会连接到本地 DynamoDB Local 实例而不是 AWS。