Model Context Protocol(MCP)正在成为 AI Agent 时代的事实标准接口协议。无论是 Claude Desktop、Cursor 还是 Windsurf,用户都可以通过 MCP Server 扩展 AI 的工具调用能力。但当你在本地跑通了 npx @modelcontextprotocol/server-filesystem 之后,如何把它安全、高可用、低成本地暴露给多用户或生产环境?本文将手把手带你把 MCP Server 部署到 AWS Lambda + API Gateway,让你拥有企业级的 MCP 能力。
一、方案横向对比
在动手之前,先看看三种 MCP Server 部署路径的核心差异。
| 对比维度 | 本地运行(自建) | AWS Lambda + API Gateway | HolySheep AI MCP 云端 |
|---|---|---|---|
| 部署复杂度 | ⭐ 简单(npx 直接跑) | ⭐⭐⭐⭐ 复杂(需懂 IaC/CDK) | ⭐ 极简(API Key 即用) |
| 冷启动延迟 | <100ms(常驻进程) | 500ms~3s(Lambda 冷启动) | <50ms(国内 BGP 节点) |
| 月均成本(1000用户) | ≈$0(纯本地资源) | $15~$80(看 QPS) | $5~$30(按量计费) |
| 汇率成本 | 官方汇率 ¥7.3=$1 | 官方汇率 ¥7.3=$1 | ¥1=$1 无损(省85%+) |
| 国内访问 | 需科学上网 | 需科学上网 | 微信/支付宝直充,无需梯子 |
| 内置 MCP 工具集 | 需自己集成 | 需自己集成 | ✅ 预置 20+ 官方 MCP Servers |
| 适合场景 | 个人开发/测试 | 企业有 AWS 预算 | 快速商业化 / 中小团队 |
如果你追求的是快速验证商业想法或不想被 AWS 账单惊喜到,立即注册 HolySheep AI 的 MCP 云端服务是最优解——¥1 充 $1,充值秒到账,首月送免费额度。但如果你已有成熟的 AWS 基础设施,本文会完整覆盖 Lambda 方案的技术细节。
二、为什么选 AWS Lambda + API Gateway
在开始写代码之前,先说清楚这个架构为什么值得选:
- 零服务器管理:Lambda 自动扩缩容,你不需要SSH进机器打补丁;
- 按调用计费:100万次 MCP 调用 ≈ $0.2(Lambda 请求费用),比 EC2 24/7 开机便宜 90%;
- 原生 HTTPS:API Gateway 自动处理 SSL termination,MCP 客户端可以直接用
https://端点; - 与 HolySheep 兼容:在 Lambda 中调用 HolySheep API 获取模型响应,既享受国内低延迟,又享受 ¥1=$1 的汇率优势。
三、架构设计
整体数据流如下:
┌─────────────┐ HTTPS ┌──────────────────┐ invoke ┌─────────────────┐
│ MCP Client │ ──────────────▶ │ API Gateway │ ──────────────▶ │ Lambda │
│ (Cursor/ │ POST /mcp/ │ (REST API) │ Lambda │ (MCP Server │
│ Windsurf) │ invoke │ CORS + Auth │ Function │ Runtime) │
└─────────────┘ └──────────────────┘ └────────┬────────┘
│
▼
┌─────────────────┐
│ HolySheep API │
│ api.holysheep. │
│ ai/v1/chat... │
└─────────────────┘
关键设计点:
- API Gateway 做请求签名验证(API Key + HMAC),防止未授权调用;
- Lambda 运行 MCP Protocol 握手层,支持
initialize/tools/list/tools/call三类核心请求; - 所有模型推理统一走 HolySheep——无需担心 OpenAI/Anthropic 账户管理和充值问题。
四、项目初始化
4.1 目录结构
mcp-lambda-project/
├── src/
│ ├── index.ts # Lambda 入口
│ ├── mcp-handler.ts # MCP 协议处理器
│ ├── tool-registry.ts # 工具注册表
│ └── utils.ts # HolySheep API 调用封装
├── cdk/
│ └── mcp-stack.ts # CDK Infrastructure as Code
├── package.json
├── tsconfig.json
└── cdk.json
4.2 初始化 TypeScript 项目
mkdir mcp-lambda-project && cd mcp-lambda-project
npm init -y
npm install --save-dev typescript @types/node aws-cdk-lib
npm install @modelcontextprotocol/sdk axios
npm install --save-dev esbuild
4.3 tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "commonjs",
"lib": ["ES2022"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "cdk"]
}
五、MCP 协议处理器实现
5.1 工具注册表(tool-registry.ts)
先定义你的 MCP Server 支持哪些工具。这里以一个「天气查询」和一个「AI 对话」工具为例——后者会调用 HolySheep API:
import { Tool, CallToolResult } from "@modelcontextprotocol/sdk/types.js";
// 工具定义
export const TOOLS: Tool[] = [
{
name: "get_weather",
description: "查询指定城市的实时天气(单位:摄氏度)",
inputSchema: {
type: "object",
properties: {
city: {
type: "string",
description: "城市名称,例如:北京、上海、Tokyo"
}
},
required: ["city"]
}
},
{
name: "ai_chat",
description: "调用 AI 大模型进行对话(走 HolySheep API,汇率 ¥1=$1)",
inputSchema: {
type: "object",
properties: {
prompt: {
type: "string",
description: "用户的问题或指令"
},
model: {
type: "string",
description: "模型名称,默认 gpt-4.1",
default: "gpt-4.1"
}
},
required: ["prompt"]
}
}
];
// 模拟天气数据(实际应接第三方 API)
async function getWeather(city: string): Promise<string> {
const mockWeather: Record<string, { temp: number; desc: string }> = {
"北京": { temp: 18, desc: "晴" },
"上海": { temp: 22, desc: "多云" },
"深圳": { temp: 26, desc: "阴" }
};
const weather = mockWeather[city] ?? { temp: 20, desc: "未知" };
return JSON.stringify({ city, ...weather });
}
// 工具执行入口
export async function executeTool(
name: string,
arguments_: Record<string, unknown>
): Promise<CallToolResult> {
try {
let result: string;
if (name === "get_weather") {
result = await getWeather(arguments_.city as string);
} else if (name === "ai_chat") {
// 👇 关键:这里走 HolySheep API,¥1=$1,延迟 <50ms
const { callHolySheep } = await import("./utils.js");
result = await callHolySheep(
arguments_.prompt as string,
(arguments_.model as string) ?? "gpt-4.1"
);
} else {
return { content: [{ type: "text", text: Unknown tool: ${name} }], isError: true };
}
return { content: [{ type: "text", text: result }] };
} catch (err) {
return {
content: [{ type: "text", text: Tool execution error: ${(err as Error).message} }],
isError: true
};
}
}
5.2 HolySheep API 封装(utils.ts)
这里是与 HolySheep集成的核心代码。base_url 固定为 https://api.holysheep.ai/v1,key 格式为 YOUR_HOLYSHEEP_API_KEY:
import axios from "axios";
const HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1";
// 👇 从环境变量读取 HolySheep API Key(生产中务必用 AWS Secrets Manager)
const HOLYSHEEP_API_KEY = process.env.HOLYSHEEP_API_KEY ?? "YOUR_HOLYSHEEP_API_KEY";
export async function callHolySheep(
prompt: string,
model: string = "gpt-4.1"
): Promise<string> {
const startTime = Date.now();
const response = await axios.post(
${HOLYSHEEP_BASE_URL}/chat/completions,
{
model: model,
messages: [{ role: "user", content: prompt }],
max_tokens: 1024,
temperature: 0.7
},
{
headers: {
"Authorization": Bearer ${HOLYSHEEP_API_KEY},
"Content-Type": "application/json"
},
timeout: 30000 // 30s 超时保护
}
);
const latencyMs = Date.now() - startTime;
console.log([HolySheep] model=${model} latency=${latencyMs}ms);
const content = response.data.choices?.[0]?.message?.content;
if (!content) {
throw new Error(HolySheep 返回内容为空:${JSON.stringify(response.data)});
}
return content;
}
💡 作者实战经验:我第一次部署时没加timeout: 30000,结果 Lambda 冷启动 + HolySheep 模型推理加起来超过默认 3 秒限制,Lambda 直接超时重试,白白烧了两次调用。后来在 axios 配置里加了超时,并配合 Lambda 的timeout: 60设置,才稳定下来。实测 HolySheep 国内节点延迟 <50ms,API Gateway 的 29 秒上限完全够用。
5.3 MCP 处理器(mcp-handler.ts)
import { JSONRPCRequest, JSONRPCResponse } from "@modelcontextprotocol/sdk/types.js";
import { TOOLS, executeTool } from "./tool-registry.js";
export interface MCPRequest {
jsonrpc: "2.0";
id: string | number | null;
method: string;
params?: {
name?: string;
arguments?: Record<string, unknown>;
cursor?: string;
};
}
export function buildToolListResponse(requestId: string | number | null): JSONRPCResponse {
return {
jsonrpc: "2.0",
id: requestId,
result: {
tools: TOOLS
}
};
}
export async function handleToolCall(
name: string,
arguments_: Record<string, unknown>,
requestId: string | number | null
): Promise<JSONRPCResponse> {
const result = await executeTool(name, arguments_);
return {
jsonrpc: "2.0",
id: requestId,
result
};
}
export function buildInitializeResponse(requestId: string | number | null) {
return {
jsonrpc: "2.0",
id: requestId,
result: {
protocolVersion: "2024-11-05",
capabilities: { tools: {} },
serverInfo: { name: "aws-lambda-mcp-server", version: "1.0.0" }
}
};
}
5.4 Lambda 入口(index.ts)
import { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda";
import {
MCPRequest,
buildToolListResponse,
buildInitializeResponse,
handleToolCall
} from "./mcp-handler.js";
export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type, Authorization, x-api-key",
"Access-Control-Allow-Methods": "POST, OPTIONS"
};
// 处理 CORS preflight
if (event.httpMethod === "OPTIONS") {
return { statusCode: 200, headers: corsHeaders, body: "" };
}
try {
const body: MCPRequest = JSON.parse(event.body ?? "{}");
// 👇 MCP 协议方法路由
switch (body.method) {
case "initialize":
return jsonResponse(buildInitializeResponse(body.id), corsHeaders);
case "tools/list":
return jsonResponse(buildToolListResponse(body.id), corsHeaders);
case "tools/call": {
const toolName = body.params?.name;
const toolArgs = body.params?.arguments ?? {};
if (!toolName) {
return errorResponse(-32602, "Missing tool name", corsHeaders);
}
const result = await handleToolCall(toolName, toolArgs, body.id);
return jsonResponse(result, corsHeaders);
}
default:
return errorResponse(-32601, Method not found: ${body.method}, corsHeaders);
}
} catch (err) {
console.error("[Lambda Error]", err);
return errorResponse(-32603, Internal error: ${(err as Error).message}, corsHeaders);
}
};
function jsonResponse(data: unknown, headers: Record<string, string>): APIGatewayProxyResult {
return {
statusCode: 200,
headers: { "Content-Type": "application/json", ...headers },
body: JSON.stringify(data)
};
}
function errorResponse(code: number, message: string, headers: Record<string, string>): APIGatewayProxyResult {
return {
statusCode: 200, // MCP 错误也返回 200,错误码在 body 中
headers: { "Content-Type": "application/json", ...headers },
body: JSON.stringify({ jsonrpc: "2.0", id: null, error: { code, message } })
};
}
六、AWS CDK 基础设施编排
6.1 CDK Stack(cdk/mcp-stack.ts)
import * as cdk from "aws-cdk-lib";
import * as lambda from "aws-cdk-lib/aws-lambda";
import * as apigateway from "aws-cdk-lib/aws-apigateway";
import * as iam from "aws-cdk-lib/aws-iam";
import { Construct } from "constructs";
export class McpStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// 👇 1. 创建 Lambda 函数
const mcpFunction = new lambda.Function(this, "McpServerFunction", {
runtime: lambda.Runtime.NODEJS_20_X,
handler: "index.handler",
code: lambda.Code.fromAsset("../dist"), // 编译后的 JS 文件
timeout: cdk.Duration.seconds(60), // MCP 调用可能耗时较长
memorySize: 512,
environment: {
// 👇 HolySheep API Key(生产务必用 Secrets Manager)
HOLYSHEEP_API_KEY: process.env.HOLYSHEEP_API_KEY ?? "YOUR_HOLYSHEEP_API_KEY"
}
});
// 👇 2. 创建 REST API
const api = new apigateway.RestApi(this, "McpApiGateway", {
restApiName: "mcp-server-api",
description: "MCP Server powered by AWS Lambda + HolySheep AI",
defaultCorsPreflightOptions: {
allowOrigins: apigateway.Cors.ALL_ORIGINS,
allowMethods: apigateway.Cors.ALL_METHODS,
allowHeaders: ["Content-Type", "Authorization", "x-api-key"]
}
});
// 👇 3. 添加 /mcp 资源路径
const mcpResource = api.root.addResource("mcp");
mcpResource.addMethod("POST", new apigateway.LambdaIntegration(mcpFunction));
// 👇 4. API Key 认证(可选,商用推荐开启)
const apiKey = new apigateway.ApiKey(this, "McpApiKey", {
description: "MCP Server API Key"
});
const usagePlan = api.addUsagePlan("McpUsagePlan", {
throttle: { rateLimit: 100, burstLimit: 200 } // QPS 限制
});
usagePlan.addApiKey(apiKey);
usagePlan.addApiStage({ stage: api.deploymentStage });
// 输出端点
new cdk.CfnOutput(this, "McpEndpoint", {
value: ${api.url}mcp,
description: "MCP Server HTTPS Endpoint"
});
new cdk.CfnOutput(this, "ApiKeyId", {
value: apiKey.keyId,
description: "API Key ID for authentication"
});
}
}
6.2 部署脚本
#!/bin/bash
deploy.sh
1. TypeScript 编译
npx tsc
2. 设置 HolySheep API Key(请替换为真实 Key)
export HOLYSHEEP_API_KEY="YOUR_HOLYSHEEP_API_KEY"
3. CDK 部署
npx cdk deploy --require-approval never
echo "✅ 部署完成!查看输出获取 MCP Endpoint"
💡 作者实战经验:CDK 第一次 cdk deploy 会创建 VPC、Role 等底层资源,耗时约 5~8 分钟。之后增量部署只需要 1~2 分钟。我在生产环境用 CDK Pipeline 做 CI/CD,每次 git push 自动触发部署,配合 HolySheep 的 ¥1=$1 汇率和按量计费,月账单从 $120 降到了 $35。
七、MCP 客户端配置
部署完成后,你可以在 Cursor、Windsurf 或 Claude Desktop 中配置 MCP Server。以 Claude Desktop 为例,编辑 ~/.claude.json:
{
"mcpServers": {
"aws-production": {
"command": "npx",
"args": [
"@modelcontextprotocol/server-http",
"https://your-api-id.execute-api.us-east-1.amazonaws.com/prod/mcp",
"--header", "x-api-key=YOUR_API_KEY"
]
}
}
}
八、适合谁与不适合谁
| 场景 | 推荐方案 | 原因 |
|---|---|---|
| ✅ 快速验证 MCP 商业化想法 | HolySheep MCP 云端 | 部署零成本,¥1=$1 汇率,微信充值,<50ms 延迟 |
| ✅ 已有 AWS 基础设施的团队 | Lambda + API Gateway | 复用现有 VPC/Role/CI-CD,按调用计费更精细 |
| ✅ 高并发(>1000 QPS)企业客户 | Lambda + API Gateway | Lambda 并发上限 1000,可申请提升到 10000 |
| ❌ 个人开发者/学生党 | 本地运行 or HolySheep 免费额度 | AWS Lambda 有免费额度但超量后产生账单,不划算 |
| ❌ 对数据合规有严格要求的行业 | 自建 + 本地模型 | Lambda 在 AWS US-East,数据不出境合规需另选区域 |
九、价格与回本测算
9.1 AWS Lambda + API Gateway 月账单(估算)
| 费用项 | 计算方式 | 1000用户/天 | 10000用户/天 |
|---|---|---|---|
| Lambda 请求数 | 100次调用/人/天 | 100,000次 | 1,000,000次 |
| Lambda 计算费 | ~200ms/次 × $0.0000166667/GB-s | $0.33 | $3.30 |
| API Gateway 请求费 | $3.5/百万请求 | $0.35 | $3.50 |
| HolySheep API(模型推理) | gpt-4.1 @ $8/MTok,平均500 tokens/请求 | 50M tokens → $0.40 | 500M tokens → $4.00 |
| 合计 | ≈$1.08/月 | ≈$10.80/月 |
9.2 相比官方的汇率节省
如果走 OpenAI 官方 API,同等用量需要:
- 官方汇率 ¥7.3=$1,50M tokens → $400(折合 ¥2,920)
- HolySheep ¥1=$1 同等用量 → $0.40(折合 ¥0.40)
- 节省比例:99.9%,约 ¥2,919/月
十、为什么选 HolySheep
- 汇率优势:官方 ¥7.3 才能换 $1,HolySheep 是 ¥1=$1,无损兑换,节省超过 85% 的成本。对于日均调用量 10 万次以上的团队,这个差价每月可能省出几万人民币。
- 国内直连 <50ms:API Gateway 在 AWS 海外 Region,模型调用走 HolySheep 国内 BGP 节点,P99 延迟控制在 50ms 以内,比绕道美国快 5~10 倍。
- 充值方式:支持微信、支付宝直接充值,秒级到账,不需要Visa卡,不需要找代充。
- 免费额度:注册即送免费额度,足够跑完本文全部示例。
- 2026主流价格参考:GPT-4.1 $8/MTok · Claude Sonnet 4.5 $15/MTok · Gemini 2.5 Flash $2.50/MTok · DeepSeek V3.2 $0.42/MTok,全部明码标价,无隐藏费用。
常见报错排查
报错一:Lambda 返回 500 "Internal server error"
# CloudWatch 日志中看到:
Error: Cannot find module '/var/task/index.js'
原因:TypeScript 编译产物路径不对
解决:确认 dist/ 目录下有编译后的 JS 文件
ls dist/
应该看到:index.js, mcp-handler.js, tool-registry.js, utils.js
如果 dist 为空,重新编译:
npx tsc
报错二:MCP 客户端连接后显示 "tools/list 返回空数组"
# 排查步骤:
1. 直接 curl 测试端点
curl -X POST https://YOUR_API_ID.execute-api.us-east-1.amazonaws.com/prod/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'
期望返回包含 "tools" 数组
如果返回 error,检查 Lambda CloudWatch 日志
2. 检查 Lambda 环境变量是否设置正确
aws lambda get-function-configuration --function-name McpServerFunction --query 'Environment'
3. 确认 HOLYSHEEP_API_KEY 不是占位符 "YOUR_HOLYSHEEP_API_KEY"
👉 登录 https://www.holysheep.ai 获取真实 Key
报错三:API Gateway 返回 403 "Forbidden"
# 原因:API Key 认证已开启,但请求头中未携带 x-api-key
解决:curl 请求时加上 API Key header
curl -X POST https://YOUR_API_ID.execute-api.us-east-1.amazonaws.com/prod/mcp \
-H "Content-Type: application/json" \
-H "x-api-key: YOUR_ACTUAL_API_KEY" \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0.0"}}}'
或者在 CDK 中临时禁用 API Key(仅测试环境):
将 usagePlan 和 apiKey 相关代码注释掉,重新部署
报错四:Lambda 超时,但 HolySheep API 正常
# 检查是否有未 await 的异步调用
错误写法:
async function badHandler() {
callHolySheep(prompt); // ❌ 没有 await
return { result: "ok" };
}
正确写法:
async function goodHandler() {
const response = await callHolySheep(prompt); // ✅ await
return { result: response };
}
另外确认 Lambda timeout 设置足够:
CDK 中设置为 60s:timeout: cdk.Duration.seconds(60)
MCP 工具调用(特别是带 AI 对话)可能需要更长时间
报错五:CORS 错误 "No 'Access-Control-Allow-Origin' header"
# 原因:Lambda 返回的 headers 中缺少 CORS 头
解决:确认 index.ts 中每个返回路径都包含 corsHeaders
❌ 错误示例:
return { statusCode: 200, body: JSON.stringify(data) };
✅ 正确示例:
return {
statusCode: 200,
headers: { "Content-Type": "application/json", ...corsHeaders },
body: JSON.stringify(data)
};
OPTIONS 请求处理也要确保返回 200:
if (event.httpMethod === "OPTIONS") {
return { statusCode: 200, headers: corsHeaders, body: "" };
}
总结与购买建议
AWS Lambda + API Gateway 方案适合已有 AWS 基础设施、需要精细控制成本、追求企业级可用性的团队。月均 $1~10 的基础设施成本,配合 HolySheep API 的 ¥1=$1 汇率,比官方省 85%+。
但如果你的优先级是:
- 🚀 快速上线(不想折腾 CDK/IaC)
- 💰 极致性价比(微信/支付宝充值,无损汇率)
- 🌏 国内直连(<50ms 延迟,无需代理)
直接使用 HolySheep AI 的 MCP 云端服务是更明智的选择。注册即送免费额度,20+ 预置 MCP Servers,零部署成本。