ในบทความนี้ผมจะพาทุกคนไปสำรวจวิธีการ deploy MCP (Model Context Protocol) Server ไปยัง cloud ด้วย AWS Lambda และ API Gateway อย่างละเอียด พร้อมทั้งเปรียบเทียบความคุ้มค่าระหว่างการ self-host กับการใช้บริการ managed API อย่าง HolySheep AI ที่รองรับ multi-provider ในที่เดียว
ทำไมต้อง Deploy MCP Server ขึ้น Cloud?
MCP Server คือ middleware ที่ช่วยให้ AI agents สามารถเข้าถึง external tools และ data sources ได้อย่างเป็นมาตรฐาน การ deploy ขึ้น cloud ช่วยให้:
- ทีมหลายคนใช้งาน centralize MCP tools ร่วมกัน
- Scale automatically ตาม demand โดยไม่ต้องจัดการ infrastructure
- ประหยัด cost จากการ reuse compute resources
- มี monitoring และ logging แบบ centralized
AWS Lambda + API Gateway Architecture
สถาปัตยกรรมที่เราจะใช้ประกอบด้วย 3 ส่วนหลัก:
1. MCP Server Layer (Lambda Function)
# mcp_server/lambda_handler.py
import json
import boto3
from mcp.server import MCPServer
from mcp.types import Tool, Resource
Initialize MCP Server
server = MCPServer(
name="cloud-mcp-server",
version="1.0.0",
tools=[
Tool(
name="search_knowledge_base",
description="Search company knowledge base",
input_schema={
"type": "object",
"properties": {
"query": {"type": "string"},
"limit": {"type": "number", "default": 10}
},
"required": ["query"]
}
),
Tool(
name="get_weather",
description="Get current weather for location",
input_schema={
"type": "object",
"properties": {
"location": {"type": "string"}
},
"required": ["location"]
}
)
]
)
def lambda_handler(event, context):
"""Main Lambda handler for MCP requests"""
try:
method = event.get('httpMethod')
path = event.get('path')
body = json.loads(event.get('body', '{}')) if event.get('body') else {}
# Route MCP requests
if method == 'POST' and path == '/mcp/execute':
result = server.execute_tool(
name=body.get('tool'),
arguments=body.get('arguments', {})
)
return {
'statusCode': 200,
'body': json.dumps({'success': True, 'result': result}),
'headers': {'Content-Type': 'application/json'}
}
elif method == 'GET' and path == '/mcp/tools':
return {
'statusCode': 200,
'body': json.dumps({'tools': server.list_tools()}),
'headers': {'Content-Type': 'application/json'}
}
else:
return {
'statusCode': 404,
'body': json.dumps({'error': 'Endpoint not found'})
}
except Exception as e:
return {
'statusCode': 500,
'body': json.dumps({'error': str(e)})
}
2. Infrastructure as Code (Terraform)
# terraform/main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "ap-southeast-1"
}
Lambda Function
resource "aws_lambda_function" "mcp_server" {
function_name = "mcp-server-${var.environment}"
role = aws_iam_role.lambda_exec.arn
filename = "deployment_package.zip"
handler = "lambda_handler.lambda_handler"
runtime = "python3.11"
timeout = 30