Skip to content
Back to search

run-model-context-protocol-servers-with-aws-lambda

Run existing Model Context Protocol (MCP) stdio-based servers in AWS Lambda functions

Safety scan

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

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/awslabs--run-model-context-protocol-servers-with-aws-lambda/badge.svg)](/listings/awslabs--run-model-context-protocol-servers-with-aws-lambda)

HTML

<a href="/listings/awslabs--run-model-context-protocol-servers-with-aws-lambda"><img src="/api/listings/awslabs--run-model-context-protocol-servers-with-aws-lambda/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

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 · 954 lines

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

  1. # Run Model Context Protocol (MCP) servers with AWS Lambda
  2. [![PyPI - Downloads](https://img.shields.io/pypi/dm/run-mcp-servers-with-aws-lambda?style=for-the-badge&label=PyPi%20Downloads&color=blue)](https://pypi.org/project/run-mcp-servers-with-aws-lambda/)
  3. [![NPM Downloads](https://img.shields.io/npm/dm/%40aws%2Frun-mcp-servers-with-aws-lambda?style=for-the-badge&label=NPM%20Downloads&color=blue)](https://www.npmjs.com/package/@aws/run-mcp-servers-with-aws-lambda)
  4. This project enables you to run [Model Context Protocol](https://modelcontextprotocol.io) stdio-based servers in AWS Lambda functions.
  5. Currently, most implementations of MCP servers and clients are entirely local on a single machine.
  6. A desktop application such as an IDE or Claude Desktop initiates MCP servers locally as child processes
  7. and communicates with each of those servers over a long-running stdio stream.
  8. ```mermaid
  9. flowchart LR
  10. subgraph "Your Laptop"
  11. Host["Desktop Application<br>with MCP Clients"]
  12. S1["MCP Server A<br>(child process)"]
  13. S2["MCP Server B<br>(child process)"]
  14. Host <-->|"MCP Protocol<br>(over stdio stream)"| S1
  15. Host <-->|"MCP Protocol<br>(over stdio stream)"| S2
  16. end
  17. ```
  18. This library helps you to wrap existing stdio MCP servers into Lambda functions.
  19. You can invoke these function-based MCP servers from your application using the MCP protocol
  20. over short-lived HTTPS connections.
  21. Your application can then be a desktop-based app, a distributed system running in the cloud,
  22. or any other architecture.
  23. ```mermaid
  24. flowchart LR
  25. subgraph "Distributed System"
  26. App["Your Application<br>with MCP Clients"]
  27. S3["MCP Server A<br>(Lambda function)"]
  28. S4["MCP Server B<br>(Lambda function)"]
  29. App <-->|"MCP Protocol<br>(over HTTPS connection)"| S3
  30. App <-->|"MCP Protocol<br>(over HTTPS connection)"| S4
  31. end
  32. ```
  33. Using this library, the Lambda function will manage the lifecycle of your stdio MCP server.
  34. Each Lambda function invocation will:
  35. 1. Start the stdio MCP server as a child process
  36. 1. Initialize the MCP server
  37. 1. Forward the incoming request to the local server
  38. 1. Return the server's response to the function caller
  39. 1. Shut down the MCP server child process
  40. This library supports connecting to Lambda-based MCP servers in four ways:
  41. 1. The [MCP Streamable HTTP transport](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#streamable-http), using Amazon API Gateway. Typically authenticated using OAuth.
  42. 1. The MCP Streamable HTTP transport, using Amazon Bedrock AgentCore Gateway. Authenticated using OAuth.
  43. 1. A custom Streamable HTTP transport with support for SigV4, using a Lambda function URL. Authenticated with AWS IAM.
  44. 1. A custom Lambda invocation transport, using the Lambda Invoke API directly. Authenticated with AWS IAM.
  45. ## Determine your server parameters
  46. Many stdio-based MCP servers's documentation encourages using tools that download and run the server on-demand.
  47. For example, `uvx my-mcp-server` or `npx my-mcp-server`.
  48. These tools are often not pre-packaged in the Lambda environment, and it can be inefficient to
  49. re-download the server on every Lambda invocation.
  50. Instead, the examples in this repository show how to package the MCP server along with
  51. the Lambda function code, then start it with `python` or `node` (or `npx --offline`) directly.
  52. You will need to determine the right parameters depending on your MCP server's package.
  53. This can often be a trial and error process locally, since MCP server packaging varies.
  54. <details>
  55. <summary><b>Python server examples</b></summary>
  56. Basic example:
  57. ```python
  58. from mcp.client.stdio import StdioServerParameters
  59. server_params = StdioServerParameters(
  60. command=sys.executable,
  61. args=[
  62. "-m",
  63. "my_mcp_server_python_module",
  64. "--my-server-command-line-parameter",
  65. "some_value",
  66. ],
  67. )
  68. ```
  69. Locally, you would run this module using:
  70. ```bash
  71. python -m my_mcp_server_python_module --my-server-command-line-parameter some_value
  72. ```
  73. Other examples:
  74. ```bash
  75. python -m mcpdoc.cli # Note the sub-module
  76. python -c "from mcp_openapi_proxy import main; main()"
  77. python -c "import asyncio; from postgres_mcp.server import main; asyncio.run(main())"
  78. ```
  79. If you use Lambda layers, you need to also set the PYTHONPATH for the python sub-process:
  80. ```python
  81. lambda_paths = ["/opt/python"] + sys.path
  82. env_config = {"PYTHONPATH": ":".join(lambda_paths)}
  83. server_params = StdioServerParameters(
  84. command=sys.executable,
  85. args=[
  86. "-c",
  87. "from mcp_openapi_proxy import main; main()",
  88. ],
  89. env=env_config,
  90. )
  91. ```
  92. </details>
  93. <details>
  94. <summary><b>Typescript server examples</b></summary>
  95. Basic example:
  96. ```typescript
  97. const serverParams = {
  98. command: "npx",
  99. args: [
  100. "--offline",
  101. "my-mcp-server-typescript-module",
  102. "--my-server-command-line-parameter",
  103. "some_value",
  104. ],
  105. };
  106. ```
  107. Locally, you would run this module using:
  108. ```bash
  109. npx --offline my-mcp-server-typescript-module --my-server-command-line-parameter some_value
  110. ```
  111. Other examples:
  112. ```bash
  113. node /var/task/node_modules/@ivotoby/openapi-mcp-server/bin/mcp-server.js
  114. ```
  115. </details>
  116. ### Passing credentials and other secrets to the MCP server
  117. This library does not provide out-of-the-box mechanisms for managing any secrets needed by the wrapped
  118. MCP server. For example, the [GitHub MCP server](https://github.com/modelcontextprotocol/servers/tree/main/src/github)
  119. and the [Brave search MCP server](https://github.com/modelcontextprotocol/servers/tree/main/src/brave-search)
  120. require API keys to make requests to third-party APIs.
  121. You may configure these API keys as
  122. [encrypted environment variables](https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars-encryption.html)
  123. in the Lambda function's configuration or retrieve them from Secrets Manager in the Lambda function code (examples below).
  124. However, note that anyone with access to invoke the Lambda function
  125. will then have access to use your API key to call the third-party APIs by invoking the function.
  126. We recommend limiting access to the Lambda function using
  127. [least-privilege IAM policies](https://docs.aws.amazon.com/lambda/latest/dg/security-iam.html).
  128. If you use an identity-based authentication mechanism such as OAuth, you could also store and retrieve API keys per user but there are no implementation examples in this repository.
  129. <details>
  130. <summary><b>Python server example retrieving an API key from Secrets Manager</b></summary>
  131. ```python
  132. import sys
  133. import boto3
  134. from mcp.client.stdio import StdioServerParameters
  135. # Retrieve API key from Secrets Manager
  136. secrets_client = boto3.client("secretsmanager")
  137. api_key = secrets_client.get_secret_value(SecretId="my-api-key-secret")["SecretString"]
  138. server_params = StdioServerParameters(
  139. command=sys.executable,
  140. args=["-m", "my_mcp_server"],
  141. env={
  142. "API_KEY": api_key,
  143. },
  144. )
  145. ```
  146. </details>
  147. <details>
  148. <summary><b>Typescript server example retrieving an API key from Secrets Manager</b></summary>
  149. ```typescript
  150. import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";
  151. const secretsClient = new SecretsManagerClient({});
  152. const secret = await secretsClient.send(
  153. new GetSecretValueCommand({ SecretId: "my-api-key-secret" })
  154. );
  155. const apiKey = secret.SecretString;
  156. const serverParams = {
  157. command: "npx",
  158. args: ["--offline", "my-mcp-server"],
  159. env: {
  160. API_KEY: apiKey,
  161. },
  162. };
  163. ```
  164. </details>
  165. <br/>
  166. If your MCP server needs to call AWS APIs (such as the [MCP servers for AWS](https://github.com/awslabs/mcp)),
  167. you can pass the Lambda function's AWS credentials to the wrapped MCP server via environment variables.
  168. The wrapped MCP server's child process does not automatically inherit the Lambda execution role's credentials.
  169. Again, note that anyone with access to invoke the Lambda function
  170. will then have access to use the function's AWS credentials to call AWS APIs by invoking the function.
  171. We recommend limiting access to the Lambda function using
  172. [least-privilege IAM policies](https://docs.aws.amazon.com/lambda/latest/dg/security-iam.html).
  173. <details>
  174. <summary><b>Python server example using AWS credentials via environment variables</b></summary>
  175. ```python
  176. import os
  177. import sys
  178. import boto3
  179. from mcp.client.stdio import StdioServerParameters
  180. # Get AWS credentials from Lambda execution role to pass to subprocess
  181. session = boto3.Session()
  182. credentials = session.get_credentials()
  183. if credentials is None:
  184. raise RuntimeError("Unable to retrieve AWS credentials from the execution environment")
  185. resolved = credentials.get_frozen_credentials()
  186. server_params = StdioServerParameters(
  187. command=sys.executable,
  188. args=["-m", "my_mcp_server"],
  189. env={
  190. "AWS_REGION": os.environ.get("AWS_REGION", "us-west-2"),
  191. "AWS_DEFAULT_REGION": os.environ.get("AWS_REGION", "us-west-2"),
  192. "AWS_ACCESS_KEY_ID": resolved.access_key,
  193. "AWS_SECRET_ACCESS_KEY": resolved.secret_key,
  194. "AWS_SESSION_TOKEN": resolved.token or "",
  195. },
  196. )
  197. ```
  198. </details>
  199. <details>
  200. <summary><b>Python server example using AWS credentials via credentials file</b></summary>
  201. Some MCP servers require an AWS profile and do not support credentials passed via environment variables.
  202. In this case, you can write the credentials to a file and point the MCP server to it.
  203. ```python
  204. import os
  205. import sys
  206. import boto3
  207. from mcp.client.stdio import StdioServerParameters
  208. # Get AWS credentials from Lambda execution role to pass to subprocess
  209. session = boto3.Session()
  210. credentials = session.get_credentials()
  211. if credentials is None:
  212. raise RuntimeError("Unable to retrieve AWS credentials from the execution environment")
  213. resolved = credentials.get_frozen_credentials()
  214. # Write credentials to disk as default profile
  215. aws_dir = "/tmp/.aws"
  216. os.makedirs(aws_dir, exist_ok=True)
  217. with open(f"{aws_dir}/credentials", "w") as f:
  218. f.write("[default]\n")
  219. f.write(f"aws_access_key_id = {resolved.access_key}\n")
  220. f.write(f"aws_secret_access_key = {resolved.secret_key}\n")
  221. if resolved.token:
  222. f.write(f"aws_session_token = {resolved.token}\n")
  223. server_params = StdioServerParameters(
  224. command=sys.executable,
  225. args=["-m", "my_mcp_server"],
  226. env={
  227. "AWS_REGION": os.environ.get("AWS_REGION", "us-west-2"),
  228. "AWS_DEFAULT_REGION": os.environ.get("AWS_REGION", "us-west-2"),
  229. "AWS_SHARED_CREDENTIALS_FILE": f"{aws_dir}/credentials",
  230. },
  231. )
  232. ```
  233. See a full, deployable example [here](examples/servers/sns-sqs/).
  234. </details>
  235. ## Use API Gateway
  236. ```mermaid
  237. flowchart LR
  238. App["MCP Client"]
  239. T1["MCP Server<br>(Lambda function)"]
  240. T2["API Gateway"]
  241. T3["OAuth Server<br>(Cognito or similar)"]
  242. App -->|"MCP Streamable<br>HTTP Transport"| T2
  243. T2 -->|"Invoke"| T1
  244. T2 -->|"Authorize"| T3
  245. ```
  246. This solution is compatible with most MCP clients that support the streamable HTTP transport.
  247. MCP servers deployed with this architecture can typically be used with off-the-shelf
  248. MCP-compatible applications such as Cursor, Cline, Claude Desktop, etc.
  249. You can choose your desired OAuth server provider for this solution. The examples in this
  250. repository use Amazon Cognito, or you can use third-party providers such as Okta or Auth0
  251. with API Gateway custom authorization.
  252. <details>
  253. <summary><b>Python server example</b></summary>
  254. ```python
  255. import sys
  256. from mcp.client.stdio import StdioServerParameters
  257. from mcp_lambda import APIGatewayProxyEventHandler, StdioServerAdapterRequestHandler
  258. server_params = StdioServerParameters(
  259. command=sys.executable,
  260. args=[
  261. "-m",
  262. "my_mcp_server_python_module",
  263. "--my-server-command-line-parameter",
  264. "some_value",
  265. ],
  266. )
  267. request_handler = StdioServerAdapterRequestHandler(server_params)
  268. event_handler = APIGatewayProxyEventHandler(request_handler)
  269. def handler(event, context):
  270. return event_handler.handle(event, context)
  271. ```
  272. See a full, deployable example [here](examples/servers/dad-jokes/).
  273. </details>
  274. <details>
  275. <summary><b>Typescript server example</b></summary>
  276. ```typescript
  277. import {
  278. Handler,
  279. Context,
  280. APIGatewayProxyWithCognitoAuthorizerEvent,
  281. APIGatewayProxyResult,
  282. } from "aws-lambda";
  283. import {
  284. APIGatewayProxyEventHandler,
  285. StdioServerAdapterRequestHandler,
  286. } from "@aws/run-mcp-servers-with-aws-lambda";
  287. const serverParams = {
  288. command: "npx",
  289. args: [
  290. "--offline",
  291. "my-mcp-server-typescript-module",
  292. "--my-server-command-line-parameter",
  293. "some_value",
  294. ],
  295. };
  296. const requestHandler = new APIGatewayProxyEventHandler(
  297. new StdioServerAdapterRequestHandler(serverParams)
  298. );
  299. export const handler: Handler = async (
  300. event: APIGatewayProxyWithCognitoAuthorizerEvent,
  301. context: Context
  302. ): Promise<APIGatewayProxyResult> => {
  303. return requestHandler.handle(event, context);
  304. };
  305. ```
  306. See a full, deployable example [here](examples/servers/dog-facts/).
  307. </details>
  308. <details>
  309. <summary><b>Python client example</b></summary>
  310. ```python
  311. from mcp import ClientSession
  312. from mcp.client.streamable_http import streamablehttp_client
  313. # Create OAuth client provider here
  314. async with streamablehttp_client(
  315. url="https://abc123.execute-api.us-west-2.amazonaws.com/prod/mcp",
  316. auth=oauth_client_provider,
  317. ) as (
  318. read_stream,
  319. write_stream,
  320. _,
  321. ):
  322. async with ClientSession(read_stream, write_stream) as session:
  323. await session.initialize()
  324. tool_result = await session.call_tool("echo", {"message": "hello"})
  325. ```
  326. See a full example as part of the sample chatbot [here](examples/chatbots/python/interactive_oauth.py).
  327. </details>
  328. <details>
  329. <summary><b>Typescript client example</b></summary>
  330. ```typescript
  331. import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
  332. import { Client } from "@modelcontextprotocol/sdk/client/index.js";
  333. const client = new Client(
  334. {
  335. name: "my-client",
  336. version: "0.0.1",
  337. },
  338. {
  339. capabilities: {
  340. sampling: {},
  341. },
  342. }
  343. );
  344. // Create OAuth client provider here
  345. const transport = new StreamableHTTPClientTransport(
  346. "https://abc123.execute-api.us-west-2.amazonaws.com/prod/mcp",
  347. {
  348. authProvider: oauthProvider,
  349. }
  350. );
  351. await client.connect(transport);
  352. ```
  353. See a full example as part of the sample chatbot [here](examples/chatbots/typescript/src/interactive_oauth.ts).
  354. </details>
  355. ## Use Bedrock AgentCore Gateway
  356. ```mermaid
  357. flowchart LR
  358. App["MCP Client"]
  359. T1["MCP Server<br>(Lambda function)"]
  360. T2["Bedrock AgentCore Gateway"]
  361. T3["OAuth Server<br>(Cognito or similar)"]
  362. App -->|"MCP Streamable<br>HTTP Transport"| T2
  363. T2 -->|"Invoke"| T1
  364. T2 -->|"Authorize"| T3
  365. ```
  366. This solution is compatible with most MCP clients that support the streamable HTTP transport.
  367. MCP servers deployed with this architecture can typically be used with off-the-shelf
  368. MCP-compatible applications such as Cursor, Cline, Claude Desktop, etc.
  369. You can choose your desired OAuth server provider with Bedrock AgentCore Gateway,
  370. such as Amazon Cognito, Okta, or Auth0.
  371. Using Bedrock AgentCore Gateway in front of your stdio-based MCP server requires that
  372. you retrieve the MCP server's tool schema, and provide it in the
  373. [AgentCore Gateway Lambda target configuration](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-add-target-lambda.html#gateway-building-lambda-multiple-tools).
  374. AgentCore Gateway can then advertise the schema to HTTP clients and validate request inputs and outputs.
  375. To retrieve and save your stdio-based MCP server's tool schema to a file, run:
  376. ```bash
  377. npx @modelcontextprotocol/inspector --cli --method tools/list <your MCP server command and arguments> > tool-schema.json
  378. # For example:
  379. npx @modelcontextprotocol/inspector --cli --method tools/list uvx mcp-server-time > tool-schema.json
  380. ```
  381. Some MCP servers generate tool schemas that AgentCore Gateway rejects with strict validation,
  382. such as `"items": {}`, `"default": null`, or `anyOf` with `{"type": "null"}`.
  383. You may need to clean up the schema before using it:
  384. ```bash
  385. python3 scripts/clean-tool-schema.py tool-schema.json
  386. ```
  387. <details>
  388. <summary><b>Python server example</b></summary>
  389. ```python
  390. import sys
  391. from mcp.client.stdio import StdioServerParameters
  392. from mcp_lambda import BedrockAgentCoreGatewayTargetHandler, StdioServerAdapterRequestHandler
  393. server_params = StdioServerParameters(
  394. command=sys.executable,
  395. args=[
  396. "-m",
  397. "my_mcp_server_python_module",
  398. "--my-server-command-line-parameter",
  399. "some_value",
  400. ],
  401. )
  402. request_handler = StdioServerAdapterRequestHandler(server_params)
  403. event_handler = BedrockAgentCoreGatewayTargetHandler(request_handler)
  404. def handler(event, context):
  405. return event_handler.handle(event, context)
  406. ```
  407. See a full, deployable example [here](examples/servers/book-search/).
  408. </details>
  409. <details>
  410. <summary><b>Typescript server example</b></summary>
  411. ```typescript
  412. import { Handler, Context } from "aws-lambda";
  413. import {
  414. BedrockAgentCoreGatewayTargetHandler,
  415. StdioServerAdapterRequestHandler,
  416. } from "@aws/run-mcp-servers-with-aws-lambda";
  417. const serverParams = {
  418. command: "npx",
  419. args: [
  420. "--offline",
  421. "my-mcp-server-typescript-module",
  422. "--my-server-command-line-parameter",
  423. "some_value",
  424. ],
  425. };
  426. const requestHandler = new BedrockAgentCoreGatewayTargetHandler(
  427. new StdioServerAdapterRequestHandler(serverParams)
  428. );
  429. export const handler: Handler = async (
  430. event: Record<string, unknown>,
  431. context: Context
  432. ): Promise<Record<string, unknown>> => {
  433. return requestHandler.handle(event, context);
  434. };
  435. ```
  436. See a full, deployable example [here](examples/servers/dictionary/).
  437. </details>
  438. <details>
  439. <summary><b>Python client example</b></summary>
  440. ```python
  441. from mcp import ClientSession
  442. from mcp.client.streamable_http import streamablehttp_client
  443. # Create OAuth client provider here
  444. async with streamablehttp_client(
  445. url="https://abc123.gateway.bedrock-agentcore.us-west-2.amazonaws.com/mcp",
  446. auth=oauth_client_provider,
  447. ) as (
  448. read_stream,
  449. write_stream,
  450. _,
  451. ):
  452. async with ClientSession(read_stream, write_stream) as session:
  453. await session.initialize()
  454. tool_result = await session.call_tool("echo", {"message": "hello"})
  455. ```
  456. See a full example as part of the sample chatbot [here](examples/chatbots/python/interactive_oauth.py).
  457. </details>
  458. <details>
  459. <summary><b>Typescript client example</b></summary>
  460. ```typescript
  461. import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
  462. import { Client } from "@modelcontextprotocol/sdk/client/index.js";
  463. const client = new Client(
  464. {
  465. name: "my-client",
  466. version: "0.0.1",
  467. },
  468. {
  469. capabilities: {
  470. sampling: {},
  471. },
  472. }
  473. );
  474. // Create OAuth client provider here
  475. const transport = new StreamableHTTPClientTransport(
  476. "https://abc123.gateway.bedrock-agentcore.us-west-2.amazonaws.com/mcp",
  477. {
  478. authProvider: oauthProvider,
  479. }
  480. );
  481. await client.connect(transport);
  482. ```
  483. See a full example as part of the sample chatbot [here](examples/chatbots/typescript/src/interactive_oauth.ts).
  484. </details>
  485. ## Use a Lambda function URL
  486. ```mermaid
  487. flowchart LR
  488. App["MCP Client"]
  489. T1["MCP Server<br>(Lambda function)"]
  490. T2["Lambda function URL"]
  491. App -->|"Custom Streamable HTTP<br>Transport with AWS Auth"| T2
  492. T2 -->|"Invoke"| T1
  493. ```
  494. This solution uses AWS IAM for authentication, and relies on granting
  495. [Lambda InvokeFunctionUrl permission](https://docs.aws.amazon.com/lambda/latest/dg/urls-auth.html#urls-auth-iam) to your
  496. IAM users and roles to enable access to the MCP server. Clients must use an extension to the MCP Streamable
  497. HTTP transport that signs requests with [AWS SigV4](https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html).
  498. Off-the-shelf MCP-compatible applications are unlikely to have support for this custom transport,
  499. so this solution is more appropriate for service-to-service communication rather than for end users.
  500. <details>
  501. <summary><b>Python server example</b></summary>
  502. ```python
  503. import sys
  504. from mcp.client.stdio import StdioServerParameters
  505. from mcp_lambda import LambdaFunctionURLEventHandler, StdioServerAdapterRequestHandler
  506. server_params = StdioServerParameters(
  507. command=sys.executable,
  508. args=[
  509. "-m",
  510. "my_mcp_server_python_module",
  511. "--my-server-command-line-parameter",
  512. "some_value",
  513. ],
  514. )
  515. request_handler = StdioServerAdapterRequestHandler(server_params)
  516. event_handler = LambdaFunctionURLEventHandler(request_handler)
  517. def handler(event, context):
  518. return event_handler.handle(event, context)
  519. ```
  520. See a full, deployable example [here](examples/servers/mcpdoc/).
  521. </details>
  522. <details>
  523. <summary><b>Typescript server example</b></summary>
  524. ```typescript
  525. import {
  526. Handler,
  527. Context,
  528. APIGatewayProxyEventV2WithIAMAuthorizer,
  529. APIGatewayProxyResultV2,
  530. } from "aws-lambda";
  531. import {
  532. LambdaFunctionURLEventHandler,
  533. StdioServerAdapterRequestHandler,
  534. } from "@aws/run-mcp-servers-with-aws-lambda";
  535. const serverParams = {
  536. command: "npx",
  537. args: [
  538. "--offline",
  539. "my-mcp-server-typescript-module",
  540. "--my-server-command-line-parameter",
  541. "some_value",
  542. ],
  543. };
  544. const requestHandler = new LambdaFunctionURLEventHandler(
  545. new StdioServerAdapterRequestHandler(serverParams)
  546. );
  547. export const handler: Handler = async (
  548. event: APIGatewayProxyEventV2WithIAMAuthorizer,
  549. context: Context
  550. ): Promise<APIGatewayProxyResultV2> => {
  551. return requestHandler.handle(event, context);
  552. };
  553. ```
  554. See a full, deployable example [here](examples/servers/cat-facts/).
  555. </details>
  556. <details>
  557. <summary><b>Python client example</b></summary>
  558. ```python
  559. from mcp import ClientSession
  560. from mcp_proxy_for_aws.client import aws_iam_streamablehttp_client
  561. async with aws_iam_streamablehttp_client(
  562. endpoint="https://url-id-12345.lambda-url.us-west-2.on.aws",
  563. aws_service="lambda",
  564. aws_region="us-west-2",
  565. ) as (
  566. read_stream,
  567. write_stream,
  568. _,
  569. ):
  570. async with ClientSession(read_stream, write_stream) as session:
  571. await session.initialize()
  572. tool_result = await session.call_tool("echo", {"message": "hello"})
  573. ```
  574. See a full example as part of the sample chatbot [here](examples/chatbots/python/mcp_clients.py).
  575. </details>
  576. <details>
  577. <summary><b>Typescript client example</b></summary>
  578. ```typescript
  579. import { StreamableHTTPClientWithSigV4Transport } from "@aws/run-mcp-servers-with-aws-lambda";
  580. import { Client } from "@modelcontextprotocol/sdk/client/index.js";
  581. const client = new Client(
  582. {
  583. name: "my-client",
  584. version: "0.0.1",
  585. },
  586. {
  587. capabilities: {
  588. sampling: {},
  589. },
  590. }
  591. );
  592. const transport = new StreamableHTTPClientWithSigV4Transport(
  593. new URL("https://url-id-12345.lambda-url.us-west-2.on.aws"),
  594. {
  595. service: "lambda",
  596. region: "us-west-2",
  597. }
  598. );
  599. await client.connect(transport);
  600. ```
  601. See a full example as part of the sample chatbot [here](examples/chatbots/typescript/src/mcp_clients.ts).
  602. </details>
  603. ## Use the Lambda Invoke API
  604. ```mermaid
  605. flowchart LR
  606. App["MCP Client"]
  607. T1["MCP Server<br>(Lambda function)"]
  608. App -->|"Custom MCP Transport<br>(Lambda Invoke API)"| T1
  609. ```
  610. Like the Lambda function URL approach, this solution uses AWS IAM for authentication.
  611. It relies on granting
  612. [Lambda InvokeFunction permission](https://docs.aws.amazon.com/lambda/latest/dg/lambda-api-permissions-ref.html)
  613. to your IAM users and roles to enable access to the MCP server.
  614. Clients must use a custom MCP transport that directly calls the
  615. [Lambda Invoke API](https://docs.aws.amazon.com/lambda/latest/api/API_Invoke.html).
  616. Off-the-shelf MCP-compatible applications are unlikely to have support for this custom transport,
  617. so this solution is more appropriate for service-to-service communication rather than for end users.
  618. <details>
  619. <summary><b>Python server example</b></summary>
  620. ```python
  621. import sys
  622. from mcp.client.stdio import StdioServerParameters
  623. from mcp_lambda import stdio_server_adapter
  624. server_params = StdioServerParameters(
  625. command=sys.executable,
  626. args=[
  627. "-m",
  628. "my_mcp_server_python_module",
  629. "--my-server-command-line-parameter",
  630. "some_value",
  631. ],
  632. )
  633. def handler(event, context):
  634. return stdio_server_adapter(server_params, event, context)
  635. ```
  636. See a full, deployable example [here](examples/servers/time/).
  637. </details>
  638. <details>
  639. <summary><b>Typescript server example</b></summary>
  640. ```typescript
  641. import { Handler, Context } from "aws-lambda";
  642. import { stdioServerAdapter } from "@aws/run-mcp-servers-with-aws-lambda";
  643. const serverParams = {
  644. command: "npx",
  645. args: [
  646. "--offline",
  647. "my-mcp-server-typescript-module",
  648. "--my-server-command-line-parameter",
  649. "some_value",
  650. ],
  651. };
  652. export const handler: Handler = async (event, context: Context) => {
  653. return await stdioServerAdapter(serverParams, event, context);
  654. };
  655. ```
  656. See a full, deployable example [here](examples/servers/weather-alerts/).
  657. </details>
  658. <details>
  659. <summary><b>Python client example</b></summary>
  660. ```python
  661. from mcp import ClientSession
  662. from mcp_lambda import LambdaFunctionParameters, lambda_function_client
  663. server_params = LambdaFunctionParameters(
  664. function_name="my-mcp-server-function",
  665. region_name="us-west-2",
  666. )
  667. async with lambda_function_client(server_params) as (
  668. read_stream,
  669. write_stream,
  670. ):
  671. async with ClientSession(read_stream, write_stream) as session:
  672. await session.initialize()
  673. tool_result = await session.call_tool("echo", {"message": "hello"})
  674. ```
  675. See a full example as part of the sample chatbot [here](examples/chatbots/python/mcp_clients.py).
  676. </details>
  677. <details>
  678. <summary><b>Typescript client example</b></summary>
  679. ```typescript
  680. import {
  681. LambdaFunctionParameters,
  682. LambdaFunctionClientTransport,
  683. } from "@aws/run-mcp-servers-with-aws-lambda";
  684. import { Client } from "@modelcontextprotocol/sdk/client/index.js";
  685. const serverParams: LambdaFunctionParameters = {
  686. functionName: "my-mcp-server-function",
  687. regionName: "us-west-2",
  688. };
  689. const client = new Client(
  690. {
  691. name: "my-client",
  692. version: "0.0.1",
  693. },
  694. {
  695. capabilities: {
  696. sampling: {},
  697. },
  698. }
  699. );
  700. const transport = new LambdaFunctionClientTransport(serverParams);
  701. await client.connect(transport);
  702. ```
  703. See a full example as part of the sample chatbot [here](examples/chatbots/typescript/src/mcp_clients.ts).
  704. </details>
  705. ## Related projects
  706. - To write custom MCP servers in Lambda functions,
  707. see the [MCP Lambda Handler](https://github.com/awslabs/mcp/tree/main/src/mcp-lambda-handler) project.
  708. - To invoke existing Lambda functions as tools through a stdio MCP server,
  709. see the [AWS Lambda Tool MCP Server](https://awslabs.github.io/mcp/servers/lambda-tool-mcp-server/) project.
  710. ## Considerations
  711. - This library currently supports MCP servers and clients written in Python and Typescript.
  712. Other languages such as Kotlin are not supported.
  713. - This library only adapts stdio MCP servers for Lambda, not servers written for other protocols such as SSE.
  714. - This library does not maintain any MCP server state or sessions across Lambda function invocations.
  715. Only stateless MCP servers are a good fit for using this library. For example, MCP servers
  716. that invoke stateless tools like the [time MCP server](https://github.com/modelcontextprotocol/servers/tree/main/src/time)
  717. or make stateless web requests like the [fetch MCP server](https://github.com/modelcontextprotocol/servers/tree/main/src/fetch).
  718. Stateful MCP servers are not a good fit, because they will lose their state on every request.
  719. For example, MCP servers that manage data on disk or in memory such as
  720. the [sqlite MCP server](https://github.com/modelcontextprotocol/servers/tree/main/src/sqlite),
  721. the [filesystem MCP server](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem),
  722. and the [git MCP server](https://github.com/modelcontextprotocol/servers/tree/main/src/git).
  723. ## Deploy and run the examples
  724. See the [development guide](DEVELOP.md) for instructions to deploy and run the examples in this repository.
  725. ## Security
  726. See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information.
  727. ## License
  728. This project is licensed under the Apache-2.0 License.

Ratings and comments

Sign in to rate this skill.

Sign in

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