The Traveling Lambda: An AgentCore Build Diary
A hands-on journey through Strands Agents, Bedrock, MCP, and API Gateway, building a travel assistant from a single Lambda function into a fully authenticated, traceable service.
Why I Built This
There's a big gap between an AI agent that answers a question in a test console and one that's actually a product, something a real user could call, that remembers who they are, knows things about your business, and that you can debug when something goes wrong.
I wanted to close that gap myself using AWS's Strands Agents SDK. What follows is the full journey: starting from a bare-bones agent with one tool, and finishing with a secured REST API backed by memory, private knowledge, external MCP tools, and full request tracing.
Here's where we end up:
User ↓API Gateway (REST, TLS 1.3) ↓Cognito Authorizer ↓/chat POST ↓strands-travel-agent Lambda ↓MCP Client ↓Attractions Gateway (Bedrock AgentCore) ↓Attractions Lambda
Module 1: Building the Agent
Every agent starts somewhere simple. My first version of
strands-travel-agent was a single Lambda function with one tool: a hardcoded flight_search function returning airline options for a handful of cities.Steps: Go to the Lambda console → open
strands-travel-agent → paste the code below into index.py → click Deploy.from strands import Agent, toolfrom typing import Dict, Any
TRAVEL_AGENT_PROMPT = """You are a travel assistant that can help customers book their travel. Think step-by-step. Limit your answers to the user prompt.Tools available:- Use the flight_search tool to provide flight carrier choices for their destination."""
@tooldef flight_search(city: str) -> dict: """Get available flight options to a city.""" flights = { "Atlanta": ["Delta Airlines", "Spirit Airlines"], "Seattle": ["Alaska Airlines", "Delta Airlines"], "New York": ["United Airlines", "JetBlue"] } return flights[city]
def handler(event: Dict[str, Any], _context) -> str: travel_agent = Agent( model="us.amazon.nova-lite-v1:0", system_prompt=TRAVEL_AGENT_PROMPT, tools=[flight_search] ) response = travel_agent(event.get('prompt')) return str(response)
Test it: click the Test tab → name the event
Test → paste {"prompt": "What are the flight options to Seattle?"} → Save and Test. You should get back a natural-language answer listing Alaska and Delta.
Module 2: Integrating an External API
A hardcoded dictionary is a fine starting tool, but real usefulness comes from live data. So next I gave the agent access to the National Weather Service API, using the built-in
http_request tool from strands-tools — no custom HTTP client code needed.Steps: In the same Lambda, add
from strands_tools import http_request , add it to the tools=[...] list, and extend the system prompt with strict rules about when/how to fetch weather. Deploy, then test with {"prompt": "What is the weather forecast for Seattle?"} . You should get a live 5-day forecast summary pulled straight from a government API.
Module 3: Giving the Agent Memory
Without memory, every message is a fresh start. Module 3 added persistent memory using Strands' built-in S3 Session Manager, which stores conversation history in S3 keyed by session ID.
Steps: Add
from strands.session.s3_session_manager import S3SessionManager , then in the handler:session_manager = S3SessionManager( session_id=event["user"]["session_id"], bucket=os.environ['SESSIONS_BUCKET'], prefix="agent-sessions")travel_agent = Agent(..., session_manager=session_manager)
Deploy, then test twice with the same
session_id (e.g. "123" ): first ask about flights to Seattle, then ask "Can you tell me some local things to do?" without naming a city again. The agent should correctly infer Seattle from memory. Check the S3 bucket prefixed strands-travelagents3sessionsbucket — you'll find a subdirectory under agent-sessions per session with the full history.
Module 4: Adding Private Knowledge with RAG
Module 4 connected the agent to an Amazon Bedrock Knowledge Base backed by Amazon S3 Vectors, enabling Retrieval Augmented Generation over a private list of Seattle tour operators.
Steps to create the Knowledge Base:
- Open CloudShell, upload the sample tour-operator file to your
strands-travelagents3bucketragS3 bucket.
- Open the Bedrock console → Knowledge bases (left sidebar) → Create → Knowledge Base with vector store.
- Name it
StrandsTravelAgentKB, select the existingstrands-BedrockKnowledgeBaseRolerole → Next.
- Set data source name
TravelAgentS3DataSource, browse to your S3 bucket → Next.
- Choose Titan Text Embeddings v2 as the embedding model, keep Amazon S3 Vectors as the vector store → Next → Create knowledge base.
- On the Knowledge Base details page, find your data source and click Sync — wait for status Available.
- Copy the Knowledge Base ID from the overview section at the top.
Steps to wire it into the agent: In the Lambda console, go to Configuration → Environment variables, set
KNOWLEDGE_BASE_ID to the ID you copied, and save. Then update the code to import retrieve from strands_tools and add it to the tools list. Deploy, then test with {"prompt": "What are some tour operators with water activities?", "user": {"session_id": "123"}} — the response should reflect your private document, and the Lambda logs will show the retrieve tool being called.
Module 5: Connecting to an MCP Server
This is where the architecture got genuinely interesting. Instead of hardcoding every tool into the agent's own Lambda, Module 5 used the Model Context Protocol (MCP) to let the agent dynamically discover and call tools hosted on a separate service.
Steps to create the Gateway:
- Open the Bedrock AgentCore console → Gateways (left sidebar, under Build and Deploy) → Create gateway.
- Name it
TravelAttractionsGateway, keep Quick create with Cognito selected.
- Under IAM Permissions, select the existing
strands-AgentCoreGatewayExecutionRole.
- Target details: name
TravelAttractionsLambdaTarget, target type Lambda ARN — go to the Lambda console, open theattractionsfunction, copy its ARN, paste it in.
- Target schema: choose Define an inline schema, paste in the JSON describing
list_attractions,reserve_ticket, andcancel_ticket.
- Leave the rest as default → Create gateway.
Steps to wire the agent as an MCP client: In
strands-travel-agent , add the MCP client code (imports for MCPClient and streamablehttp_client , a fetch_access_token helper using client-credentials OAuth2, and a transport that attaches the bearer token). Inside the handler, fetch the token, open the MCP client, call list_tools_sync() , and merge those tools with your existing ones before creating the Agent . Deploy.Steps to configure credentials: Open CloudShell, run the provided
agentcore_gateway_info.sh script to retrieve CLIENT_ID , CLIENT_SECRET , DOMAIN_URL , and GATEWAY_URL . Go to the Lambda's Configuration → Environment variables, paste in these four values, save.Test it with
{"prompt": "Reserve your ticket for the Space Needle on December 20th at 9 AM", "user": {"session_id": "test-mcp-456"}} — you should get back a real reservation confirmation with a reservation code, generated by a completely separate Lambda reached through the gateway.
Module 6: Exposing the Agent Through API Gateway
Everything so far had been tested from inside the Lambda console. To make the agent callable by an actual client, I needed a real HTTPS endpoint.
Steps to create the API:
- Open the API Gateway console → Create API → under REST API, click Build → New API.
- Name:
strands-travel-agent. Endpoint Type: Regional. Security Policy: TLS 1.3 – 2025_09 (Recommended) (older workshop docs may referenceSecurityPolicy_TLS13_1_2_2021_06— if you don't see that option, the "Recommended" TLS 1.3 policy is its replacement). Endpoint access mode: Basic → Create API.
Steps to add the /chat endpoint:
- Resources (left sidebar) → select root
/→ Create Resource.
- Resource Name:
chat, leave CORS unchecked → Create Resource.
- Select
/chat→ Create Method → choose POST.
- Integration type Lambda Function, enable Lambda Proxy integration, Response transfer mode Buffered, Lambda Function
strands-travel-agent→ Create method → choose Allow if prompted for invoke permission.
Steps to secure it with Cognito:
- Authorizers (left sidebar) → Create authorizer.
- Name
CognitoAuthorizer, Type Cognito, User PoolStrandsAgentUserPool, Token SourceAuthorization→ Create Authorizer.
- Back in Resources → /chat → POST → Method Request, click Edit, set Authorization to
CognitoAuthorizer, Save.
Steps to deploy: Click Deploy API → Deployment stage [New Stage] → Stage name
prod → Deploy.The Payload Shape Gotcha
Testing the Lambda directly, the expected event was
{"prompt": "...", "user": {"session_id": "..."}} . Through API Gateway, the prompt instead arrives as a JSON string nested in body : {"body": "{\"prompt\":\"...\"}"} . The handler needs updating to parse it explicitly, and to pull the session ID from the authenticated Cognito claims instead:body = json.loads(event['body'])session_manager = S3SessionManager( session_id=event["requestContext"]["authorizer"]["claims"]["cognito:username"], bucket=os.environ['SESSIONS_BUCKET'], prefix="agent-sessions")response = travel_agent(body['prompt'])
I also wrapped the handler in try/except (returning proper HTTP status codes) and stripped stray
<thinking> tags from the model's output before returning it. Deploy the updated Lambda code.One more thing worth checking if you've rebuilt any upstream resource: make sure the Lambda's environment variables still point at the current gateway/pool, not stale values from an earlier version.
Steps to create a test user: Open CloudShell, run:
USER_POOL_ID=$(aws cognito-idp list-user-pools --max-results 20 \ --query 'UserPools[?Name==`StrandsAgentUserPool`].Id' --output text)CLIENT_ID=$(aws cognito-idp list-user-pool-clients --user-pool-id $USER_POOL_ID \ --query 'UserPoolClients[0].ClientId' --output text)
aws cognito-idp admin-create-user --user-pool-id $USER_POOL_ID --username testuser \ --user-attributes Name=email,Value=test@example.com Name=email_verified,Value=true \ --temporary-password "TempPass123!" --message-action SUPPRESS
aws cognito-idp admin-set-user-password --user-pool-id $USER_POOL_ID \ --username testuser --password "MyPassword123!" --permanent
Then get a token:
TOKEN_RESPONSE=$(aws cognito-idp admin-initiate-auth --user-pool-id $USER_POOL_ID \ --client-id $CLIENT_ID --auth-flow ADMIN_NO_SRP_AUTH \ --auth-parameters USERNAME=testuser,PASSWORD="MyPassword123!")ID_TOKEN=$(echo $TOKEN_RESPONSE | jq -r '.AuthenticationResult.IdToken')
Steps to get your Invoke URL: In API Gateway, go to Stages → prod → / → /chat → POST, copy the Invoke URL.
Test it:
API_URL="your-invoke-url-here"curl -X POST "$API_URL" \ -H "Authorization: $ID_TOKEN" -H "Content-Type: application/json" \ -d '{"prompt": "What are the flight options to Seattle?"}' | jq
That single response travels through six AWS services — API Gateway, Cognito, Lambda, S3, Bedrock Knowledge Bases, and the MCP Gateway to a second Lambda — fully authenticated, end to end.
Module 7 (Optional): Making the Request Flow Observable
AWS presents this as a "challenge module" — no exact steps, just an objective: get a working CloudWatch Trace Map showing the full service topology. Here's the configuration that gets you there. No code changes needed.
Steps to enable X-Ray on API Gateway: API Gateway console →
strands-travel-agent → Stages → prod → Logs and tracing tab → Edit → toggle X-Ray tracing on → Save.Steps to enable Application Signals on the Lambda: Lambda console →
strands-travel-agent → Configuration tab → Monitoring and operations tools → Additional monitoring tools → Edit → enable Application Signals and Lambda service traces → Save.Generate traffic, sending a few varied requests through your API Gateway endpoint (different prompts work best).
View the trace map: CloudWatch console → Application Signals → Trace Map. You'll see the full service topology; click any individual trace to inspect timing and catch errors.
If you only add one thing after getting a serverless project working, make it this — two minutes of configuration turns a black-box request into a fully inspectable pipeline.
What I'd Tell Someone Starting This From Scratch
- Build up in layers, and test at every layer. Each module added exactly one new capability, and testing after each one meant I always knew exactly which change had broken something, if anything did.
- Watch for event-shape changes when adding infrastructure. Testing a Lambda directly vs. through API Gateway are genuinely different payloads — this cost me the most debugging time.
- Recheck environment variables after any resource rebuild. If you recreate a gateway, pool, or bucket, your Lambda has no idea — stale references are one of the sneakiest bugs to chase.
- Turn on tracing early, not after something breaks. It costs almost nothing to enable and saves real time later.
- Treat any exposed secret as compromised. If a client secret ends up in a screenshot, chat log, or shared doc, rotate it — regardless of whether the environment is "just a workshop."
Final Architecture
User ↓API Gateway (REST, TLS 1.3, Regional) ↓Cognito Authorizer (JWT validation) ↓/chat POST ↓strands-travel-agent Lambda ├─→ S3 Session Manager (conversation memory) ├─→ Bedrock Knowledge Base (RAG — tour operators) ├─→ National Weather Service API (live weather) └─→ MCP Client ↓ Attractions Gateway (Bedrock AgentCore, OAuth2/Cognito) ↓ Attractions Lambda (list/reserve/cancel tickets)
What started as a single Lambda function returning a hardcoded flight list is now a secured, memory-backed, RAG-enabled, multi-service AI agent with full observability — reachable over HTTPS by any authenticated client. The most valuable lesson wasn't really about agentic AI specifically: it's that agents built this way don't need a special deployment story. They need the same solid AWS fundamentals — IAM, API Gateway, Cognito, tracing — that any serious serverless application needs, wrapped around the reasoning layer.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article