### Run Example Python Chatbot Client Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/DEVELOP.md Navigate to the Python chatbot example directory, install dependencies using uv pip, and run the main Python script to start the chatbot client. ```bash cd examples/chatbots/python/ uv pip install -r requirements.txt python main.py ``` -------------------------------- ### Run Example TypeScript Chatbot Client Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/DEVELOP.md Navigate to the TypeScript chatbot example directory, install Node.js dependencies, link the package, build the project, and run the start script to launch the chatbot client. ```bash cd examples/chatbots/typescript/ npm install npm link @aws/run-mcp-servers-with-aws-lambda npm run build npm run start ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/DEVELOP.md Navigate to the src/python directory and install pre-commit hooks to ensure commits adhere to conventional commit guidelines. ```bash cd src/python uv run pre-commit install ``` -------------------------------- ### Deploy MCP Server with CDK Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/examples/servers/book-search/README.md Installs dependencies and deploys the server using AWS CDK. Ensure you have the necessary AWS credentials and CDK setup. ```bash uv pip install -r requirements.txt cdk deploy --app 'python3 cdk_stack.py' ``` -------------------------------- ### Install Dependencies, Build, and Deploy CDK Pipeline Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/pipeline/README.md Install project dependencies, build the CDK application, and deploy the pipeline using npm commands. ```bash npm install npm run build npm run deploy ``` -------------------------------- ### Run Python MCP Server Modules Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Examples of running different Python MCP server modules from the command line. ```bash python -m mcpdoc.cli # Note the sub-module ``` ```bash python -c "from mcp_openapi_proxy import main; main()" ``` ```bash python -c "import asyncio; from postgres_mcp.server import main; asyncio.run(main())" ``` -------------------------------- ### Deploy SNS/SQS MCP Server with AWS CDK Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/DEVELOP.md Navigate to the sns-sqs example directory, install dependencies, and deploy the MCP server using AWS CDK. This wraps the Amazon SNS/SQS MCP server. ```bash cd examples/servers/sns-sqs/ uv pip install -r requirements.txt cdk deploy --app 'python3 cdk_stack.py' ``` -------------------------------- ### Deploy Time MCP Server with AWS CDK Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/DEVELOP.md Navigate to the time example directory, install dependencies, and deploy the MCP server using AWS CDK. The deployed function will be named 'mcp-server-time'. ```bash cd examples/servers/time/ uv pip install -r requirements.txt cdk deploy --app 'python3 cdk_stack.py' ``` -------------------------------- ### Install Function Dependencies Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/examples/servers/time/README.md Installs the Python dependencies required for the Lambda function. This should be run in the function's directory. ```bash uv pip install -r function/requirements.txt ``` -------------------------------- ### Run Python MCP Server Locally Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Example of how to run a Python MCP server module locally from the command line. ```bash python -m my_mcp_server_python_module --my-server-command-line-parameter some_value ``` -------------------------------- ### Deploy Cat-Facts MCP Server with AWS CDK Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/DEVELOP.md Navigate to the cat-facts example directory, install Node.js dependencies, link the package, build the project, and deploy the MCP server using AWS CDK. The deployed function will be named 'mcp-server-cat-facts'. ```bash cd examples/servers/cat-facts/ npm install npm link @aws/run-mcp-servers-with-aws-lambda npm run build cdk deploy --app 'node lib/cat-facts-mcp-server.js' ``` -------------------------------- ### Deploy Weather-Alerts MCP Server with AWS CDK Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/DEVELOP.md Navigate to the weather-alerts example directory, install Node.js dependencies, link the package, build the project, and deploy the MCP server using AWS CDK. The deployed function will be named 'mcp-server-weather-alerts'. ```bash cd examples/servers/weather-alerts/ npm install npm link @aws/run-mcp-servers-with-aws-lambda npm run build cdk deploy --app 'node lib/weather-alerts-mcp-server.js' ``` -------------------------------- ### Run Node.js MCP Server from Path Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Example of running a Node.js MCP server directly from its path within the Lambda environment. ```bash node /var/task/node_modules/@ivotoby/openapi-mcp-server/bin/mcp-server.js ``` -------------------------------- ### Deploy mcpdoc MCP Server with AWS CDK Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/DEVELOP.md Navigate to the mcpdoc example directory, install dependencies, and deploy the MCP server using AWS CDK. The deployed function will be named 'mcp-server-mcpdoc'. ```bash cd examples/servers/mcpdoc/ uv pip install -r requirements.txt cdk deploy --app 'python3 cdk_stack.py' ``` -------------------------------- ### Deploy MCP Auth Stack Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/examples/servers/auth/README.md Installs dependencies, builds the project, and deploys the CDK stack for MCP authentication. Ensure you are in the project root directory. ```bash npm install npm run build cdk deploy --app 'node lib/mcp-auth.js' ``` -------------------------------- ### Deploy Weather Alerts MCP Server Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/examples/servers/weather-alerts/README.md Install dependencies, link the package, build the project, and deploy the CDK application. ```bash npm install npm link @aws/run-mcp-servers-with-aws-lambda npm run build cdk deploy --app 'node lib/weather-alerts-mcp-server.js' ``` -------------------------------- ### Build Python Module with UV Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/DEVELOP.md Installs and synchronizes the Python module using 'uv'. This includes installing development dependencies and running linters/tests. ```bash cd src/python/ ``` ```bash uv venv ``` ```bash source .venv/bin/activate ``` ```bash uv sync --all-extras --dev ``` ```bash # For development ``` ```bash uv run ruff check . ``` ```bash uv run pyright ``` ```bash uv run pytest # coverage report will be in htmlcov/index.html ``` -------------------------------- ### Deploy Dictionary MCP Server Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/examples/servers/dictionary/README.md Install dependencies, link the MCP server package, build the project, and deploy the CDK application for the dictionary MCP server. ```bash npm install npm link @aws/run-mcp-servers-with-aws-lambda npm run build cdk deploy --app 'node lib/dictionary-mcp-server.js' ``` -------------------------------- ### TypeScript MCP Client with Bedrock AgentCore Gateway Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Establish a connection from a TypeScript MCP client to Bedrock AgentCore Gateway using the StreamableHTTPClientTransport. This example shows client initialization and connection setup. ```typescript import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; const client = new Client( { name: "my-client", version: "0.0.1", }, { capabilities: { sampling: {}, }, } ); // Create OAuth client provider here const transport = new StreamableHTTPClientTransport( "https://abc123.gateway.bedrock-agentcore.us-west-2.amazonaws.com/mcp", { authProvider: oauthProvider, } ); await client.connect(transport); ``` -------------------------------- ### Deploy Book-Search MCP Server Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/DEVELOP.md Deploys the book-search Lambda function using AWS CDK. Ensure you are in the 'examples/servers/book-search/' directory and have installed Python dependencies. ```bash cd examples/servers/book-search/ ``` ```bash uv pip install -r requirements.txt ``` ```bash cdk deploy --app 'python3 cdk_stack.py' ``` -------------------------------- ### Deploy OAuth Authentication Stack Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/DEVELOP.md Deploys the OAuth authentication stack using AWS CDK. Ensure you are in the 'examples/servers/auth' directory and have installed Node.js dependencies. ```bash cd examples/servers/auth ``` ```bash npm install ``` ```bash npm run build ``` ```bash cdk deploy --app 'node lib/mcp-auth.js' ``` ```bash ./sync-cognito-user-password.sh ``` -------------------------------- ### Deploy Zen MCP Server Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/DEVELOP.md Deploys the zen Bedrock AgentCore Gateway using AWS CDK. Ensure you are in the 'examples/servers/zen/' directory and have installed Python dependencies. ```bash cd examples/servers/zen/ ``` ```bash uv pip install -r requirements.txt ``` ```bash cdk deploy --app 'python3 cdk_stack.py' ``` -------------------------------- ### Run TypeScript MCP Server Locally Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Example of how to run a TypeScript MCP server module locally using npx with the --offline flag. ```bash npx --offline my-mcp-server-typescript-module --my-server-command-line-parameter some_value ``` -------------------------------- ### Deploy Dog-Facts MCP Server Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/DEVELOP.md Deploys the dog-facts Lambda function using AWS CDK. Ensure you are in the 'examples/servers/dog-facts/' directory and have installed Node.js dependencies. ```bash cd examples/servers/dog-facts/ ``` ```bash npm install ``` ```bash npm link @aws/run-mcp-servers-with-aws-lambda ``` ```bash npm run build ``` ```bash cdk deploy --app 'node lib/dog-facts-mcp-server.js' ``` -------------------------------- ### Deploy Cat Facts MCP Server Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/examples/servers/cat-facts/README.md Install dependencies, link the package, build the project, and deploy the CDK application for the Cat Facts MCP server. ```bash npm install npm link @aws/run-mcp-servers-with-aws-lambda npm run build cdk deploy --app 'node lib/cat-facts-mcp-server.js' ``` -------------------------------- ### Deploy Dog Facts MCP Server Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/examples/servers/dog-facts/README.md Commands to install dependencies, link the MCP server package, build the project, and deploy the CDK application for the Dog Facts MCP Server. ```bash npm install npm link @aws/run-mcp-servers-with-aws-lambda npm run build cdk deploy --app 'node lib/dog-facts-mcp-server.js' ``` -------------------------------- ### Deploy Dictionary MCP Server Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/DEVELOP.md Deploys the dictionary Lambda function using AWS CDK. Ensure you are in the 'examples/servers/dictionary/' directory and have installed Node.js dependencies. ```bash cd examples/servers/dictionary/ ``` ```bash npm install ``` ```bash npm link @aws/run-mcp-servers-with-aws-lambda ``` ```bash npm run build ``` ```bash cdk deploy --app 'node lib/dictionary-mcp-server.js' ``` -------------------------------- ### Initialize MCP Server Locally Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/examples/servers/dad-jokes/README.md Initializes the MCP server locally by running the Lambda handler with specific HTTP POST request details. This is useful for testing the server's setup and initial handshake. ```python python -c 'import index; print(index.handler({"httpMethod": "POST", "headers": {"Accept": "application/json, text/event-stream", "content-type": "application/json"}, "body": "{\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\",\"capabilities\":{},\"clientInfo\":{\"name\":\"mcp\",\"version\":\"0.1.0\"}},\"jsonrpc\":\"2.0\",\"id\":0}"}, ""))' ``` -------------------------------- ### Build Typescript Package Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/DEVELOP.md Builds the Typescript module using npm. This includes installing dependencies, building the package, linking it, and running tests. ```bash cd src/typescript/ ``` ```bash npm install ``` ```bash npm run build ``` ```bash npm link ``` ```bash # For development ``` ```bash npm test # coverage report will be in coverage/index.html ``` ```bash npm run lint ``` -------------------------------- ### Python MCP Client with Bedrock AgentCore Gateway Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Connect a Python MCP client to a Bedrock AgentCore Gateway endpoint using the streamable HTTP transport. This example includes initializing the client session and calling a tool. ```python from mcp import ClientSession from mcp.client.streamable_http import streamablehttp_client # Create OAuth client provider here async with streamablehttp_client( url="https://abc123.gateway.bedrock-agentcore.us-west-2.amazonaws.com/mcp", auth=oauth_client_provider, ) as ( read_stream, write_stream, _, ): async with ClientSession(read_stream, write_stream) as session: await session.initialize() tool_result = await session.call_tool("echo", {"message": "hello"}) ``` -------------------------------- ### Deploy Auth Stack with CDK Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/e2e_tests/setup/setup.md Deploys the authentication stack after installing dependencies and building the project. This includes attaching and detaching administrator access for the CloudFormation execution role. ```bash cd ../../examples/servers/auth/ ``` ```bash npm install ``` ```bash npm run build ``` ```bash AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query "Account" --output text) ``` ```bash aws iam attach-role-policy \ --role-name cdk-hnb659fds-cfn-exec-role-$AWS_ACCOUNT_ID-us-west-2 \ --policy-arn arn:aws:iam::aws:policy/AdministratorAccess ``` ```bash cdk deploy --app 'node lib/mcp-auth.js' ``` ```bash aws iam detach-role-policy \ --role-name cdk-hnb659fds-cfn-exec-role-$AWS_ACCOUNT_ID-us-west-2 \ --policy-arn arn:aws:iam::aws:policy/AdministratorAccess ``` ```bash ./sync-cognito-user-password.sh ``` -------------------------------- ### Deploy Dad-Jokes MCP Server Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/DEVELOP.md Deploys the dad-jokes Lambda function using AWS CDK. Ensure you are in the 'examples/servers/dad-jokes/' directory and have installed Python dependencies. ```bash cd examples/servers/dad-jokes/ ``` ```bash uv pip install -r requirements.txt ``` ```bash cdk deploy --app 'python3 cdk_stack.py' ``` -------------------------------- ### Python MCP Server with Secrets Manager Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Example of retrieving an API key from AWS Secrets Manager for a Python MCP server. Requires boto3 and StdioServerParameters. ```python import sys import boto3 from mcp.client.stdio import StdioServerParameters ``` -------------------------------- ### TypeScript MCP Server for API Gateway Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Set up an MCP server for AWS Lambda using TypeScript, compatible with API Gateway. This example uses `aws-lambda` and `@aws/run-mcp-servers-with-aws-lambda` packages. ```typescript import { Handler, Context, APIGatewayProxyWithCognitoAuthorizerEvent, APIGatewayProxyResult, } from "aws-lambda"; import { APIGatewayProxyEventHandler, StdioServerAdapterRequestHandler, } from "@aws/run-mcp-servers-with-aws-lambda"; const serverParams = { command: "npx", args: [ "--offline", "my-mcp-server-typescript-module", "--my-server-command-line-parameter", "some_value", ], }; const requestHandler = new APIGatewayProxyEventHandler( new StdioServerAdapterRequestHandler(serverParams) ); export const handler: Handler = async ( event: APIGatewayProxyWithCognitoAuthorizerEvent, context: Context ): Promise => { return requestHandler.handle(event, context); }; ``` -------------------------------- ### TypeScript Bedrock AgentCore Gateway Lambda Target Handler Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Set up a TypeScript Lambda function for Bedrock AgentCore Gateway using StdioServerAdapterRequestHandler. This example demonstrates the necessary imports and handler structure. ```typescript import { Handler, Context } from "aws-lambda"; import { BedrockAgentCoreGatewayTargetHandler, StdioServerAdapterRequestHandler, } from "@aws/run-mcp-servers-with-aws-lambda"; const serverParams = { command: "npx", args: [ "--offline", "my-mcp-server-typescript-module", "--my-server-command-line-parameter", "some_value", ], }; const requestHandler = new BedrockAgentCoreGatewayTargetHandler( new StdioServerAdapterRequestHandler(serverParams) ); export const handler: Handler = async ( event: Record, context: Context ): Promise> => { return requestHandler.handle(event, context); }; ``` -------------------------------- ### TypeScript MCP Client with Streamable HTTP Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Establish a connection to an MCP server using the streamable HTTP transport in TypeScript. This client setup requires an OAuth provider for authorization. ```typescript import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; const client = new Client( { name: "my-client", version: "0.0.1", }, { capabilities: { sampling: {}, }, } ); // Create OAuth client provider here const transport = new StreamableHTTPClientTransport( "https://abc123.execute-api.us-west-2.amazonaws.com/prod/mcp", { authProvider: oauthProvider, } ); await client.connect(transport); ``` -------------------------------- ### Python Bedrock AgentCore Gateway Lambda Target Handler Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Configure a Python Lambda function to act as a Bedrock AgentCore Gateway target. This example uses StdioServerAdapterRequestHandler to adapt an MCP server. ```python import sys from mcp.client.stdio import StdioServerParameters from mcp_lambda import BedrockAgentCoreGatewayTargetHandler, StdioServerAdapterRequestHandler server_params = StdioServerParameters( command=sys.executable, args=[ "-m", "my_mcp_server_python_module", "--my-server-command-line-parameter", "some_value", ], ) request_handler = StdioServerAdapterRequestHandler(server_params) event_handler = BedrockAgentCoreGatewayTargetHandler(request_handler) def handler(event, context): return event_handler.handle(event, context) ``` -------------------------------- ### Python Client for Lambda Function URL with AWS IAM Auth Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md This Python client example demonstrates how to connect to an MCP server exposed via a Lambda Function URL using AWS IAM authentication. It utilizes the aws_iam_streamablehttp_client to establish a secure connection and interact with the server using ClientSession. ```python from mcp import ClientSession from mcp_proxy_for_aws.client import aws_iam_streamablehttp_client async with aws_iam_streamablehttp_client( endpoint="https://url-id-12345.lambda-url.us-west-2.on.aws", aws_service="lambda", aws_region="us-west-2", ) as ( read_stream, write_stream, _, ): async with ClientSession(read_stream, write_stream) as session: await session.initialize() tool_result = await session.call_tool("echo", {"message": "hello"}) ``` -------------------------------- ### TypeScript Client for Lambda Function URL with SigV4 Transport Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md This TypeScript client example shows how to connect to an MCP server running on a Lambda Function URL. It uses the StreamableHTTPClientWithSigV4Transport to handle AWS SigV4 authentication, enabling secure communication with the Lambda endpoint. ```typescript import { StreamableHTTPClientWithSigV4Transport } from "@aws/run-mcp-servers-with-aws-lambda"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; const client = new Client( { name: "my-client", version: "0.0.1", }, { capabilities: { sampling: {}, }, } ); const transport = new StreamableHTTPClientWithSigV4Transport( new URL("https://url-id-12345.lambda-url.us-west-2.on.aws"), { service: "lambda", region: "us-west-2", } ); await client.connect(transport); ``` -------------------------------- ### List Tools with MCP Server Locally Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/examples/servers/dad-jokes/README.md Tests the MCP server's ability to list available tools by sending a POST request with the 'tools/list' method. Requires the server to be running locally. ```python python -c 'import index; print(index.handler({"httpMethod": "POST", "headers": {"Accept": "application/json, text/event-stream", "content-type": "application/json"}, "body": "{\"method\":\"tools/list\",\"params\":{\"protocolVersion\":\"2025-06-18\",\"capabilities\":{},\"clientInfo\":{\"name\":\"mcp\",\"version\":\"0.1.0\"}},\"jsonrpc\":\"2.0\",\"id\":0}"}, ""))' ``` -------------------------------- ### Bootstrap AWS Account for CDK Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/DEVELOP.md Initializes the AWS account for use with AWS CDK. Replace with your actual AWS account ID. ```bash cdk bootstrap aws:///us-west-2 ``` -------------------------------- ### Sample Input for Tools List Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/examples/servers/dad-jokes/README.md A sample JSON payload representing an HTTP POST request to the MCP server for listing tools. This payload is used in local testing scenarios. ```json {"httpMethod": "POST", "headers": {"Accept": "application/json, text/event-stream", "content-type": "application/json"}, "body": "{\"method\":\"tools/list\",\"params\":{\"protocolVersion\":\"2025-06-18\",\"capabilities\":{},\"clientInfo\":{\"name\":\"mcp\",\"version\":\"0.1.0\"}},\"jsonrpc\":\"2.0\",\"id\":0}"} ``` -------------------------------- ### Create and Configure CodeBuild IAM Role Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/pipeline/README.md Create an IAM role for CodeBuild with the necessary permissions. This involves creating the role, attaching the PowerUserAccess policy, and adding an inline policy for specific permissions. ```bash aws iam create-role \ --role-name mcp-servers-codebuild \ --assume-role-policy-document file://codebuild-assume-role-policy.json aws iam attach-role-policy \ --role-name mcp-servers-codebuild \ --policy-arn arn:aws:iam::aws:policy/PowerUserAccess aws iam put-role-policy \ --role-name mcp-servers-codebuild \ --policy-name inline \ --policy-document file://codebuild-role-policy.json ``` -------------------------------- ### Create IAM Role for Bedrock AgentCore Gateways Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/DEVELOP.md Creates an IAM role for Bedrock AgentCore gateways with full access. Ensure the bedrock-agentcore-gateway-assume-role-policy.json and bedrock-agentcore-gateway-role-policy.json files exist. ```bash aws iam create-role \ --role-name mcp-lambda-example-agentcore-gateways \ --assume-role-policy-document file://examples/servers/bedrock-agentcore-gateway-assume-role-policy.json ``` ```bash aws iam put-role-policy \ --role-name mcp-lambda-example-agentcore-gateways \ --policy-name bedrock-agentcore-full-access \ --policy-document file://examples/servers/bedrock-agentcore-gateway-role-policy.json ``` -------------------------------- ### Create Bedrock AgentCore API Key Credential Provider Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/examples/servers/zen/README.md Use this AWS CLI command to create a credential provider for your ZenQuotes API key. Ensure you specify the correct region. ```bash aws bedrock-agentcore-control create-api-key-credential-provider \ --name zen-quotes-api-key \ --api-key "dummy-key" \ --region us-west-2 ``` -------------------------------- ### Test Lambda Function: Initialize Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/examples/servers/time/README.md Executes the Lambda function handler with an 'initialize' method call. This is used to set up the MCP server environment within the Lambda function. ```python python -c 'from function import index; print(index.handler({"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{"roots":{"listChanged":True}}},"clientInfo":{"name":"mcp","version":"0.1.0"}},"jsonrpc":"2.0","id":0}, ""))' ``` -------------------------------- ### Bootstrap CDK Environment Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/pipeline/README.md Bootstrap the AWS CDK environment for the specified account and region. This command must be run before deploying the CDK application. ```bash cdk bootstrap aws://ACCOUNT-ID/us-west-2 ``` -------------------------------- ### Python MCP Server Parameters Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Configure Python MCP server parameters, including the command and arguments. Use this when packaging Python MCP servers with your Lambda function. ```python from mcp.client.stdio import StdioServerParameters server_params = StdioServerParameters( command=sys.executable, args=[ "-m", "my_mcp_server_python_module", "--my-server-command-line-parameter", "some_value", ], ) ``` -------------------------------- ### Deploy IAM Roles with CloudFormation Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/e2e_tests/setup/setup.md Deploys least-privilege IAM roles required for integration tests using CloudFormation. Ensure the template file and parameters are correctly specified. ```bash aws cloudformation deploy \ --template-file integ-test-authentication.yaml \ --stack-name github-integ-test-identity-provider \ --parameter-overrides GitHubOrg=awslabs RepositoryName=run-model-context-protocol-servers-with-aws-lambda \ --capabilities CAPABILITY_NAMED_IAM \ --region us-west-2 ``` ```bash AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query "Account" --output text) ``` ```bash cdk bootstrap \ aws://$AWS_ACCOUNT_ID/us-west-2 \ --cloudformation-execution-policies "arn:aws:iam::$AWS_ACCOUNT_ID:policy/mcp-lambda-integ-test-cdk-cfn-execution" ``` -------------------------------- ### Configure MCP server with API key (Python) Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Configure the MCP server parameters in Python, passing the retrieved API key via environment variables. This is typically used when the MCP server needs to interact with external services using the API key. ```python import sys from mcp.client.stdio import StdioServerParameters server_params = StdioServerParameters( command=sys.executable, args=["-m", "my_mcp_server"], env={ "API_KEY": api_key, }, ) ``` -------------------------------- ### Create IAM Role for Lambda Servers Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/DEVELOP.md Creates an IAM role for Lambda functions with basic execution and secret access policies. Ensure the assume-role-policy.json and lambda-function-role-policy.json files exist. ```bash aws iam create-role \ --role-name mcp-lambda-example-servers \ --assume-role-policy-document file://examples/servers/lambda-assume-role-policy.json ``` ```bash aws iam attach-role-policy \ --role-name mcp-lambda-example-servers \ --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole ``` ```bash aws iam put-role-policy \ --role-name mcp-lambda-example-servers \ --policy-name secret-access \ --policy-document file://examples/servers/lambda-function-role-policy.json ``` ```bash aws iam put-role-policy \ --role-name mcp-lambda-example-servers \ --policy-name sns-sqs-access \ --policy-document file://examples/servers/lambda-function-sns-sqs-policy.json ``` -------------------------------- ### Python MCP Server with Lambda Layers and PYTHONPATH Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Configure Python MCP server parameters for Lambda environments using layers. Sets the PYTHONPATH environment variable for the subprocess. ```python lambda_paths = ["/opt/python"] + sys.path env_config = {"PYTHONPATH": ":".join(lambda_paths)} server_params = StdioServerParameters( command=sys.executable, args=[ "-c", "from mcp_openapi_proxy import main; main()", ], env=env_config, ) ``` -------------------------------- ### Test OAuth Configuration Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/DEVELOP.md Tests the OAuth configuration using provided shell scripts. These scripts are useful for verifying the authentication flow. ```bash ./test-interactive-oauth.sh ``` ```bash ./test-automated-oauth.sh ``` -------------------------------- ### Configure MCP server with API key (TypeScript) Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Configure the MCP server parameters in TypeScript, passing the retrieved API key via environment variables. This is typically used when the MCP server needs to interact with external services using the API key. ```typescript const serverParams = { command: "npx", args: ["--offline", "my-mcp-server"], env: { API_KEY: apiKey, }, }; ``` -------------------------------- ### Retrieve MCP Server Tool Schema Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Use the MCP inspector CLI to list and save the tool schema of your MCP server. This is required for Bedrock AgentCore Gateway configuration. ```bash npx @modelcontextprotocol/inspector --cli --method tools/list > tool-schema.json ``` ```bash # For example: npx @modelcontextprotocol/inspector --cli --method tools/list uvx mcp-server-time > tool-schema.json ``` -------------------------------- ### Pass AWS credentials via credentials file (Python) Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md This Python snippet shows how to write AWS credentials to a temporary file and configure the MCP server to use this file for authentication. This is useful for MCP servers that require credentials via a profile file rather than environment variables. ```python import os import sys import boto3 from mcp.client.stdio import StdioServerParameters # Get AWS credentials from Lambda execution role to pass to subprocess session = boto3.Session() credentials = session.get_credentials() if credentials is None: raise RuntimeError("Unable to retrieve AWS credentials from the execution environment") resolved = credentials.get_frozen_credentials() # Write credentials to disk as default profile aws_dir = "/tmp/.aws" os.makedirs(aws_dir, exist_ok=True) with open(f"{aws_dir}/credentials", "w") as f: f.write("[default]\n") f.write(f"aws_access_key_id = {resolved.access_key}\n") f.write(f"aws_secret_access_key = {resolved.secret_key}\n") if resolved.token: f.write(f"aws_session_token = {resolved.token}\n") server_params = StdioServerParameters( command=sys.executable, args=["-m", "my_mcp_server"], env={ "AWS_REGION": os.environ.get("AWS_REGION", "us-west-2"), "AWS_DEFAULT_REGION": os.environ.get("AWS_REGION", "us-west-2"), "AWS_SHARED_CREDENTIALS_FILE": f"{aws_dir}/credentials", }, ) ``` -------------------------------- ### Test Lambda Function: List Tools Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/examples/servers/time/README.md Executes the Lambda function handler with a 'tools/list' method call. This is used to retrieve a list of available tools from the MCP server. ```python python -c 'from function import index; print(index.handler({"method":"tools/list","params":{"clientInfo":{"name":"mcp","version":"0.1.0"}},"jsonrpc":"2.0","id":0}, ""))' ``` -------------------------------- ### Clean MCP Tool Schema for AgentCore Gateway Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Execute a Python script to clean the tool schema JSON file, removing problematic entries that AgentCore Gateway might reject due to strict validation. ```bash python3 scripts/clean-tool-schema.py tool-schema.json ``` -------------------------------- ### Create AWS Secret for Dog API Key Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/examples/servers/dog-facts/README.md Use this AWS CLI command to create a secret in AWS Secrets Manager to store your TheDogAPI key. Replace "your-api-key-here" with your actual API key. ```bash aws secretsmanager create-secret \ --name "mcp-lambda-examples-dog-api-key" \ --description "API key for thedogapi.com" \ --secret-string "your-api-key-here" ``` -------------------------------- ### Customize Repository Details in CDK Pipeline Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/pipeline/README.md Update the CodeStar Connections source action in `src/pipeline-stack.ts` with your GitHub username and repository name. ```typescript owner: 'your-github-username', repo: 'your-repo-name', ``` -------------------------------- ### TypeScript MCP Server Parameters Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Configure TypeScript MCP server parameters using npx with the --offline flag. Suitable for packaging Node.js MCP servers with Lambda. ```typescript const serverParams = { command: "npx", args: [ "--offline", "my-mcp-server-typescript-module", "--my-server-command-line-parameter", "some_value", ], }; ``` -------------------------------- ### Python MCP Client with Streamable HTTP Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Connect to an MCP server deployed via API Gateway using Python's streamable HTTP transport. Requires an OAuth client provider for authentication. ```python from mcp import ClientSession from mcp.client.streamable_http import streamablehttp_client # Create OAuth client provider here async with streamablehttp_client( url="https://abc123.execute-api.us-west-2.amazonaws.com/prod/mcp", auth=oauth_client_provider, ) as ( read_stream, write_stream, _, ): async with ClientSession(read_stream, write_stream) as session: await session.initialize() tool_result = await session.call_tool("echo", {"message": "hello"}) ``` -------------------------------- ### Pass AWS credentials via environment variables (Python) Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md This Python snippet demonstrates how to retrieve AWS credentials from the Lambda execution role and pass them to a child MCP server process via environment variables. Ensure the Lambda function's IAM role has the necessary permissions. ```python import os import sys import boto3 from mcp.client.stdio import StdioServerParameters # Get AWS credentials from Lambda execution role to pass to subprocess session = boto3.Session() credentials = session.get_credentials() if credentials is None: raise RuntimeError("Unable to retrieve AWS credentials from the execution environment") resolved = credentials.get_frozen_credentials() server_params = StdioServerParameters( command=sys.executable, args=["-m", "my_mcp_server"], env={ "AWS_REGION": os.environ.get("AWS_REGION", "us-west-2"), "AWS_DEFAULT_REGION": os.environ.get("AWS_REGION", "us-west-2"), "AWS_ACCESS_KEY_ID": resolved.access_key, "AWS_SECRET_ACCESS_KEY": resolved.secret_key, "AWS_SESSION_TOKEN": resolved.token or "", }, ) ``` -------------------------------- ### Python MCP Client for Lambda Function Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md This client connects to an MCP server running as a Lambda function using the Lambda Invoke API. It requires `mcp-lambda` and `LambdaFunctionParameters` to specify the target function name and region. The client session is established over streams. ```python from mcp import ClientSession from mcp_lambda import LambdaFunctionParameters, lambda_function_client server_params = LambdaFunctionParameters( function_name="my-mcp-server-function", region_name="us-west-2", ) async with lambda_function_client(server_params) as ( read_stream, write_stream, ): async with ClientSession(read_stream, write_stream) as session: await session.initialize() tool_result = await session.call_tool("echo", {"message": "hello"}) ``` -------------------------------- ### Python MCP Server for Lambda Function URL Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md This Python code sets up an MCP server to run within an AWS Lambda function, designed to be invoked via a Lambda Function URL. It uses StdioServerParameters to define the server command and arguments, and LambdaFunctionURLEventHandler to process incoming events. ```python import sys from mcp.client.stdio import StdioServerParameters from mcp_lambda import LambdaFunctionURLEventHandler, StdioServerAdapterRequestHandler server_params = StdioServerParameters( command=sys.executable, args=[ "-m", "my_mcp_server_python_module", "--my-server-command-line-parameter", "some_value", ], ) request_handler = StdioServerAdapterRequestHandler(server_params) event_handler = LambdaFunctionURLEventHandler(request_handler) def handler(event, context): return event_handler.handle(event, context) ``` -------------------------------- ### Python MCP Server Lambda Handler Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Use this handler to adapt an existing Python MCP server to run within an AWS Lambda function. It requires the `mcp-lambda` library and `StdioServerParameters` to configure the server command and arguments. ```python import sys from mcp.client.stdio import StdioServerParameters from mcp_lambda import stdio_server_adapter server_params = StdioServerParameters( command=sys.executable, args=[ "-m", "my_mcp_server_python_module", "--my-server-command-line-parameter", "some_value", ], ) def handler(event, context): return stdio_server_adapter(server_params, event, context) ``` -------------------------------- ### Python MCP Server for API Gateway Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Configure an MCP server to run within an AWS Lambda function, designed to be invoked via API Gateway using streamable HTTP transport. Requires `mcp-lambda` and `mcp` libraries. ```python import sys from mcp.client.stdio import StdioServerParameters from mcp_lambda import APIGatewayProxyEventHandler, StdioServerAdapterRequestHandler server_params = StdioServerParameters( command=sys.executable, args=[ "-m", "my_mcp_server_python_module", "--my-server-command-line-parameter", "some_value", ], ) request_handler = StdioServerAdapterRequestHandler(server_params) event_handler = APIGatewayProxyEventHandler(request_handler) def handler(event, context): return event_handler.handle(event, context) ``` -------------------------------- ### TypeScript MCP Server for Lambda Function URL Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md This TypeScript code configures an MCP server for deployment on AWS Lambda, accessible through a Lambda Function URL. It leverages StdioServerAdapterRequestHandler and LambdaFunctionURLEventHandler to manage server execution and event handling, suitable for Node.js environments. ```typescript import { Handler, Context, APIGatewayProxyEventV2WithIAMAuthorizer, APIGatewayProxyResultV2, } from "aws-lambda"; import { LambdaFunctionURLEventHandler, StdioServerAdapterRequestHandler, } from "@aws/run-mcp-servers-with-aws-lambda"; const serverParams = { command: "npx", args: [ "--offline", "my-mcp-server-typescript-module", "--my-server-command-line-parameter", "some_value", ], }; const requestHandler = new LambdaFunctionURLEventHandler( new StdioServerAdapterRequestHandler(serverParams) ); export const handler: Handler = async ( event: APIGatewayProxyEventV2WithIAMAuthorizer, context: Context ): Promise => { return requestHandler.handle(event, context); }; ``` -------------------------------- ### TypeScript MCP Server Lambda Handler Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md This handler allows an existing TypeScript MCP server to run within an AWS Lambda function. It utilizes the `@aws/run-mcp-servers-with-aws-lambda` library and requires server parameters to specify the command and arguments. ```typescript import { Handler, Context } from "aws-lambda"; import { stdioServerAdapter } from "@aws/run-mcp-servers-with-aws-lambda"; const serverParams = { command: "npx", args: [ "--offline", "my-mcp-server-typescript-module", "--my-server-command-line-parameter", "some_value", ], }; export const handler: Handler = async (event, context: Context) => { return await stdioServerAdapter(serverParams, event, context); }; ``` -------------------------------- ### TypeScript MCP Client for Lambda Function Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md This TypeScript client connects to an MCP server deployed as a Lambda function. It uses `LambdaFunctionClientTransport` from `@aws/run-mcp-servers-with-aws-lambda` and the `@modelcontextprotocol/sdk` to establish a connection and interact with the server. ```typescript import { LambdaFunctionParameters, LambdaFunctionClientTransport, } from "@aws/run-mcp-servers-with-aws-lambda"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; const serverParams: LambdaFunctionParameters = { functionName: "my-mcp-server-function", regionName: "us-west-2", }; const client = new Client( { name: "my-client", version: "0.0.1", }, { capabilities: { sampling: {}, }, } ); const transport = new LambdaFunctionClientTransport(serverParams); await client.connect(transport); ``` -------------------------------- ### Retrieve API key from Secrets Manager (Python) Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Use this snippet to retrieve an API key from AWS Secrets Manager in a Python Lambda function. Ensure the Lambda function has permissions to access the specified secret. ```python import boto3 secrets_client = boto3.client("secretsmanager") api_key = secrets_client.get_secret_value(SecretId="my-api-key-secret")["SecretString"] ``` -------------------------------- ### Retrieve API key from Secrets Manager (TypeScript) Source: https://github.com/awslabs/run-model-context-protocol-servers-with-aws-lambda/blob/main/README.md Use this snippet to retrieve an API key from AWS Secrets Manager in a TypeScript Lambda function. Ensure the Lambda function has permissions to access the specified secret. ```typescript import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager"; const secretsClient = new SecretsManagerClient({}); const secret = await secretsClient.send( new GetSecretValueCommand({ SecretId: "my-api-key-secret" }) ); const apiKey = secret.SecretString; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.