generated from amazon-archives/__template_Apache-2.0
-
Notifications
You must be signed in to change notification settings - Fork 8
feat: add FastMCP Lambda template for MCP server scaffolding #420
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
aidandaly24
wants to merge
4
commits into
aws:feat/gateway-integration
from
aidandaly24:feat/batch-5-fastmcp-lambda-template
Closed
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
d0754e0
feat: add FastMCP Lambda template for MCP server scaffolding
aidandaly24 85577a8
fix: rename handler to lambda_handler to match DEFAULT_HANDLER
aidandaly24 e3d19f2
fix: use correct template variable casing and switch to http_app() fo…
aidandaly24 9c3817b
fix: use streamable_http_app() instead of http_app() for FastMCP Lambda
aidandaly24 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| """ | ||
| FastMCP Server for AWS Lambda with Function URL. | ||
|
|
||
| This template shows: | ||
| - FastMCP server running on Lambda via Lambda Web Adapter + uvicorn | ||
| - 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 mcp.server.fastmcp import FastMCP | ||
|
|
||
| logging.basicConfig(level=logging.INFO, format="%(levelname)s - %(message)s") | ||
| logger = logging.getLogger(__name__) | ||
|
|
||
| mcp = FastMCP("{{ Name }}", stateless_http=True, host="0.0.0.0") | ||
|
|
||
| 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']}" | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| [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.18.0", | ||
| "httpx >= 0.27.0", | ||
| "fastapi >= 0.115.0", | ||
| "uvicorn >= 0.34.0", | ||
| ] | ||
|
|
||
| [tool.hatch.build.targets.wheel] | ||
| packages = ["."] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| #!/bin/bash | ||
| exec python -m uvicorn --port=$PORT server:app |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| from fastapi import FastAPI | ||
| from handler import mcp | ||
|
|
||
| app = FastAPI(lifespan=lambda app: mcp.session_manager.run()) | ||
| app.mount("/", mcp.streamable_http_app()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.