Skip to content

almahdi/aws-lambda-mcp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 

Repository files navigation

MCP (Model Context Protocol) AWS Lambda Implementation

A comprehensive implementation of the Model Context Protocol (MCP) using AWS Lambda functions, featuring both server and client components for building AI-powered serverless applications.

Overview

This repository demonstrates a complete MCP implementation with:

  • MCP Server: An AWS Lambda function that exposes tools through the Model Context Protocol
  • MCP Client: An AWS Lambda function that consumes MCP tools using an AI agent
  • Infrastructure: CloudFormation templates and deployment scripts for AWS

The implementation showcases how to build scalable AI applications using serverless architecture with MCP tools that can be consumed by AI agents.

Project Structure

mcp/
├── server/                     # MCP Server Lambda function
│   ├── lambda_function.py      # Server implementation with MCP tools
│   ├── template.yaml          # SAM template for deployment
│   ├── install-packages.ps1   # Install dependencies
│   ├── package.ps1            # Package for deployment
│   ├── cleanup.ps1            # Clean up build artifacts
│   └── .gitignore             # Git ignore rules
├── client/                     # MCP Client Lambda function
│   ├── lambda_function.py      # Client implementation with AI agent
│   ├── install-packages.ps1   # Install dependencies
│   ├── package.ps1            # Package for deployment
│   ├── cleanup.ps1            # Clean up build artifacts
│   └── .gitignore             # Git ignore rules
├── README.md                   # This file
└── LICENSE                     # MIT License

Components

MCP Server (server/)

The MCP server is an AWS Lambda function that implements the Model Context Protocol, exposing various tools that can be called by MCP clients:

Available Tools:

  • hello_mcp(name: str) - Greets users with their name
  • add_numbers(a: int, b: int) - Adds two numbers
  • roll_dice() - Returns a random number between 1-6
  • echo_message(message: str) - Echoes back the provided message

Key Features:

  • Built using aws-lambda-powertools for observability
  • Uses awslabs.mcp-lambda-handler for MCP protocol implementation
  • Deployed with AWS SAM (Serverless Application Model)
  • RESTful API endpoint for MCP communication

MCP Client (client/)

The MCP client is an AWS Lambda function that uses an AI agent to interact with MCP tools:

Key Features:

  • Uses strands-agents for AI agent functionality
  • Connects to MCP servers via HTTP streaming
  • Processes natural language requests and maps them to tool calls
  • Returns AI-generated responses based on tool outputs

Example Usage:

{
  "message": "add the numbers 5 and 10"
}

Prerequisites

  • AWS CLI configured with appropriate permissions
  • AWS SAM CLI installed
  • PowerShell 5.0 or later
  • Python 3.13
  • pip package manager

Deployment

Server Deployment

  1. Install Dependencies:

    cd server
    .\install-packages.ps1
  2. Package the Application:

    .\package.ps1
  3. Deploy with SAM:

    sam deploy --guided

Client Deployment

  1. Install Dependencies:

    cd client
    .\install-packages.ps1
  2. Update the MCP Server URL: Edit lambda_function.py and update the server URL in the streamablehttp_client call.

  3. Package the Application:

    .\package.ps1
  4. Deploy to AWS Lambda: Upload the deployment-package.zip to your AWS Lambda function.

Development

PowerShell Scripts

The repository includes several PowerShell scripts for managing dependencies, packaging, and deployment:

Server Scripts (server/)

  • install-packages.ps1 - Installs Python dependencies for the MCP server

    • Downloads aws-lambda-powertools and awslabs.mcp-lambda-handler
    • Targets Linux x86_64 platform for Lambda compatibility
    • Creates dependencies in the package/ directory
  • package.ps1 - Creates deployment package for AWS Lambda

    • Combines package dependencies with lambda_function.py
    • Creates deployment-package.zip ready for Lambda deployment
    • Includes compression optimization and size reporting
  • cleanup.ps1 - Removes build artifacts and temporary files

    • Deletes the package/ directory
    • Removes deployment-package.zip
    • Useful for clean rebuilds

Client Scripts (client/)

  • install-packages.ps1 - Installs Python dependencies for the MCP client

    • Downloads aws-lambda-powertools and strands-agents
    • Targets Linux x86_64 platform for Lambda compatibility
    • Creates dependencies in the package/ directory
  • package.ps1 - Creates deployment package for AWS Lambda

    • Combines package dependencies with lambda_function.py
    • Creates deployment-package.zip ready for Lambda deployment
    • Includes compression optimization and size reporting
  • cleanup.ps1 - Removes build artifacts and temporary files

    • Deletes the package/ directory
    • Removes deployment-package.zip
    • Useful for clean rebuilds

All scripts include proper copyright headers and MIT license references.

Lambda Functions

Both Lambda function files include comprehensive documentation and licensing:

Server Lambda (server/lambda_function.py)

  • Purpose: Implements MCP server with tool definitions
  • Tools Available:
    • hello_mcp() - Greeting function
    • add_numbers() - Mathematical operations
    • roll_dice() - Random number generation
    • echo_message() - Message echoing
  • Dependencies: aws-lambda-powertools, awslabs.mcp-lambda-handler
  • Handler: lambda_handler(event, context) - Main entry point

Client Lambda (client/lambda_function.py)

  • Purpose: MCP client with AI agent for natural language processing
  • Features:
    • Natural language request processing
    • MCP tool discovery and execution
    • Intelligent response generation
    • Error handling and validation
  • Dependencies: strands-agents, mcp, HTTP streaming client
  • Handler: lambda_handler(event, context) - Processes user messages

Both Lambda functions include proper copyright headers and MIT license references.

Local Testing

Both components can be tested locally:

Server Testing:

# The server exposes tools that can be called via MCP protocol
# Test individual tools in the lambda_function.py

Client Testing:

# Run the client locally
if __name__ == "__main__":
    test_event = {"message": "add the numbers 5 and 10"}
    result = lambda_handler(test_event, None)
    print(json.dumps(result, indent=2))

Cleanup

To clean up build artifacts:

# In either server/ or client/ directory
.\cleanup.ps1

Dependencies

Server Dependencies

  • aws-lambda-powertools - AWS Lambda utilities and observability
  • awslabs.mcp-lambda-handler - MCP protocol implementation for Lambda

Client Dependencies

  • aws-lambda-powertools - AWS Lambda utilities and observability
  • strands-agents - AI agent framework
  • mcp - Model Context Protocol client library

API Reference

Server Endpoint

POST /mcp

  • Content-Type: application/json
  • Handles MCP protocol requests

Client Endpoint

POST (Lambda function URL or API Gateway)

{
  "message": "Your natural language request"
}

Response:

{
  "statusCode": 200,
  "body": {
    "response": "AI agent response based on tool execution"
  }
}

Configuration

Environment Variables

Both Lambda functions can be configured with environment variables for:

  • Logging levels
  • MCP server endpoints
  • AWS service configurations

Memory and Timeout

  • Server: 128MB memory, 10-second timeout
  • Client: Recommended 512MB+ memory for AI processing

Error Handling

The implementation includes comprehensive error handling:

  • Input validation
  • MCP protocol error handling
  • AWS Lambda error responses
  • Graceful degradation for network issues

Security Considerations

  • Use IAM roles with least privilege principles
  • Implement input validation and sanitization
  • Consider API Gateway authentication for production use
  • Monitor CloudWatch logs for security events

Monitoring

Both components integrate with AWS observability services:

  • CloudWatch Logs for application logging
  • CloudWatch Metrics for performance monitoring
  • AWS X-Ray for distributed tracing (optional)

Author

Ali Almahdihttps://www.ali.ac

Training Note

This repository is used as part of the training provided by Ali Almahdi. The code and examples are included for teaching and demonstration purposes to students.

Contributions

No contributions will be accepted for this repository. The content is maintained for training and reference only.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Additional Resources

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published