Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
174 changes: 174 additions & 0 deletions src/assets/__tests__/__snapshots__/assets.snapshot.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,9 @@ exports[`Assets Directory Snapshots > File listing > should match the expected f
"cdk/tsconfig.json",
"container/python/Dockerfile",
"container/python/dockerignore.template",
"mcp/python-fastmcp-lambda/README.md",
"mcp/python-fastmcp-lambda/handler.py",
"mcp/python-fastmcp-lambda/pyproject.toml",
"mcp/python-lambda/README.md",
"mcp/python-lambda/handler.py",
"mcp/python-lambda/pyproject.toml",
Expand Down Expand Up @@ -631,6 +634,177 @@ if __name__ == "__main__":
"
`;

exports[`Assets Directory Snapshots > MCP assets > mcp/mcp/python-fastmcp-lambda/README.md should match snapshot 1`] = `
"# {{ name }}

FastMCP server running on AWS Lambda with a function URL, generated by the AgentCore CLI.

Demonstrates HTTP tool patterns with proper error handling and retry logic.

## How It Works

This server uses [FastMCP](https://github.com/jlowin/fastmcp) to define MCP tools and
[Mangum](https://github.com/jordanh/mangum) to adapt the ASGI app for AWS Lambda.
The Lambda function URL provides the HTTP endpoint that the AgentCore gateway connects to.

## Available Tools

| Tool | Description |
| ----------------- | ------------------------------------------------------ |
| \`lookup_ip\` | Look up geolocation and network info for an IP address |
| \`get_random_user\` | Generate a random user profile for testing |
| \`fetch_post\` | Fetch a post by ID from JSONPlaceholder API |

## Deployment

\`\`\`bash
agentcore deploy
\`\`\`

The CDK stack creates the Lambda function, function URL, and wires it to the gateway target.
"
`;

exports[`Assets Directory Snapshots > MCP assets > mcp/mcp/python-fastmcp-lambda/handler.py should match snapshot 1`] = `
""""
FastMCP Server for AWS Lambda with Function URL.

This template shows:
- FastMCP server running on Lambda via Mangum ASGI adapter
- HTTP tool patterns with proper error handling
- Retry logic and response validation

Deploy with: agentcore deploy
"""

import logging
from typing import Any

import httpx
from mangum import Mangum
from mcp.server.fastmcp import FastMCP

logging.basicConfig(level=logging.INFO, format="%(levelname)s - %(message)s")
logger = logging.getLogger(__name__)

mcp = FastMCP("tools")

HTTP_TIMEOUT = 10.0
MAX_RETRIES = 2


async def fetch_json(url: str, headers: dict[str, str] | None = None) -> dict[str, Any] | None:
"""Make an HTTP GET request with retry logic."""
async with httpx.AsyncClient() as client:
for attempt in range(MAX_RETRIES):
try:
response = await client.get(url, headers=headers, timeout=HTTP_TIMEOUT)
response.raise_for_status()
return response.json()
except httpx.TimeoutException:
logger.warning(f"Timeout on attempt {attempt + 1} for {url}")
except httpx.HTTPStatusError as e:
logger.error(f"HTTP {e.response.status_code} for {url}")
return None
except httpx.RequestError as e:
logger.error(f"Request failed: {e}")
return None
return None


@mcp.tool()
async def lookup_ip(ip_address: str) -> str:
"""Look up geolocation and network info for an IP address.

Args:
ip_address: IPv4 or IPv6 address to look up
"""
data = await fetch_json(f"http://ip-api.com/json/{ip_address}")

if not data:
return f"Failed to look up IP: {ip_address}"

if data.get("status") == "fail":
return f"Lookup failed: {data.get('message', 'unknown error')}"

return (
f"IP: {data['query']}\\n"
f"Location: {data['city']}, {data['regionName']}, {data['country']}\\n"
f"ISP: {data['isp']}\\n"
f"Organization: {data['org']}\\n"
f"Timezone: {data['timezone']}"
)


@mcp.tool()
async def get_random_user() -> str:
"""Generate a random user profile for testing or mock data."""
data = await fetch_json("https://randomuser.me/api/")

if not data or "results" not in data:
return "Failed to generate random user."

user = data["results"][0]
name = user["name"]
location = user["location"]

return (
f"Name: {name['first']} {name['last']}\\n"
f"Email: {user['email']}\\n"
f"Location: {location['city']}, {location['country']}\\n"
f"Phone: {user['phone']}"
)


@mcp.tool()
async def fetch_post(post_id: int) -> str:
"""Fetch a post by ID from JSONPlaceholder API.

Args:
post_id: The post ID (1-100)
"""
if not 1 <= post_id <= 100:
return "Post ID must be between 1 and 100."

data = await fetch_json(f"https://jsonplaceholder.typicode.com/posts/{post_id}")

if not data:
return f"Failed to fetch post {post_id}."

return (
f"Post #{data['id']}\\n"
f"Title: {data['title']}\\n\\n"
f"{data['body']}"
)


# Create ASGI app from FastMCP server and wrap with Mangum for Lambda
lambda_handler = Mangum(mcp.sse_app(), lifespan="off")
"
`;

exports[`Assets Directory Snapshots > MCP assets > mcp/mcp/python-fastmcp-lambda/pyproject.toml should match snapshot 1`] = `
"[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "{{ name }}"
version = "0.1.0"
description = "FastMCP Server on AWS Lambda"
readme = "README.md"
requires-python = ">=3.10"
dependencies = [
"mcp[cli] >= 1.2.0",
"httpx >= 0.27.0",
"mangum >= 0.19.0",
]

[tool.hatch.build.targets.wheel]
packages = ["."]
"
`;

exports[`Assets Directory Snapshots > MCP assets > mcp/mcp/python-lambda/README.md should match snapshot 1`] = `
"# {{ Name }}

Expand Down
27 changes: 27 additions & 0 deletions src/assets/mcp/python-fastmcp-lambda/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# {{ name }}

FastMCP server running on AWS Lambda with a function URL, generated by the AgentCore CLI.

Demonstrates HTTP tool patterns with proper error handling and retry logic.

## How It Works

This server uses [FastMCP](https://github.com/jlowin/fastmcp) to define MCP tools and
[Mangum](https://github.com/jordanh/mangum) to adapt the ASGI app for AWS Lambda.
The Lambda function URL provides the HTTP endpoint that the AgentCore gateway connects to.

## Available Tools

| Tool | Description |
| ----------------- | ------------------------------------------------------ |
| `lookup_ip` | Look up geolocation and network info for an IP address |
| `get_random_user` | Generate a random user profile for testing |
| `fetch_post` | Fetch a post by ID from JSONPlaceholder API |

## Deployment

```bash
agentcore deploy
```

The CDK stack creates the Lambda function, function URL, and wires it to the gateway target.
114 changes: 114 additions & 0 deletions src/assets/mcp/python-fastmcp-lambda/handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
"""
FastMCP Server for AWS Lambda with Function URL.

This template shows:
- FastMCP server running on Lambda via Mangum ASGI adapter
- HTTP tool patterns with proper error handling
- Retry logic and response validation

Deploy with: agentcore deploy
"""

import logging
from typing import Any

import httpx
from mangum import Mangum
from mcp.server.fastmcp import FastMCP

logging.basicConfig(level=logging.INFO, format="%(levelname)s - %(message)s")
logger = logging.getLogger(__name__)

mcp = FastMCP("tools")

HTTP_TIMEOUT = 10.0
MAX_RETRIES = 2


async def fetch_json(url: str, headers: dict[str, str] | None = None) -> dict[str, Any] | None:
"""Make an HTTP GET request with retry logic."""
async with httpx.AsyncClient() as client:
for attempt in range(MAX_RETRIES):
try:
response = await client.get(url, headers=headers, timeout=HTTP_TIMEOUT)
response.raise_for_status()
return response.json()
except httpx.TimeoutException:
logger.warning(f"Timeout on attempt {attempt + 1} for {url}")
except httpx.HTTPStatusError as e:
logger.error(f"HTTP {e.response.status_code} for {url}")
return None
except httpx.RequestError as e:
logger.error(f"Request failed: {e}")
return None
return None


@mcp.tool()
async def lookup_ip(ip_address: str) -> str:
"""Look up geolocation and network info for an IP address.

Args:
ip_address: IPv4 or IPv6 address to look up
"""
data = await fetch_json(f"http://ip-api.com/json/{ip_address}")

if not data:
return f"Failed to look up IP: {ip_address}"

if data.get("status") == "fail":
return f"Lookup failed: {data.get('message', 'unknown error')}"

return (
f"IP: {data['query']}\n"
f"Location: {data['city']}, {data['regionName']}, {data['country']}\n"
f"ISP: {data['isp']}\n"
f"Organization: {data['org']}\n"
f"Timezone: {data['timezone']}"
)


@mcp.tool()
async def get_random_user() -> str:
"""Generate a random user profile for testing or mock data."""
data = await fetch_json("https://randomuser.me/api/")

if not data or "results" not in data:
return "Failed to generate random user."

user = data["results"][0]
name = user["name"]
location = user["location"]

return (
f"Name: {name['first']} {name['last']}\n"
f"Email: {user['email']}\n"
f"Location: {location['city']}, {location['country']}\n"
f"Phone: {user['phone']}"
)


@mcp.tool()
async def fetch_post(post_id: int) -> str:
"""Fetch a post by ID from JSONPlaceholder API.

Args:
post_id: The post ID (1-100)
"""
if not 1 <= post_id <= 100:
return "Post ID must be between 1 and 100."

data = await fetch_json(f"https://jsonplaceholder.typicode.com/posts/{post_id}")

if not data:
return f"Failed to fetch post {post_id}."

return (
f"Post #{data['id']}\n"
f"Title: {data['title']}\n\n"
f"{data['body']}"
)


# Create ASGI app from FastMCP server and wrap with Mangum for Lambda
lambda_handler = Mangum(mcp.sse_app(), lifespan="off")
18 changes: 18 additions & 0 deletions src/assets/mcp/python-fastmcp-lambda/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "{{ name }}"
version = "0.1.0"
description = "FastMCP Server on AWS Lambda"
readme = "README.md"
requires-python = ">=3.10"
dependencies = [
"mcp[cli] >= 1.2.0",
"httpx >= 0.27.0",
"mangum >= 0.19.0",
]

[tool.hatch.build.targets.wheel]
packages = ["."]
Loading
Loading