Skip to content
Back to search

aws-lambda-mcp-cookbook

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.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/ran-isenberg--aws-lambda-mcp-cookbook/badge.svg)](/listings/ran-isenberg--aws-lambda-mcp-cookbook)

HTML

<a href="/listings/ran-isenberg--aws-lambda-mcp-cookbook"><img src="/api/listings/ran-isenberg--aws-lambda-mcp-cookbook/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

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}
make dev
make deploy

Check out the official [Documentation](https://ran-isenberg.github.io/aws-lambda-mcp-cookbook/).

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

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 305 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # AWS Lambda MCP Cookbook (Python)
  2. [![license](https://img.shields.io/github/license/ran-isenberg/aws-lambda-mcp-cookbook)](https://github.com/ran-isenberg/aws-lambda-mcp-cookbook/blob/master/LICENSE)
  3. ![PythonSupport](https://img.shields.io/static/v1?label=python&message=3.14&color=blue?style=flat-square&logo=python)
  4. [![codecov](https://codecov.io/github/ran-isenberg/aws-lambda-mcp-cookbook/graph/badge.svg?token=x9asxTtNQZ)](https://codecov.io/github/ran-isenberg/aws-lambda-mcp-cookbook)
  5. ![version](https://img.shields.io/github/v/release/ran-isenberg/aws-lambda-mcp-cookbook)
  6. ![github-star-badge](https://img.shields.io/github/stars/ran-isenberg/aws-lambda-mcp-cookbook.svg?style=social)
  7. ![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/ran-isenberg/aws-lambda-mcp-cookbook/badge)
  8. ![issues](https://img.shields.io/github/issues/ran-isenberg/aws-lambda-mcp-cookbook)
  9. <a href="https://ranthebuilder.cloud/">
  10. <img src="https://github.com/ran-isenberg/aws-lambda-mcp-cookbook/blob/main/docs/media/banner.png?raw=true" width="800" alt="Ran The Builder - Master Serverless and Platform Engineering" />
  11. </a>
  12. This project provides a working, open source based, AWS Lambda based Python MCP server implementation.
  13. It is built on the AWS Lambda Web Adapter and the official [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) (`mcp` v2), so it speaks the current `2026-07-28` MCP spec as well as older handshake-era clients.
  14. It contains an opinionated implementation including DEPLOYMENT code with CDK and a CI/CD pipeline, testing, observability and more (see Features section).
  15. This project is a blueprint for new Serverless MCP servers.
  16. **[📜Documentation](https://ran-isenberg.github.io/aws-lambda-mcp-cookbook/)** | **[Blogs website](https://www.ranthebuilder.cloud)**
  17. > **Contact details | mailto:ran.isenberg@ranthebuilder.cloud**
  18. [![Twitter Follow](https://img.shields.io/twitter/follow/IsenbergRan?label=Follow&style=social)](https://twitter.com/RanBuilder)
  19. [![Website](https://img.shields.io/badge/Website-www.ranthebuilder.cloud-blue)](https://www.ranthebuilder.cloud/)
  20. ## Getting Started
  21. You can start with a clean service out of this blueprint repository without using the 'Template' button on GitHub.
  22. **That's it, you are ready to deploy the MCP server (make sure Docker is running!):**
  23. ```bash
  24. cd {new repo folder}
  25. make dev
  26. make deploy
  27. ```
  28. Check out the official [Documentation](https://ran-isenberg.github.io/aws-lambda-mcp-cookbook/).
  29. You can also run 'make pr' will run all checks, synth, file formatters , unit tests, deploy to AWS and run integration and E2E tests.
  30. ## **The Problem**
  31. Starting a Serverless MCP can be overwhelming. You need to figure out many questions and challenges that have nothing to do with your business domain:
  32. * How to deploy to the cloud? What IAC framework do you choose?
  33. * How to write a SaaS-oriented CI/CD pipeline? What does it need to contain?
  34. * How do you handle observability, logging, tracing, metrics?
  35. * How do you write a well-structured Lambda function?
  36. * How do you handle testing?
  37. * What makes an AWS Lambda handler resilient, traceable, and easy to maintain? How do you write such a code?
  38. ## **The Solution**
  39. This project aims to reduce cognitive load and answer these questions for you by providing an opinionated Python Serverless MCP server blueprint that implements best practices for AWS Lambda, MCP, Serverless CI/CD, and AWS CDK in one project.
  40. This project is a blueprint for new Serverless MCP servers.
  41. ```mermaid
  42. flowchart LR
  43. agents["MCP clients<br/>agents, IDEs"]
  44. waf["AWS WAF<br/>optional - see note"]
  45. gw["Amazon API Gateway<br/>HTTP API v2 · ANY proxy route"]
  46. subgraph fn["AWS Lambda · ARM64 · Python 3.14"]
  47. direction TB
  48. adapter["Lambda Web Adapter<br/>layer via AWS_LAMBDA_EXEC_WRAPPER"]
  49. uvi["uvicorn on :8000"]
  50. app["MCP server · mcp v2<br/>streamable_http_app at /mcp<br/>stateless_http · json_response"]
  51. adapter --> uvi --> app
  52. end
  53. ddb[("Amazon DynamoDB<br/>provisioned for app state")]
  54. cw["CloudWatch<br/>logs · metrics · dashboards · alarms"]
  55. xray["AWS X-Ray"]
  56. agents -->|"MCP over Streamable HTTP"| gw
  57. waf -.-> gw
  58. gw --> adapter
  59. app -.->|"unused by default"| ddb
  60. app --> cw
  61. app --> xray
  62. classDef optional stroke-dasharray: 5 5
  63. class waf,ddb optional
  64. ```
  65. > **AWS WAF is not attached today.** WAF cannot front an API Gateway **HTTP** API (v2) - only a REST API. `WafToApiGatewayConstruct` in `cdk/service/waf_construct.py` is kept as a working reference: wire it up if you switch the edge to a REST API GW.
  66. >
  67. > **DynamoDB is provisioned but unread.** The `2026-07-28` protocol is stateless, so nothing touches the table out of the box - see [Session data and DynamoDB](#session-data-and-dynamodb).
  68. ### Serverless Lambda Web Adapter & the official MCP Python SDK
  69. Based on [AWS Lambda Web Adapter](https://github.com/awslabs/aws-lambda-web-adapter) and the official [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) (`mcp` v2).
  70. Use an HTTP API GW and Lambda function. Can be used with a REST API GW with a custom domain too.
  71. The server is a plain ASGI (Starlette) app served by uvicorn behind the Lambda Web Adapter, so it upholds the official MCP protocol and has a native auth mechanism (OAuth).
  72. The MCP surface is split by capability kind, mirroring the business logic layout so each protocol binding sits opposite the logic it exposes:
  73. ```text
  74. service/
  75. app.py the ASGI app uvicorn serves - assembles everything below
  76. mcp_app/
  77. mcp_server.py the MCPServer instance, its identity and instructions
  78. caching.py cache hints advertised on catalog listings
  79. context.py AppContext + lifespan (shared, per-process state)
  80. handlers/
  81. __init__.py imports the modules below - this is what registers them
  82. tools.py -> service/logic/math.py
  83. resources.py -> service/logic/profiles.py
  84. prompts.py -> service/logic/hld.py
  85. ```
  86. A handler binds the protocol to a logic function and declares how clients may treat it - see [service/mcp_app/handlers/tools.py](service/mcp_app/handlers/tools.py):
  87. ```python
  88. from mcp.types import ToolAnnotations
  89. from service.handlers.utils.observability import logger
  90. from service.logic.math import add_two_numbers
  91. from service.mcp_app.mcp_server import mcp
  92. @mcp.tool(
  93. title='Add two numbers',
  94. annotations=ToolAnnotations( # lets clients decide what may run without asking
  95. read_only_hint=True,
  96. idempotent_hint=True,
  97. open_world_hint=False,
  98. ),
  99. )
  100. def math(a: int, b: int) -> int:
  101. """Add two numbers together"""
  102. logger.info('using math tool', extra={'a': a, 'b': b})
  103. return add_two_numbers(a, b)
  104. ```
  105. > **Capabilities register on import.** `@mcp.tool()`, `@mcp.resource()` and `@mcp.prompt()` register when their module is imported, so a new handler module must be imported in [service/mcp_app/handlers/__init__.py](service/mcp_app/handlers/__init__.py). Forget it and the capability is silently missing from the catalog rather than raising - the listing tests in `tests/integration/test_mcp_server.py` are what catch that.
  106. ### Protocol versions
  107. `streamable_http_app()` serves **both** MCP protocol eras from the same endpoint, routed per request by the `MCP-Protocol-Version` header:
  108. * `2026-07-28` - the current stateless spec: no `initialize` handshake, no `Mcp-Session-Id`.
  109. * `2025-11-25` and earlier - the handshake era, for clients that have not migrated yet.
  110. There is nothing to configure; both are always on.
  111. ### Session data and DynamoDB
  112. The `2026-07-28` protocol is stateless: no `initialize` handshake, no `Mcp-Session-Id`, and the server runs with `stateless_http=True`. Nothing is carried between requests for you.
  113. That is a protocol change, not a restriction on your application. **The stack still provisions a DynamoDB table and passes its name to the Lambda as `TABLE_NAME`, so you can use it to store session or conversation state whenever you want it.** Nothing reads it out of the box - it is there for you to build on.
  114. The `lifespan` yields a shared context object, and the table is resolved from `TABLE_NAME` on first use and reused thereafter - so the server still boots without any environment configured. A handler reaches it through the injected `Context`. The approach the spec recommends is a server-minted handle: your tool writes state to DynamoDB under a key it generates, returns that key to the client, and the client passes it back as an ordinary tool argument on the next call.
  115. ```python
  116. from mcp.server.mcpserver import Context
  117. @mcp.tool()
  118. def start_analysis(dataset: str, ctx: Context) -> str:
  119. """Begin an analysis and return a handle to resume it."""
  120. handle = str(uuid.uuid4())
  121. ctx.request_context.lifespan_context.table.put_item(Item={'session_id': handle, 'dataset': dataset})
  122. return handle
  123. @mcp.tool()
  124. def continue_analysis(handle: str, ctx: Context) -> str:
  125. """Continue an analysis previously started with start_analysis."""
  126. state = ctx.request_context.lifespan_context.table.get_item(Key={'session_id': handle})['Item']
  127. ...
  128. ```
  129. The table's partition key is `session_id`, and the Lambda role already grants `GetItem`, `PutItem`, `UpdateItem` and `DeleteItem` on it.
  130. > **Note:** a handle is a bearer token - anyone holding it can read that state. Bind it to the caller's identity rather than trusting the handle alone.
  131. ### **Monitoring Design**
  132. ```mermaid
  133. flowchart LR
  134. subgraph sources["Monitored resources"]
  135. direction TB
  136. gw["HTTP API Gateway"]
  137. fn["Lambda function"]
  138. logs["CloudWatch Logs<br/>ERROR pattern widget"]
  139. ddb[("DynamoDB table")]
  140. kpi["Custom metric<br/>ValidMcpEvents"]
  141. end
  142. subgraph high["High level dashboard"]
  143. direction TB
  144. h1["API Gateway health"]
  145. h2["Daily MCP Requests"]
  146. end
  147. subgraph low["Low level dashboard"]
  148. direction TB
  149. l1["Lambda latency, errors,<br/>throttles, invocations"]
  150. l2["Error log widget"]
  151. l3["DynamoDB usage, latency,<br/>errors, throttles"]
  152. end
  153. alarms["CloudWatch alarms<br/>5xx error rate · p90 latency"]
  154. sns["SNS topic<br/>KMS encrypted"]
  155. gw --> h1
  156. kpi --> h2
  157. fn --> l1
  158. logs --> l2
  159. ddb --> l3
  160. h1 --> alarms
  161. l1 --> alarms
  162. l2 --> alarms
  163. alarms --> sns
  164. ```
  165. <br></br>
  166. ### **Features**
  167. * Python Serverless MCP server with a recommended file structure.
  168. * Official MCP Python SDK v2 - supports the current `2026-07-28` spec and older clients alike.
  169. * MCP Tools input validation: check argument types and values
  170. * Tests - unit, integration (in-process MCP client against the real server) and E2E with a real MCP client
  171. * CDK infrastructure with infrastructure tests and security tests.
  172. * CI/CD pipelines based on Github actions that deploys to AWS with python linters, complexity checks and style formatters.
  173. * CI/CD pipeline deploys to dev/staging and production environments with different gates between each environment
  174. * Makefile for simple developer experience.
  175. * The AWS Lambda handler embodies Serverless best practices and has all the bells and whistles for a well-structured handler.
  176. * AWS Lambda handler uses [AWS Lambda Powertools](https://docs.powertools.aws.dev/lambda-python/).
  177. * AWS Lambda handler 3 layer architecture: handler layer, logic layer and data access layer
  178. * CloudWatch dashboards - High level and low level including CloudWatch alarms
  179. ## CDK Deployment
  180. The CDK code creates an HTTP API GW that proxies every path to the Lambda, which serves MCP at /mcp.
  181. The AWS Lambda handler uses a Lambda layer optimization: `make build` exports the runtime dependencies from `pyproject.toml` with `uv export`, and CDK bundles them into a layer via Docker.
  182. To package extra dependencies, add them to the `dependencies` list in `pyproject.toml`.
  183. ## Serverless Best Practices
  184. The AWS Lambda handler will implement multiple best practice utilities.
  185. Each utility is implemented when a new blog post is published about that utility.
  186. The utilities cover multiple aspects of a well-structured service, including:
  187. * [Logging](https://www.ranthebuilder.cloud/post/aws-lambda-cookbook-elevate-your-handler-s-code-part-1-logging)
  188. * [Observability: Monitoring and Tracing](https://www.ranthebuilder.cloud/post/aws-lambda-cookbook-elevate-your-handler-s-code-part-2-observability)
  189. * [Observability: Business KPIs Metrics](https://www.ranthebuilder.cloud/post/aws-lambda-cookbook-elevate-your-handler-s-code-part-3-business-domain-observability)
  190. * [Environment Variables](https://www.ranthebuilder.cloud/post/aws-lambda-cookbook-environment-variables)
  191. * [Input Validation](https://www.ranthebuilder.cloud/post/aws-lambda-cookbook-elevate-your-handler-s-code-part-5-input-validation)
  192. * [Hexagonal Architecture](https://www.ranthebuilder.cloud/post/learn-how-to-write-aws-lambda-functions-with-architecture-layers)
  193. * [CDK Best practices](https://github.com/ran-isenberg/aws-lambda-mcp-cookbook)
  194. * [Serverless Monitoring](https://www.ranthebuilder.cloud/post/how-to-effortlessly-monitor-serverless-applications-with-cloudwatch-part-one)
  195. ## Security
  196. * Use the SDK's `auth` parameter on `MCPServer` for an OAuth implementation, or put an IAM/Cognito/Lambda authorizer in front of the API Gateway.
  197. * DNS rebinding protection is switched off in [service/app.py](service/app.py). That check exists to protect a server bound to a local port from browsers on the same machine; under the Lambda Web Adapter the app only listens on loopback inside the execution environment and API Gateway forwards its own Host header, so leaving it on would reject every request with `421 Misdirected Request`. API Gateway is where authn/authz belongs here.
  198. * AWS WAF is **not** attached - see the note under the architecture diagram above.
  199. ### Known Issues
  200. * There might be security issues with this implementation, MCP is very new and has many issues.
  201. ## Code Contributions
  202. Code contributions are welcomed. Read this [guide.](https://github.com/ran-isenberg/aws-lambda-mcp-cookbook/blob/main/CONTRIBUTING.md)
  203. ## Code of Conduct
  204. Read our code of conduct [here.](https://github.com/ran-isenberg/aws-lambda-mcp-cookbook/blob/main/CODE_OF_CONDUCT.md)
  205. ## Connect
  206. - Email: ran.isenberg@ranthebuilder.cloud
  207. - Blog: https://www.ranthebuilder.cloud
  208. - Bluesky: [@ranthebuilder.cloud](https://bsky.app/profile/ranthebuilder.cloud)
  209. - X: [@RanBuilder](https://twitter.com/RanBuilder)
  210. - LinkedIn: https://www.linkedin.com/in/ranbuilder/
  211. ## Credits
  212. * [AWS Lambda Powertools (Python)](https://github.com/aws-powertools/powertools-lambda-python)
  213. * [AWS Lambda Handler cookbook](https://ran-isenberg.github.io/aws-lambda-handler-cookbook/)
  214. * [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk)
  215. * [AWS Lambda Web adapter](https://github.com/awslabs/aws-lambda-web-adapter)
  216. ## License
  217. This library is licensed under the MIT License. See the [LICENSE](https://github.com/ran-isenberg/aws-lambda-mcp-cookbook/blob/main/LICENSE) file.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.