Deploying Claude Agent SDK on Bedrock AgentCore Runtime
A hands-on walkthrough for deploying a Python agent built with Anthropic's Claude Agent SDK to Amazon Bedrock AgentCore Runtime, using the new AgentCore CLI. It progresses in three stages — a stateless one-shot agent, conversational context held within a runtime session, then streamed output — and covers the traps along the way, from tool permissions to why a CodeZip package won't work.
Deploying the Claude Agent SDK on Amazon Bedrock AgentCore Runtime
This walkthrough deploys a Python agent built with the Claude Agent SDK to Amazon Bedrock AgentCore Runtime. You will first deploy a one-shot agent, then keep conversation context within a runtime session, and finally stream response deltas to the caller.
The deployment uses a container because a CodeZip package drops the executable bit on the
claude binary the Python SDK bundles, so the agent can't launch it. The walkthrough assumes familiarity with Python, Docker, AWS credentials, and basic IAM policy editing.We'll build up in stages: start with the simplest possible agent that handles one-shot tasks, see for ourselves that each invocation is a completely independent session, then keep conversational context within a session, and finally add streaming output.
Overview
Amazon Bedrock AgentCore Runtime is a serverless runtime purpose-built for hosting AI agents. It handles session isolation, durable sessions (up to 8 hrs), scaling, identity, memory, and observability, and it invokes your agent over a simple HTTP contract (
POST /invocations , GET /ping ). You bring the agent logic; AgentCore runs it.The Claude Agent SDK (formerly the Claude Code SDK) gives you Anthropic's agent loop — tool use, subagents, MCP, permissions, hooks — as a library you can embed in your own service. Pointed at Amazon Bedrock, inference at runtime stays inside your AWS account, against Claude models you've enabled.
This guide packages a Claude Agent SDK agent and deploys it to AgentCore Runtime using the new AgentCore CLI. As explained under Architecture , we use a Container build so the bundled
claude binary stays executable.Architecture

One implementation detail shapes everything downstream: the Python
claude-agent-sdk drives Anthropic's claude agent binary under the hood. The SDK ships that binary inside the wheel, so you don't have to install it — but a CodeZip package unpacks it to /var/task without the executable bit, and the agent fails at the first request with [Errno 13] Permission denied: '/var/task/claude_agent_sdk/_bundled/claude' . A Container build keeps the file mode intact, so throughout this guide we use a container.Prerequisites
- An AWS account with credentials configured (
aws sts get-caller-identityshould succeed).
- Node.js 20+ — the AgentCore CLI is an npm package.
- Python 3.10+ — the agent code is Python.
- AWS CDK installed and bootstrapped (
cdk bootstrap) — the CLI deploys via CDK/CloudFormation.
- Docker — required for the Container build.
- Bedrock model access to an Anthropic Claude model (e.g. Claude Sonnet) in your target Region. Enable it in the Bedrock console → Model access.
Step 1: Install the AgentCore CLI
npm install -g @aws/agentcoreagentcore --help
You should see the top-level commands:
create , dev , deploy , invoke , logs , status , add , remove , validate , and more.Step 2: Scaffold the project with the AgentCore CLI
The CLI ships first-class templates for Strands, LangChain/LangGraph, Google ADK, and OpenAI Agents. The Claude Agent SDK isn't a built-in framework, so we scaffold a Container project and replace the generated agent code with our own. Scaffolding still gives us the
agentcore.json config, AWS targets, IAM role wiring, and CDK deployment plumbing.agentcore create \ --name ClaudeAgent \ --framework Strands \ --protocol HTTP \ --model-provider Bedrock \ --memory none \ --build Container
cd ClaudeAgent
This generates (simplified):
ClaudeAgent/ agentcore/ agentcore.json # Project + agent configuration aws-targets.json # Account/Region targets .env.local # Local env vars (gitignored) app/ ClaudeAgent/ Dockerfile # Container image ← generated, no edits needed main.py # Agent entrypoint ← we replace this pyproject.toml # Python deps ← we edit this README.md
Step 3: Write a one-shot agent entrypoint
Start with the simplest thing that works: an entrypoint that runs a single, self-contained task per request. Replace
app/ClaudeAgent/main.py with an entrypoint that implements the AgentCore HTTP contract via the bedrock-agentcore runtime harness and calls the Claude Agent SDK 's query() function:# app/ClaudeAgent/main.pyimport osfrom bedrock_agentcore.runtime import BedrockAgentCoreAppfrom claude_agent_sdk import ( AssistantMessage, ClaudeAgentOptions, ResultMessage, TextBlock, query,)
app = BedrockAgentCoreApp()
# Route the Claude Agent SDK at Amazon Bedrock.os.environ.setdefault("CLAUDE_CODE_USE_BEDROCK", "1")os.environ.setdefault("CLAUDE_CODE_ENABLE_TELEMETRY", "1")os.environ.setdefault("CLAUDE_CODE_ENHANCED_TELEMETRY_BETA", "1")# Keep auto-updates, error reporting and feature-flag fetching off the wire.os.environ.setdefault("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "1")os.environ.setdefault("AWS_REGION", os.environ.get("AWS_REGION", "us-west-2"))
# Bedrock model (cross-Region inference profile ID). Verify current availability# in your Region before shipping.BEDROCK_MODEL = os.environ.get("ANTHROPIC_MODEL", "global.anthropic.claude-sonnet-5")options = ClaudeAgentOptions( model=BEDROCK_MODEL, # v0.1+ ships a minimal system prompt by default — set yours explicitly. system_prompt="You are a concise, helpful AWS solutions assistant.", allowed_tools=["Read", "Glob", "Grep"], setting_sources=["project"], # "dontAsk" denies any tool not listed above, rather than prompting for it. permission_mode="dontAsk",)
@app.entrypointasync def invoke(payload: dict) -> dict: """AgentCore calls this per request. Each call is a fresh, stateless query.""" prompt = payload.get("prompt", "")
text_parts: list[str] = [] cost = 0.0 async for message in query(prompt=prompt, options=options): if isinstance(message, AssistantMessage): for block in message.content: if isinstance(block, TextBlock): text_parts.append(block.text) elif isinstance(message, ResultMessage) and message.total_cost_usd: cost = message.total_cost_usd
return {"result": "".join(text_parts), "cost_usd": cost}
if __name__ == "__main__": app.run() # Serves the AgentCore HTTP contract on :8080
query() opens a fresh, stateless conversation for each call and yields typed messages, not strings: read text from the content blocks of each AssistantMessage , and use the terminal ResultMessage for metadata like cost. This is the right shape for one-shot tasks — classification, extraction, single-shot generation — where each request stands on its own. We'll see the "stateless" part first-hand in Step 6 , and add memory in Step 7 .One note on the tool options, since they don't mean quite what they look like:
allowed_tools auto-approves the tools it lists rather than restricting Claude to them, and permission_mode="dontAsk" denies anything unapproved instead of waiting for a confirmation prompt that a container has no way to show. Both are Claude Agent SDK behaviors, independent of AgentCore — read Configure permissions before widening this list to Edit or Bash .Declare Python dependencies
Update the
app/ClaudeAgent/pyproject.toml to add Claude Agent SDK and remove the unnecessary modules which are leftovers from the Strands scaffolding.[build-system]requires = ["hatchling"]build-backend = "hatchling.build"
[project]name = "ClaudeAgent"version = "0.1.0"description = "AgentCore Runtime Application using Claude Agent SDK"readme = "README.md"requires-python = ">=3.10"dependencies = [ "aws-opentelemetry-distro", "bedrock-agentcore >= 1.9.1", "claude-agent-sdk>=0.2.143",]
[tool.hatch.build.targets.wheel]packages = ["."]
Then install it, so
agentcore dev can import the SDK and the lockfile stays in step with pyproject.toml :cd app/ClaudeAgentuv sync
Configure behavior with CLAUDE.md , skills, subagents, and MCP servers
Because the SDK drives the
claude CLI under the hood, it can read the same project configuration files the CLI uses — starting with a CLAUDE.md in your agent directory. CLAUDE.md is always-on instructions the agent sees on every turn. Drop one next to main.py :app/ClaudeAgent/ main.py pyproject.toml CLAUDE.md # always-on project instructions / memory .claude/ settings.json # permissions, allowed tools, env, default model agents/ # subagent definitions skills/ # skills that extend what the agent can do commands/ # custom slash commands .mcp.json # MCP server definitions (external tools / data)
A minimal
CLAUDE.md :bash -c "cat <<EOF > CLAUDE.md# Project: AWS Solutions Assistant
- Answer concisely and name the AWS service you're recommending.- Prefer serverless, Well-Architected patterns.- Never invent API names — say so if you're unsure.EOF"
The
setting_sources=["project"] in the options above is what loads them — CLAUDE.md , .claude/ (skills, subagents, slash commands, permissions) and .mcp.json (MCP servers) — from the agent directory through the CLI, while ignoring your own user-level ~/.claude config, which the container won't have. Use setting_sources=[] to isolate the agent from on-disk configuration entirely. See the Claude Agent SDK documentation for details.These files get copied into the image by the template Dockerfile.
Step 4: Test locally
The CLI runs a local server that mimics the AgentCore Runtime environment, with hot reload:
agentcore dev
If you are still in the app folder, run
cd ../.. first. It will open a browser window where you can interact with the agent. Once up, try:Summarize what AgentCore Runtime does in one sentence
Let's also prove the SDK is reading
CLAUDE.md . Add a distinctive instruction — for example, Always begin every reply with "AWS SA:" — run agentcore dev , and send any prompt. If the AWS SA: prefix appears, the SDK picked up CLAUDE.md through the CLI.Step 5: Deploy to AgentCore Runtime
# Optional: preview without changing anythingagentcore deploy --dry-run
# Deploy (build image, push, provision via CDK/CloudFormation)agentcore deploy
agentcore deploy reads agentcore.json + aws-targets.json , builds the container, and creates the IAM role, the AgentCore Runtime, and supporting resources.The agent's execution role needs
bedrock:InvokeModel (and bedrock:InvokeModelWithResponseStream for streaming) on the Claude model or inference-profile ARNs it will call. The role the CLI provisions already grants it, and you can scope it down to only specific models.Step 6: Invoke, and see independent sessions
Invoke the deployed agent twice — first ask something, then ask it to recall what you just asked:
agentcore invoke "Tell me about AgentCore in 1 sentence"
agentcore invoke "What did I ask you?"
The second reply won't know what you asked. There are two reasons, and they compound:
- The code is stateless. Our entrypoint calls
query(), which opens a brand-new conversation on every invocation. Nothing from the previous call is carried forward.
- No session was specified (when invoking from the CLI). Because we didn't pass a
--session-id, AgentCore generates a new session id for every invocation and launches a fresh microVM.
In other words, each invocation is an independent session with completely new context. That's exactly what you want for one-shot tasks — but not for a chat. Passing a
--session-id alone won't fix it either, because query() still starts a new conversation each time:# Session IDs must be at least 33 characters — a UUID satisfies that.SESSION_ID=$(uuidgen)
agentcore invoke --session-id "$SESSION_ID" "Tell me about AgentCore in 1 sentence"agentcore invoke --session-id "$SESSION_ID" "What did I ask you?"
You can also invoke programmatically with boto3 via
InvokeAgentRuntime . Get the runtime ARN with agentcore status :import json, uuid, boto3
agent_arn = "REPLACE_WITH_AGENT_ARN" # from `agentcore status`client = boto3.client("bedrock-agentcore")sessionId = str(uuid.uuid4())response = client.invoke_agent_runtime( agentRuntimeArn=agent_arn, payload=json.dumps({"prompt": "Tell me a joke"}).encode(), runtimeSessionId=sessionId, qualifier="DEFAULT",)print(json.loads(b"".join(response.get("response", [])).decode()))
Step 7: Keep conversational context within a runtime session
To hold a conversation, swap
query() for a long-lived ClaudeSDKClient . You create it once at module scope, connect on the first request, and reuse it — so the conversation history accumulates across invocations. Update main.py :# app/ClaudeAgent/main.pyimport osfrom bedrock_agentcore.runtime import BedrockAgentCoreAppfrom claude_agent_sdk import ( AssistantMessage, ClaudeAgentOptions, ResultMessage, TextBlock, ClaudeSDKClient, # <-- add)
app = BedrockAgentCoreApp()
os.environ.setdefault("CLAUDE_CODE_USE_BEDROCK", "1")os.environ.setdefault("CLAUDE_CODE_ENABLE_TELEMETRY", "1")os.environ.setdefault("CLAUDE_CODE_ENHANCED_TELEMETRY_BETA", "1")os.environ.setdefault("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "1")os.environ.setdefault("AWS_REGION", os.environ.get("AWS_REGION", "us-west-2"))
BEDROCK_MODEL = os.environ.get("ANTHROPIC_MODEL", "global.anthropic.claude-sonnet-5")options = ClaudeAgentOptions( model=BEDROCK_MODEL, system_prompt="You are a concise, helpful AWS solutions assistant.", allowed_tools=["Read", "Glob", "Grep"], setting_sources=["project"], permission_mode="dontAsk",)
# One long-lived client, reused across invocations of this instance.claude = ClaudeSDKClient(options=options)_connected = False
@app.entrypointasync def invoke(payload: dict) -> dict: """Stateful: reuse one connected client so context persists across calls.""" global _connected if not _connected: await claude.connect() _connected = True
prompt = payload.get("prompt", "")
text_parts: list[str] = [] cost = 0.0 await claude.query(prompt=prompt) async for message in claude.receive_response(): if isinstance(message, AssistantMessage): for block in message.content: if isinstance(block, TextBlock): text_parts.append(block.text) elif isinstance(message, ResultMessage) and message.total_cost_usd: cost = message.total_cost_usd
return {"result": "".join(text_parts), "cost_usd": cost}
if __name__ == "__main__": app.run()
Now the two pieces work together. The module-level client keeps the conversation in memory, and a stable
--session-id tells AgentCore to route your calls to the same warm microVM — the one holding that client. Redeploy, then invoke with a session:agentcore deploy
SESSION_ID=$(uuidgen)
agentcore invoke --session-id "$SESSION_ID" "Tell me about AgentCore in 1 sentence"agentcore invoke --session-id "$SESSION_ID" "What did I ask you?"
This time the second reply remembers the first. And because AgentCore gives each session its own isolated microVM, this module-level client is scoped to a single session — concurrent callers with different session ids land on separate microVMs, so there's no cross-session context leakage. The warm client also keeps latency low within a session. (If a caller starts a new
--session-id , they get a fresh conversation, exactly as you'd expect.)Sessions can last up to 8 hrs and have a configurable idle timeout, which defaults to 15 min. If the session does not receive a new invocation in this time, the microVM is recycled.
Step 8: Stream the output event by event
So far the entrypoint collects the full response before returning it. To stream text as it's generated, you need three small changes to the code you already have.
- Add
StreamEventto your imports:
from claude_agent_sdk.types import StreamEvent
- Turn on partial messages in the
optionsyou already defined — everything else stays the same:
options = ClaudeAgentOptions( model=BEDROCK_MODEL, system_prompt="You are a concise, helpful AWS solutions assistant.", allowed_tools=["Read", "Glob", "Grep"], setting_sources=["project"], permission_mode="dontAsk", include_partial_messages=True, # <-- add this line)
- Make the entrypoint an async generator that
yields each text delta instead of collecting them.BedrockAgentCoreAppstreams the yielded chunks to the caller. Using the statefulClaudeSDKClientfrom Step 7:
@app.entrypointasync def invoke(payload: dict): global _connected if not _connected: await claude.connect() _connected = True
prompt = payload.get("prompt", "") await claude.query(prompt=prompt) async for message in claude.receive_response(): if isinstance(message, StreamEvent): event = message.event if event.get("type") == "content_block_delta": delta = event.get("delta", {}) if delta.get("type") == "text_delta": yield {"type": "text", "text": delta.get("text", "")}
Test it in the local dev console or invoke it from the command line with streaming enabled:
agentcore invoke "Explain AgentCore Runtime" --stream
If you're still on the one-shot design from Step 3, the change is the same — just swap the loop back to
query(prompt=prompt, options=options) and watch for StreamEvent the same way; each call remains stateless.Step 9: Observe
You can see the local traces directly in the development UI. For cloud deployed resources enable AgentCore Observability (CloudWatch Transaction Search) once, then:
agentcore status # live view of deployed resources + ARNsagentcore logs # stream runtime logsagentcore traces list # recent traces
Runtime logs also land in CloudWatch under
/aws/bedrock-agentcore/runtimes/{agent-id}-DEFAULT .Step 10: Clean up
To remove all resources from the AWS account, run:
agentcore remove all # reset local config, mark resources for teardownagentcore deploy # apply the teardown in AWS
This will not remove existing logs and traces.
What I learned
This was a fun and interesting exercise that allowed me to better understand the way AgentCore runtime works, and in particular:
- Single one-shot tasks can be implemented really easily and leverage the full power of Claude Code
- The stateful nature of the runtime allows me to create an agent and continue interacting with it.
- If you are generating large artefacts, like code, you can persist the results to a git repo (on Github or S3 - via git-remote-s3), just add the required tools to the container - I will cover this in another blog post.
Resources
- AgentCore CLI repo (
aws/agentcore-cli) — seedocs/commands.md,docs/frameworks.md,docs/container-builds.md
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article