# Terraform Deployment Guide
This directory contains Terraform configuration for deploying the MCP Gateway POC to AWS.
## Prerequisites
1. **Terraform** installed (>= 1.0)
```bash
# Install via Homebrew (macOS)
brew install terraform
# Or download from https://www.terraform.io/downloads
```
2. **AWS CLI** configured
```bash
aws configure
```
3. **AWS Credentials** with appropriate permissions:
- Lambda (create, update, delete functions)
- API Gateway (create, update, delete APIs)
- IAM (create roles and policies)
- CloudWatch Logs (create log groups)
## Quick Start
### 1. Configure Variables
Copy the example variables file:
```bash
cp terraform.tfvars.example terraform.tfvars
```
Edit `terraform.tfvars` with your values:
```hcl
aws_region = "us-east-1"
environment = "dev"
log_retention_days = 7
# Python Dependencies Lambda Layer (Required)
# Create using: ./create_dependencies_layer.sh 3.11 mcp-dependencies-python311 us-east-1 ../requirements.txt
python_dependencies_layer_arn = "arn:aws:lambda:us-east-1:YOUR_ACCOUNT:layer:mcp-dependencies-python311:1"
```
**Important**: Before deploying, you must create the Python dependencies layer:
```bash
./create_dependencies_layer.sh 3.11 mcp-dependencies-python311 us-east-1 ../requirements.txt
```
This creates a Lambda layer with all dependencies built for Linux x86_64 (Lambda's architecture).
### 2. Initialize Terraform
```bash
cd terraform
terraform init
```
### 3. Review Plan
```bash
terraform plan
```
This will show you what resources will be created.
### 4. Deploy
```bash
terraform apply
```
Type `yes` when prompted to confirm.
### 5. Get Outputs
After deployment, get the API Gateway URL:
```bash
terraform output mcp_gateway_api_url
```
## Configuration
### Backend Configuration
By default, Terraform uses local state. For production, configure an S3 backend:
1. Edit `main.tf` and uncomment the backend block:
```hcl
backend "s3" {
bucket = "your-terraform-state-bucket"
key = "mcp-gateway/terraform.tfstate"
region = "us-east-1"
}
```
2. Create the S3 bucket:
```bash
aws s3 mb s3://your-terraform-state-bucket --region us-east-1
```
3. Enable versioning:
```bash
aws s3api put-bucket-versioning \
--bucket your-terraform-state-bucket \
--versioning-configuration Status=Enabled
```
### Variables
Key variables you can customize:
- `aws_region`: AWS region (default: us-east-1)
- `environment`: Environment name (default: dev)
- `log_retention_days`: CloudWatch log retention (default: 7)
- `python_dependencies_layer_arn`: ARN of Python dependencies Lambda layer (required for MCP Gateway and REST API Server)
- `httpx_layer_arn`: ARN of httpx-only layer (optional, not needed if using python_dependencies_layer_arn)
## What Gets Deployed
The Terraform configuration creates:
1. **Lambda Functions**:
- MCP Gateway function (with Python dependencies layer)
- Weather Tool function
- Calculator Tool function
- Data Lookup Tool function
- REST API Server function (FastAPI with Mangum, with Python dependencies layer)
2. **IAM Roles and Policies**:
- Role for MCP Gateway (with Lambda invoke and STS permissions)
- Role for Tool Lambda functions (with CloudWatch Logs permissions)
3. **API Gateways**:
- MCP Gateway API - REST API for MCP protocol, POST endpoint at `/mcp`
- REST API Server API - FastAPI endpoints (stock/price, time/current, text/summarize)
4. **CloudWatch Log Groups**:
- Log groups for each Lambda function
## Post-Deployment
### Tools Auto-Registration
Tools are automatically registered when the Lambda function loads:
- **Lambda Tools**: Automatically registered based on environment and account ID
- **REST Tools**: Automatically registered if `REST_API_SERVER_API_ID` environment variable is set
No manual registration needed! The gateway will have these tools available:
- `weather_lookup` - Weather information tool
- `calculator` - Mathematical operations tool
- `data_lookup` - Data lookup tool
- `stock_price` - Stock price information (REST API)
- `current_time` - Current UTC time (REST API)
- `summarize_text` - Text summarization (REST API)
### Test the Gateway
```bash
# Get the API Gateway URL
GATEWAY_URL=$(terraform output -raw mcp_gateway_api_url)
# List tools
curl -X POST $GATEWAY_URL \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list",
"params": {}
}'
```
## Updating Resources
To update resources:
```bash
terraform plan # Review changes
terraform apply # Apply changes
```
## Destroying Resources
To remove all resources:
```bash
terraform destroy
```
Type `yes` when prompted.
## Troubleshooting
### Lambda Function Not Found
- Check that the source directories exist
- Verify the handler paths are correct
- Check Lambda function logs in CloudWatch
### API Gateway 500 Errors
- Check Lambda function logs
- Verify Lambda permissions for API Gateway
- Check API Gateway logs in CloudWatch
### Terraform State Issues
- If using S3 backend, verify bucket exists and is accessible
- Check IAM permissions for state bucket access
## Comparison with SAM
| Feature | Terraform | SAM |
|---------|-----------|-----|
| State Management | Terraform state (local or S3) | CloudFormation |
| Language | HCL | YAML/JSON |
| Lambda Packaging | Manual zip files | Automatic |
| Flexibility | High | Medium |
| Learning Curve | Steeper | Gentler |
## Best Practices
1. **Use Remote State**: Configure S3 backend for team collaboration
2. **Version Control**: Don't commit `terraform.tfvars` (contains sensitive data)
3. **Tag Resources**: All resources are tagged with environment
4. **Review Plans**: Always review `terraform plan` before applying
5. **Separate Environments**: Use different state files for dev/staging/prod
## Additional Resources
- [Terraform AWS Provider Documentation](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)
- [Terraform Best Practices](https://www.terraform.io/docs/cloud/guides/recommended-practices/index.html)
- [AWS Lambda with Terraform](https://learn.hashicorp.com/tutorials/terraform/lambda-api-gateway)
## Notes
- Lambda function code is packaged from source directories
- The `lambda_packages/` directory is created automatically (gitignored)
- All resources are tagged with environment and project name
- CloudWatch Log Groups are created with configurable retention
- Python dependencies layer must be built with Docker for correct architecture (Linux x86_64)
- Tools are automatically registered on Lambda function initialization
- REST API Server uses Mangum to run FastAPI in Lambda