Skip to content

Implement and configure the Story agent

The Story Agent is a Strands agent which, given a Game and a list of Actions for context, will progress a story. We will configure the agent to interact with our Inventory MCP Server to manage a player’s available items.

To implement our agent, update the following files in packages/story/dungeon_adventure_story/agent:

import uuid
import uvicorn
from bedrock_agentcore.runtime.models import PingStatus
from fastapi.responses import PlainTextResponse, StreamingResponse
from pydantic import BaseModel
from .agent import get_agent
from .init import app
class Action(BaseModel):
role: str
content: str
class InvokeInput(BaseModel):
playerName: str
genre: str
actions: list[Action]
async def handle_invoke(input: InvokeInput):
"""Streaming handler for agent invocation"""
messages = [{"role": "user", "content": [{"text": "Continue or create a new story..."}]}]
for action in input.actions:
messages.append({"role": action.role, "content": [{"text": action.content}]})
with get_agent(input.playerName, input.genre, session_id=str(uuid.uuid4())) as agent:
stream = agent.stream_async(messages)
async for event in stream:
print(event)
content = event.get("event", {}).get("contentBlockDelta", {}).get("delta", {}).get("text")
if content is not None:
yield content
elif event.get("event", {}).get("messageStop") is not None:
yield "\n"
@app.post("/invocations", openapi_extra={"x-streaming": True}, response_class=PlainTextResponse)
async def invoke(input: InvokeInput) -> str:
"""Entry point for agent invocation"""
return StreamingResponse(handle_invoke(input), media_type="text/event-stream")
@app.get("/ping")
def ping() -> str:
# TODO: if running an async task, return PingStatus.HEALTHY_BUSY
return PingStatus.HEALTHY
if __name__ == "__main__":
uvicorn.run("dungeon_adventure_story.agent.main:app", port=8080)

This will configure the following:

  • Extracting the player, genre and actions from the agent payload,
  • Constructing a client which the Agent can use to invoke our MCP server with SigV4 Authentication, and
  • Constructing the agent with a system prompt and the MCP server’s tools.

To build the code:

Terminal window
pnpm nx run-many --target build --all

To deploy your application, run the following command:

Terminal window
pnpm nx deploy infra dungeon-adventure-infra-sandbox/*

This deployment will take around 2 minutes to complete.

Once the deployment completes, you will see outputs similar to the following (some values have been redacted):

Terminal window
dungeon-adventure-infra-sandbox-Application
dungeon-adventure-infra-sandbox-Application: deploying... [2/2]
dungeon-adventure-infra-sandbox-Application
Deployment time: 354s
Outputs:
dungeon-adventure-infra-sandbox-Application.ElectroDbTableTableNameXXX = dungeon-adventure-infra-sandbox-Application-ElectroDbTableXXX-YYY
dungeon-adventure-infra-sandbox-Application.GameApiEndpointXXX = https://xxx.execute-api.region.amazonaws.com/prod/
dungeon-adventure-infra-sandbox-Application.GameUIDistributionDomainNameXXX = xxx.cloudfront.net
dungeon-adventure-infra-sandbox-Application.InventoryMcpArn = arn:aws:bedrock-agentcore:region:xxxxxxx:runtime/dungeonadventureventoryMcpServerXXXX-YYYY
dungeon-adventure-infra-sandbox-Application.StoryAgentArn = arn:aws:bedrock-agentcore:region:xxxxxxx:runtime/dungeonadventurecationStoryAgentXXXX-YYYY
dungeon-adventure-infra-sandbox-Application.UserIdentityUserIdentityIdentityPoolIdXXX = region:xxx
dungeon-adventure-infra-sandbox-Application.UserIdentityUserIdentityUserPoolIdXXX = region_xxx

You can test your API by either:

  • Starting a local instance of the Agent server and invoking it using curl, or
  • Calling the deployed API using curl with a JWT token.

Start your local Agent server by running the following command:

Terminal window
INVENTORY_MCP_ARN=arn:aws:bedrock-agentcore:region:xxxxxxx:runtime/dungeonadventureventoryMcpServerXXXX-YYYY AWS_REGION=<region> pnpm nx run dungeon_adventure.story:agent-serve

Once the Agent server is up and running (you won’t see any output), call it by running the following command:

Terminal window
curl -N -X POST http://127.0.0.1:8081/invocations \
-d '{"genre":"superhero", "actions":[], "playerName":"UnnamedHero"}' \
-H "Content-Type: application/json"

If the command runs successfully, you should see events being streamed similar to:

data: {"init_event_loop": true}
data: {"start": true}
data: {"start_event_loop": true}
data: {"event": {"messageStart": {"role": "assistant"}}}
data: {"event": {"contentBlockDelta": {"delta": {"text": "Welcome"}, "contentBlockIndex": 0}}}
...

Congratulations. You have built and deployed your first Strands Agent on Bedrock AgentCore Runtime! 🎉🎉🎉