Skip to content

This repository provides a working, deployable, open source-based, serverless MCP server blueprint with an AWS Lambda function and AWS CDK Python code with all the best practices and a complete CI/CD pipeline.

License

Notifications You must be signed in to change notification settings

ran-isenberg/aws-lambda-mcp-cookbook

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AWS Lambda MCP Cookbook (Python)

license PythonSupport codecov version github-star-badge OpenSSF Scorecard issues

banner

This project provides a working, open source based, pure AWS Lambda based Python MCP server implementation.

It contains a production grade implementation including DEPLOYMENT code with CDK and a CI/CD pipeline, testing, observability and more (see Features section).

NO Lambda adapter, no FastMCP - just pure Lambda as it was meant to be.

This project is a blueprint for new Serverless MCP servers.

It's based on AWS sample for MCP - but had major refactors since, combined with the AWS Lambda Handler cookbook template.

📜Documentation | Blogs website

Contact details | mailto:[email protected]

Twitter Follow Website

Getting Started

You can start with a clean service out of this blueprint repository without using the 'Template' button on GitHub.

That's it, you are ready to deploy the MCP server (make sure Docker is running!):

cd {new repo folder}
poetry env activate
poetry install
make deploy

Check out the official Documentation.

Make sure you have poetry v2 and above.

You can also run 'make pr' will run all checks, synth, file formatters , unit tests, deploy to AWS and run integration and E2E tests.

The Problem

Starting a production grade Serverless MCP can be overwhelming. You need to figure out many questions and challenges that have nothing to do with your business domain:

  • How to deploy to the cloud? What IAC framework do you choose?
  • How to write a SaaS-oriented CI/CD pipeline? What does it need to contain?
  • How do you handle observability, logging, tracing, metrics?
  • How do you write a production grade Lambda function?
  • How do you handle testing?
  • What makes an AWS Lambda handler resilient, traceable, and easy to maintain? How do you write such a code?

The Solution

This project aims to reduce cognitive load and answer these questions for you by providing a production grade Python Serverless MCP server blueprint that implements best practices for AWS Lambda, MCP, Serverless CI/CD, and AWS CDK in one project.

The MCP server uses JSON RPC over HTTP (non stream-able) via API Gateway's body payload parameter. See integration tests and see how the test event is generated.

from aws_lambda_env_modeler import init_environment_variables
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.metrics import MetricUnit
from aws_lambda_powertools.utilities.typing import LambdaContext

from service.handlers.models.env_vars import McpHandlerEnvVars
from service.handlers.utils.authentication import authenticate
from service.handlers.utils.mcp import mcp
from service.handlers.utils.observability import logger, metrics, tracer
from service.logic.math import add_two_numbers
from service.mcp_lambda_handler.session_data import SessionData


@mcp.tool()
def math(a: int, b: int) -> int:
    """Add two numbers together"""
    if not isinstance(a, int) or not isinstance(b, int):
        raise ValueError('Invalid input: a and b must be integers')

    # Uncomment the following line if you want to use session data
    # session_data: Optional[SessionData] = mcp.get_session()

    # call logic layer
    result = add_two_numbers(a, b)

    # save session data
    mcp.set_session(data={'result': result})

    metrics.add_metric(name='ValidMcpEvents', unit=MetricUnit.Count, value=1)
    return result


@init_environment_variables(model=McpHandlerEnvVars)
@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
@metrics.log_metrics
@tracer.capture_lambda_handler(capture_response=False)
def lambda_handler(event: dict, context: LambdaContext) -> dict:
    authenticate(event, context)
    return mcp.handle_request(event, context)

Serverless MCP Template

  • The project deploys an API GW with an AWS Lambda integration under the path POST /mcp/ and stores session data in a DynamoDB table.

design

Monitoring Design

monitoring_design

Features

  • PURE Lambda - not web adapter, no FastMCP required!
  • Python Serverless MCP server with a recommended file structure.
  • MCP Tools input validation: check argument types and values
  • Tests - unit, integration (tests for full MCP messages) and E2E with a real MCP client
  • CDK infrastructure with infrastructure tests and security tests.
  • CI/CD pipelines based on Github actions that deploys to AWS with python linters, complexity checks and style formatters.
  • CI/CD pipeline deploys to dev/staging and production environments with different gates between each environment
  • Makefile for simple developer experience.
  • The AWS Lambda handler embodies Serverless best practices and has all the bells and whistles for a proper production ready handler.
  • AWS Lambda handler uses AWS Lambda Powertools.
  • AWS Lambda handler 3 layer architecture: handler layer, logic layer and data access layer
  • Session context storage in DynamoDB - global getter and setter (get_session, set_session) - be advised, has security issue - need to match session id to user
  • API protected by WAF with four AWS managed rules in production deployment
  • CloudWatch dashboards - High level and low level including CloudWatch alarms

CDK Deployment

The CDK code create an API GW with a path of /mcp which triggers the lambda on 'POST' requests.

The AWS Lambda handler uses a Lambda layer optimization which takes all the packages under the [packages] section in the Pipfile and downloads them in via a Docker instance.

This allows you to package any custom dependencies you might have, just add them to the Pipfile under the [packages] section.

Serverless Best Practices

The AWS Lambda handler will implement multiple best practice utilities.

Each utility is implemented when a new blog post is published about that utility.

The utilities cover multiple aspect of a production-ready service, including:

Security

  • WAF connected in production accounts (requires having an environment variable during deployment called 'ENVIRONMENT' with a value of 'production')
  • Auth/Authz function placeholder in the mcp.py handler function - see authentication.py
  • It is recommended to either use IAM/Cognito/Lambda authorizer or use the authentication.py and implement identity provider token validation flow.

Known Issues:

  • There might be security issues with this implementation, MCP is very new and has many issues.
  • Session saving - there's no match validation between session id and user id/tenant id. This is a TODO item.
  • It is not possible to manually update session data, only fetch.

Code Contributions

Code contributions are welcomed. Read this guide.

Code of Conduct

Read our code of conduct here.

Connect

Credits

License

This library is licensed under the MIT License. See the LICENSE file.

About

This repository provides a working, deployable, open source-based, serverless MCP server blueprint with an AWS Lambda function and AWS CDK Python code with all the best practices and a complete CI/CD pipeline.

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published