Skip to main content

Transport-agnostic Model Context Protocol (MCP) server core for AWS Lambda

Project description

mcpbytes-lambda-core

Python 3.12+ MCP 2025-06-18 License: Apache 2.0

Transport-agnostic Model Context Protocol (MCP) server core for AWS Lambda. Build production-ready MCP servers that work across multiple transports without vendor lock-in.

๐Ÿš€ Quick Start

from mcpbytes_lambda.core import MCPServer, ToolResult, TextContent

# Create server with default 1MB payload limit
mcp = MCPServer(name="math-server", version="1.0.0")

@mcp.tool(name="math.add", read_only=True, idempotent=True)
def add_numbers(a: float, b: float) -> ToolResult:
    """Add two numbers with high precision."""
    result = a + b
    return ToolResult(
        content=[TextContent(text=f"{a} + {b} = {result}")],
        isError=False
    )

# Use with any transport (API Gateway, stdio, etc.)
def lambda_handler(event, context):
    from mcpbytes_lambda.apigw import ApiGatewayAdapter
    return mcp.handle(event, ApiGatewayAdapter())

โš™๏ธ Payload Size Configuration

Configure maximum request payload size based on your transport:

# Default (1MB) - works across all transports
mcp = MCPServer(name="my-server")

# API Gateway optimized (10MB maximum)
mcp = MCPServer(name="api-server", max_payload_size=10_000_000)

# Stdio unlimited (for local development)
mcp = MCPServer(name="stdio-server", max_payload_size=100_000_000)

# Conservative (512KB for ALB)
mcp = MCPServer(name="alb-server", max_payload_size=512_000)

Transport Limits:

  • API Gateway: 10MB maximum
  • Lambda Direct: 6MB maximum
  • ALB: 1MB maximum
  • Stdio: No inherent limit

โœจ Features

  • ๐Ÿ”Œ Transport Agnostic - Works with API Gateway, stdio, Lambda Function URLs, ALB
  • ๐Ÿ“ Auto Schema Generation - JSON Schema from Python type hints
  • ๐Ÿ›ก๏ธ Built-in Validation - Parameter validation with clear error messages
  • โšก Sync + Async Support - Handle both synchronous and asynchronous tools
  • ๐Ÿ“Š Structured Output - MCP 2025-06-18 structured data support
  • ๐ŸŽฏ Zero Cold Start - Optimized for AWS Lambda performance
  • ๐Ÿ”’ Production Ready - Comprehensive error handling and logging

๐Ÿ“‹ Requirements

  • Python 3.12+
  • No runtime dependencies (pure Python)

๐Ÿ—๏ธ Architecture

The core provides the foundation for MCP servers without transport coupling:

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Transport      โ”‚โ”€โ”€โ”€โ–ถโ”‚   Core       โ”‚โ”€โ”€โ”€โ–ถโ”‚   Your Tools    โ”‚
โ”‚  (HTTP/stdio)   โ”‚    โ”‚  Protocol    โ”‚    โ”‚   & Prompts     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

๐Ÿ› ๏ธ Usage Examples

Simple Tool

@mcp.tool(name="greet", description="Greet a user")
def greet(name: str) -> ToolResult:
    return ToolResult(
        content=[TextContent(text=f"Hello, {name}!")],
        isError=False
    )

Structured Output Tool (MCP 2025-06-18)

@mcp.tool(name="calculate", structured_output=True)
def calculate(operation: str, values: List[float]) -> Dict[str, Any]:
    """Returns structured data with auto-generated schema."""
    result = sum(values) if operation == "sum" else max(values)
    return {
        "operation": operation,
        "input_values": values,
        "result": result,
        "timestamp": "2025-06-18T12:00:00Z"
    }

Async Tool

@mcp.tool(name="fetch_data", read_only=True)
async def fetch_data(url: str) -> ToolResult:
    # Async operations supported natively
    async with httpx.AsyncClient() as client:
        response = await client.get(url)
        return ToolResult(
            content=[TextContent(text=response.text[:500])],
            isError=False
        )

Prompt Templates

@mcp.prompt(name="code_review")
def code_review_prompt(language: str, code: str) -> str:
    """Generate code review prompt."""
    return f"Review this {language} code for best practices:\n\n```{language}\n{code}\n```"

๐Ÿ”Œ Transport Adapters

The core works with multiple transport adapters:

  • mcpbytes-lambda-apigw - API Gateway + Lambda
  • mcpbytes-lambda-stdio - stdin/stdout (local MCP servers)
  • mcpbytes-lambda-invoke - Direct Lambda invocation
  • mcpbytes-lambda-alb - Application Load Balancer + Lambda

๐Ÿ“– API Reference

MCPServer

MCPServer(
    name: str,                           # Server name
    version: str = "1.0.0",             # Server version  
    description: Optional[str] = None,   # Server description
    log_level: str = "INFO",             # Logging level
    max_payload_size: int = 1_000_000    # Maximum request payload size in bytes
)

@tool Decorator

@mcp.tool(
    name: Optional[str] = None,           # Tool name (defaults to function name)
    description: Optional[str] = None,    # Description (from docstring)
    title: Optional[str] = None,          # Human-readable title
    read_only: bool = False,              # Tool only reads data
    destructive: bool = False,            # Tool can destroy data
    idempotent: bool = False,             # Safe to call repeatedly
    open_world: bool = True,              # Interacts with external systems
    structured_output: bool = False       # Enable structured output (MCP 2025-06-18)
)

ToolResult

ToolResult(
    content: List[ContentBlock],                    # Text/resource content blocks
    isError: bool = False,                         # Whether this is an error
    structuredContent: Optional[Dict] = None       # Structured data (MCP 2025-06-18)
)

๐Ÿงช Testing

# Test your tools directly
def test_add_tool():
    result = add_numbers(2, 3)
    assert not result.isError
    assert "5" in result.content[0].text

# Test with mock transport
def test_server_integration():
    event = {"body": '{"jsonrpc":"2.0","method":"tools/list","id":"1"}'}
    from mcpbytes_lambda.apigw import ApiGatewayAdapter
    
    response = mcp.handle(event, ApiGatewayAdapter())
    assert response["statusCode"] == 200

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature-name
  3. Make your changes and add tests
  4. Run tests: python -m pytest
  5. Submit a pull request

๐Ÿ“„ License

Apache 2.0 License - see LICENSE for details.

๐Ÿ”— Related Packages

๐Ÿ“š Documentation


Built with โค๏ธ for the MCP ecosystem

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mcpbytes_lambda_core-0.2.1.tar.gz (49.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mcpbytes_lambda_core-0.2.1-py3-none-any.whl (22.1 kB view details)

Uploaded Python 3

File details

Details for the file mcpbytes_lambda_core-0.2.1.tar.gz.

File metadata

  • Download URL: mcpbytes_lambda_core-0.2.1.tar.gz
  • Upload date:
  • Size: 49.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for mcpbytes_lambda_core-0.2.1.tar.gz
Algorithm Hash digest
SHA256 eb953f574b1f9c8a2249e4250d911c2272174753e6a5b6bd04208a5606caa7cd
MD5 29a46306b3b2eab27966d06dd74809d2
BLAKE2b-256 d169f327d223b11e672f885c06de0caefffaa043e9c3a9f571729820b4f62873

See more details on using hashes here.

File details

Details for the file mcpbytes_lambda_core-0.2.1-py3-none-any.whl.

File metadata

File hashes

Hashes for mcpbytes_lambda_core-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 6f987e8ddd39dec028aac2087ed162a4c39f8bb1b862a8c0b62bf79951d567f3
MD5 d380ca194936b64cea7e5436d3c329b9
BLAKE2b-256 552f8f7d5a08e90f0c6fc0ad844297a27efd4a0db7e5fc7307f774a7fd631092

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page