![[Update] Amazon Bedrock AgentCore Harness Is Now Based on the Strands Harness, with Built-in Tools and Lifecycle Hooks Added!](https://devio2024-media.developers.io/image/upload/f_auto,q_auto/c_limit,w_1200/v1790875048/eyecatch/edq4dfptctqlcwjhffhs.png)
[Update] Amazon Bedrock AgentCore Harness Is Now Based on the Strands Harness, with Built-in Tools and Lifecycle Hooks Added!
This page has been translated by machine translation. View original
Introduction
Hello, I'm Jinno from the Consulting Department, and I love supermarkets.
re:Invent is in full swing, but let me introduce an update from a little while ago...!
Amazon Bedrock AgentCore Harness (hereafter Harness) is now based on Strands harness!
Default settings, built-in tools, and lifecycle hooks have been added.
When you create a Harness, in addition to a model and system prompt, you quickly get tools for TODO management and subagents. The added convenience is nice!
It feels like the Strands harness I introduced previously has been built into AgentCore Harness.
Update Details
Strands harness is a Strands Agents mechanism that lets you create an agent equipped with a system prompt and built-in tools using create_harness(), so you can easily build a nicely working AI agent.
Default Settings
If you create a Harness without specifying a model or system prompt, AgentCore's recommended settings are applied.
| Item | Setting when omitted |
|---|---|
| Model | Claude Opus 5 (global.anthropic.claude-opus-5) |
| System prompt | Managed system prompt (instructions such as seeing work through to the end and verifying before completion) |
| Context management | Summarizes old conversation. The most recent 10 messages are kept as is |
| Tools | A recommended set of built-in tools (allowedTools is ["*"]) |
| Memory | Managed memory (AgentCore Memory) is enabled automatically |
| Prompt caching | Used automatically when calling a supported Bedrock model in converse_stream format |
By the way, these default values will apparently change as improvements are made. Items you have explicitly set remain as they are.
It's nice that defaults change to better ones in a fast-moving field, but output quality and cost can also change easily, so you need to be careful.
Lifecycle Hooks
Support for lifecycle hooks has also been added in this update.
At fixed points in the agent loop, you can send events to Lambda, SNS, and EventBridge.

| Event | When it runs | When Lambda returns deny |
|---|---|---|
before_invocation |
Before processing a request | Stops the invocation |
before_tool_call |
Before executing a tool | Skips only that tool |
after_tool_call |
After the tool result is available | Stops further reasoning |
after_invocation |
After the invocation finishes | Only recorded (output cannot be revoked) |
It's like being able to insert notification or approval processes.
Lambda can return allow or deny synchronously, but SNS and EventBridge only receive notifications and cannot stop processing.
Prerequisites
I proceeded with the following prerequisites this time.
| Item | Version / Value |
|---|---|
| AgentCore CLI | 1.2.0 |
| Python | 3.15.2 |
| boto3 | 1.44.5 |
| Region | us-east-1 |
Let's get started.
Creating a Harness with Defaults
I'll create it by specifying only the name.
agentcore harness create --region us-east-1 --json --name defaults_demo
{
"harnessId": "defaults_demo-qGedeQ2RRG",
"arn": "arn:aws:bedrock-agentcore:us-east-1:<アカウントID>:harness/defaults_demo-qGedeQ2RRG",
"model": {
"bedrockModelConfig": {
"modelId": "global.anthropic.claude-opus-5",
"apiFormat": "converse_stream"
}
},
"systemPrompt": [
{ "text": "You are an agent. Keep working until the task is fully resolved before ending your turn. ..." }
],
"allowedTools": ["*"],
"truncation": {
"strategy": "summarization",
"config": {
"summarization": { "summaryRatio": 0.30000001192092896, "preserveRecentMessages": 10 }
}
},
"memory": { "managedMemoryConfiguration": {} },
"maxIterations": 75,
"timeoutSeconds": 3600
}
The default settings are in place. The system prompt was the same as the Strands harness one whose full text I posted in the previous article!
It took about 4 minutes from creation until it became READY.
Managed system prompt (full text)
You are an agent. Keep working until the task is fully resolved before ending your turn. Only stop to ask the user when you are blocked on a decision or information that is genuinely theirs to provide.
# Acting
- Once you have enough to act on, act. Do not ask for confirmation of steps you can verify yourself, and do not re-derive facts you have already established.
- Explore before you change anything: understand the surrounding context and conventions, then make changes that fit them.
- Treat a task as done only when you have verified it, not when it looks plausible. If you cannot verify, say so.
# Tools
- Prefer the dedicated tool for a job over improvising with a general one.
- Independent tool calls can be issued together in a single turn; run them in parallel rather than serially.
- A denied or failed tool call is information: adjust your approach, do not retry it verbatim.
- `<system-reminder>` tags in messages and tool results are injected by the harness, not the user.
# Safety
- For actions that are hard to reverse or that reach outside the local environment, confirm first unless you have been explicitly told to proceed. Approval in one context does not carry to the next.
- Report outcomes faithfully: if something fails, say so with the output; if you skipped a step, say that; when something is done and verified, state it plainly without hedging.
# Context management
When the conversation grows long, older turns may be summarized and large tool results moved out of the immediate context, with a way to retrieve them. Work as if the full history remains available; you do not need to wrap up early or hand off mid-task.
Checking the Built-in Tools
For invocation I used boto3's invoke_harness!
I set the arn from the creation result in the environment variable HARNESS_ARN and ran it.
When using subagents, there can be a gap of several minutes before the next response, so I set read_timeout to 900 seconds.
invoke.py
import argparse
import json
import os
import uuid
import boto3
from botocore.config import Config
parser = argparse.ArgumentParser()
parser.add_argument("prompt")
parser.add_argument("--session", default=str(uuid.uuid4()))
parser.add_argument("--allowed-tools", nargs="+")
parser.add_argument("--actor")
args = parser.parse_args()
client = boto3.client(
"bedrock-agentcore", region_name="us-east-1", config=Config(read_timeout=900)
)
params = {
"harnessArn": os.environ["HARNESS_ARN"],
"runtimeSessionId": args.session,
"messages": [{"role": "user", "content": [{"text": args.prompt}]}],
}
if args.actor:
params["actorId"] = args.actor
if args.allowed_tools:
params["allowedTools"] = args.allowed_tools
res = client.invoke_harness(**params)
text, tool_input = "", ""
with open("last_events.jsonl", "w") as log:
for event in res["stream"]:
log.write(json.dumps(event, ensure_ascii=False, default=str) + "\n")
if "contentBlockStart" in event:
start = event["contentBlockStart"].get("start", {})
if "toolUse" in start:
print(f"[tool] {start['toolUse']['name']}", end=" ")
tool_input = ""
elif "contentBlockDelta" in event:
delta = event["contentBlockDelta"]["delta"]
text += delta.get("text", "")
tool_input += delta.get("toolUse", {}).get("input", "")
elif "contentBlockStop" in event and tool_input:
print(tool_input[:150])
tool_input = ""
elif "hookEvent" in event:
print("[hook]", json.dumps(event["hookEvent"], ensure_ascii=False))
elif "messageStop" in event:
print("[stop]", event["messageStop"]["stopReason"])
elif "metadata" in event:
print("[usage]", json.dumps(event["metadata"].get("usage", {})))
print("---")
print(text.strip())
print("session:", args.session)
When I passed a question to invoke.py and asked it to list the tools it can use, there were 8.
[stop] end_turn
[usage] {"inputTokens": 2, "outputTokens": 33, "totalTokens": 3410, "cacheReadInputTokens": 0, "cacheWriteInputTokens": 3375}
---
shell
read
write
edit
web_fetch
subagent
retrieve_context
todo_write
The roles of each are summarized below.
| Tool | Role |
|---|---|
shell |
Executing shell commands |
read, write, edit |
Reading, creating, and editing files |
web_fetch |
Fetching a page at a specified URL |
subagent |
Launching subagents and delegating work |
retrieve_context |
Retrieving the full text of long results omitted in a preview |
todo_write |
Recording and updating TODOs |
Let's actually use these tools.
Running the Built-in Tools Together
I asked it to read the AgentCore and Strands harness documentation and compare them in a table, with explicit instructions to use TODOs and subagents.
In a single request, the built-in tools work together as follows.

Looking at an excerpt of the tool calls in the execution log,
you can see it proceeds autonomously through planning, parallel research, full-text retrieval, file creation, and verification and fixing!
[tool] todo_write {"todos": [{"content":"Delegate reading/summarizing the AgentCore Harness tools page to a subagent", ...}]}
[tool] subagent {"agent_type": "generalist", "context": "none", "instructions": "..."}
[tool] subagent {"agent_type": "generalist", "context": "none", "instructions": "..."}
[tool] todo_write {...}
[tool] retrieve_context {"reference": "tooluse_DRaSVSvLSV9SfCalDNV673_0"}
[tool] retrieve_context {"reference": "tooluse_AjJetuz9vR85C9qqOwXok0_0"}
[tool] subagent {"agent_type": "generalist", "context": "none", "instructions": "..."}
[tool] subagent {"agent_type": "generalist", "context": "none", "instructions": "..."}
[tool] subagent {"agent_type": "generalist", "context": "none", "instructions": "..."}
[tool] write {"path": "/home/compare.md", "content": "# AgentCore Harness と Strands harness の組み込みツール比較\n..."}
[tool] shell {"command": "cd /home && awk ..."}
[tool] read {"path": "/home/compare.md", "offset": 25, "limit": 25}
[tool] edit {"path": "/home/compare.md", "old_str": "..."}
[tool] todo_write {...}
This looks useful for heavy tasks!
Checking Token Counts with Prompt Caching and allowedTools
When I passed the session ID at the end of the output to --session and asked a follow-up question, the 3,375 tokens written to the cache on the first call were read as is on the second. You can check this in the cacheReadInputTokens field.
It's nice that it's used as a cache without any configuration!
[usage] {"inputTokens": 2, "outputTokens": 319, "totalTokens": 3758, "cacheReadInputTokens": 3375, "cacheWriteInputTokens": 62}
allowedTools (the list of tools allowed for use) can also be overridden per invocation.
When I limited it to only reading and URL fetching and asked it to create a file, it explained that it had no means of writing and stopped the work.
uv run invoke.py "hello.txt というファイルに「こんにちは」と書いて保存してください。" --allowed-tools read web_fetch
[usage] {"inputTokens": 2, "outputTokens": 633, "totalTokens": 1934, "cacheReadInputTokens": 0, "cacheWriteInputTokens": 1299}
---
申し訳ありません、そのファイル作成は実行できません。
現在私が使えるツールはファイルの**読み取り**(`read`)と**URL取得**(`web_fetch`)のみで、ファイルへの書き込み・作成を行う手段がありません。そのため `hello.txt` を保存することができませんでした(できていないので「完了」とは言えません)。
The cache write also dropped from 3,375 tokens with all tools to 1,299. The recommended set of tools apparently adds about 3,000 tokens per request, so I'd like to explicitly remove unnecessary tools and operations I don't want to allow.
Trying Lifecycle Hooks
There may be cases where you want controls like "I want to stop it before it reaches the model if I accidentally include an AWS access key in the request" or "I want to prevent it from fetching URLs other than the permitted official sites with web_fetch." Even if you write such rules in the system prompt, the model won't necessarily always follow them, so I'll try lifecycle hooks to reliably stop things from the code side!
So this time, I'll try the following scenarios together with the four hooks.
- If the request contains a string that looks like a 20-character access key ID starting with AKIA, block it before the model call with the before_invocation Lambda
- To prevent access to unintended external sites, stop web_fetch to anything other than allowed domains (and subdomains) with the before_tool_call Lambda
- To notify of execution, use SNS for after_tool_call and EventBridge for after_invocation
- I'm using both just to verify that integration works; there's no intention behind choosing one over the other
The two synchronous decisions are combined into a single Lambda function, and the SNS and EventBridge notifications are aggregated into a single SQS queue so they're easy to check.

import json
import re
from urllib.parse import urlparse
ALLOWED_DOMAINS = ("aws.amazon.com", "docs.aws.amazon.com", "strandsagents.com")
ACCESS_KEY = re.compile(r"AKIA[0-9A-Z]{16}")
def lambda_handler(event, _context):
print(json.dumps({"event": event["event"], "toolName": event["context"].get("toolName")}))
ctx = event["context"]
# If the request contains a string that looks like an access key, stop it before the agent runs
if event["event"] == "before_invocation":
if ctx.get("truncated"):
return {"decision": "deny", "reason": "依頼文の全文を確認できませんでした"}
for message in ctx.get("messages", []):
for block in message.get("content", []):
if ACCESS_KEY.search(block.get("text", "")):
return {"decision": "deny", "reason": "依頼文にアクセスキーらしき文字列が含まれています"}
# Only allow web_fetch to fetch permitted domains
if event["event"] == "before_tool_call" and ctx["toolName"] == "web_fetch":
host = urlparse(ctx["toolInput"].get("url", "")).hostname or ""
if not any(host == d or host.endswith("." + d) for d in ALLOWED_DOMAINS):
return {"decision": "deny", "reason": f"{host} は取得を許可していないドメインです"}
return {"decision": "allow"}
The destinations are invoked with the Harness execution role.
Place setup_hooks.sh in the same working directory as the hook_lambda directory, run it, and note the output QUEUE_URL.
Next, replace <アカウントID> in hook_targets_policy.json with your own AWS account ID, then add permissions to the role created by the CLI.
Creating resources and permissions for hooks
#!/bin/bash
set -euo pipefail
REGION=us-east-1
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
# Lambda (for decisions)
aws iam create-role --role-name harness-hook-lambda-role \
--assume-role-policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}' >/dev/null
aws iam attach-role-policy --role-name harness-hook-lambda-role \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
sleep 10
(cd hook_lambda && zip -q ../hook_lambda.zip lambda_function.py)
aws lambda create-function --region $REGION --function-name harness-hook-policy \
--runtime python3.13 --handler lambda_function.lambda_handler \
--role arn:aws:iam::$ACCOUNT_ID:role/harness-hook-lambda-role \
--zip-file fileb://hook_lambda.zip --timeout 10 >/dev/null
# SQS queue for confirming receipt of notifications
QUEUE_URL=$(aws sqs create-queue --region $REGION --queue-name harness-hook-events --query QueueUrl --output text)
QUEUE_ARN=arn:aws:sqs:$REGION:$ACCOUNT_ID:harness-hook-events
# SNS (notification after tool execution)
TOPIC_ARN=$(aws sns create-topic --region $REGION --name harness-tool-events --query TopicArn --output text)
aws sns subscribe --region $REGION --topic-arn $TOPIC_ARN --protocol sqs \
--notification-endpoint $QUEUE_ARN --attributes RawMessageDelivery=true >/dev/null
# EventBridge (notification of invocation completion)
aws events create-event-bus --region $REGION --name harness-events >/dev/null
aws events put-rule --region $REGION --event-bus-name harness-events --name harness-hook-to-sqs \
--event-pattern '{"source":["bedrock-agentcore.harness"]}' >/dev/null
aws events put-targets --region $REGION --event-bus-name harness-events --rule harness-hook-to-sqs \
--targets "Id=sqs,Arn=$QUEUE_ARN" >/dev/null
# Allow SNS and EventBridge to send to the queue
cat > queue_policy.json <<JSON
{"Policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"sns.amazonaws.com\"},\"Action\":\"sqs:SendMessage\",\"Resource\":\"$QUEUE_ARN\",\"Condition\":{\"ArnEquals\":{\"aws:SourceArn\":\"$TOPIC_ARN\"}}},{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"events.amazonaws.com\"},\"Action\":\"sqs:SendMessage\",\"Resource\":\"$QUEUE_ARN\",\"Condition\":{\"ArnEquals\":{\"aws:SourceArn\":\"arn:aws:events:$REGION:$ACCOUNT_ID:rule/harness-events/harness-hook-to-sqs\"}}}]}"}
JSON
aws sqs set-queue-attributes --region $REGION --queue-url $QUEUE_URL --attributes file://queue_policy.json
echo "QUEUE_URL=$QUEUE_URL"
echo "TOPIC_ARN=$TOPIC_ARN"
{
"Version": "2012-10-17",
"Statement": [
{"Effect": "Allow", "Action": "lambda:InvokeFunction", "Resource": "arn:aws:lambda:us-east-1:<アカウントID>:function:harness-hook-policy"},
{"Effect": "Allow", "Action": "sns:Publish", "Resource": "arn:aws:sns:us-east-1:<アカウントID>:harness-tool-events"},
{"Effect": "Allow", "Action": "events:PutEvents", "Resource": "arn:aws:events:us-east-1:<アカウントID>:event-bus/harness-events"}
]
}
aws iam put-role-policy --role-name AgentCoreHarness-defaults_demo \
--policy-name hook-targets --policy-document file://hook_targets_policy.json
Next, I define the mapping between the four hooks and their destinations in hooks.json.
For hooks that call Lambda, you can specify the maximum number of seconds to wait for a response (timeoutSeconds) and the decision to apply when a timeout or error occurs (failureMode).
If failureMode is omitted, it defaults to deny, so processing is stopped even if a failure occurs on the Lambda side.
hooks.json
[
{
"beforeInvocation": {
"name": "block_secrets",
"target": {"lambda": {"arn": "arn:aws:lambda:us-east-1:<アカウントID>:function:harness-hook-policy", "timeoutSeconds": 10, "failureMode": "deny"}}
}
},
{
"beforeToolCall": {
"name": "fetch_allowlist",
"target": {"lambda": {"arn": "arn:aws:lambda:us-east-1:<アカウントID>:function:harness-hook-policy", "timeoutSeconds": 10, "failureMode": "deny"}}
}
},
{
"afterToolCall": {
"name": "notify_tool_result",
"target": {"sns": {"arn": "arn:aws:sns:us-east-1:<アカウントID>:harness-tool-events"}}
}
},
{
"afterInvocation": {
"name": "notify_invocation",
"target": {"eventBridge": {"arn": "arn:aws:events:us-east-1:<アカウントID>:event-bus/harness-events"}}
}
}
]
This time I configured the four hooks with the AWS CLI's update-harness.
Replace <アカウントID> in hooks.json with your own AWS account ID, and specify the harnessId shown in the initial creation result for --harness-id.
aws bedrock-agentcore-control update-harness --region us-east-1 \
--harness-id <harnessId> --hooks file://hooks.json
Blocking a Request Containing an Access Key
I included the sample access key from the AWS documentation (AKIAIOSFODNN7EXAMPLE) and asked it to find out which IAM user it belongs to.
[hook] {"hookEventId": "6f1c6360-...", "name": "block_secrets", "type": "before_invocation", "decision": "deny", "reason": "依頼文にアクセスキーらしき文字列が含まれています"}
[stop] hook_stopped
[hook] {"hookEventId": "3fedaeaf-...", "name": "notify_invocation", "type": "after_invocation"}
---
before_invocation returned deny and it ended with hook_stopped. There is no usage line, and the model was never called.
We were able to block as intended using the lifecycle!
You check the notification SQS queue with the queue URL output by setup_hooks.sh. Since both notifications flow into the same queue, if the JSON's event is after_tool_call it came via SNS, and if detail.event is after_invocation it came via EventBridge.
aws sqs receive-message --region us-east-1 --queue-url '<キューURL>' \
--wait-time-seconds 20 --max-number-of-messages 10 \
| jq -r '.Messages[]?.Body | fromjson'
In the after_invocation notification from EventBridge, the token counts were also 0, so you can see no inference took place.
{
"detail-type": "Harness Lifecycle Hook",
"source": "bedrock-agentcore.harness",
"detail": {
"name": "notify_invocation",
"event": "after_invocation",
"sessionId": "c8894322-491d-447d-a19e-9e6efd68712a",
"context": {
"stopReason": "hook_stopped",
"usage": { "inputTokens": 0, "outputTokens": 0, "totalTokens": 0 }
}
}
}
Restricting Fetchable Domains
I'll have it fetch one page from a non-allowed domain and one from an allowed domain.
uv run invoke.py "次の2つのページをweb_fetchで取得して、それぞれのタイトルを教えてください。
- https://example.com/
- https://aws.amazon.com/jp/about-aws/whats-new/" --actor hooks-demo
[hook] {"name": "block_secrets", "type": "before_invocation", "decision": "allow"}
[tool] web_fetch {"url": "https://example.com/"}
[tool] web_fetch {"url": "https://aws.amazon.com/jp/about-aws/whats-new/"}
[stop] tool_use
[hook] {"name": "fetch_allowlist", "type": "before_tool_call", "decision": "deny", "reason": "example.com は取得を許可していないドメインです"}
[hook] {"name": "notify_tool_result", "type": "after_tool_call"}
[hook] {"name": "fetch_allowlist", "type": "before_tool_call", "decision": "allow"}
[hook] {"name": "notify_tool_result", "type": "after_tool_call"}
[stop] tool_result
[stop] end_turn
[hook] {"name": "notify_invocation", "type": "after_invocation"}
---
結果は1件成功、1件失敗でした。
...
- エラー: `example.com は取得を許可していないドメインです`
Only example.com was skipped, and the agent went on to fetch the AWS page.
This also worked as intended!
After the tool execution, the result of the rejected web_fetch arrived at SNS as an error.
{
"name": "notify_tool_result",
"event": "after_tool_call",
"sessionId": "e720a8f4-34bc-4df3-bd21-a12067bf383a",
"context": {
"toolName": "web_fetch",
"toolType": "builtin",
"toolResult": {
"status": "error",
"content": [
{ "text": "example.com は取得を許可していないドメインです" }
]
}
}
}
Checking Whether Hooks Apply to Subagents
I was curious whether they apply to subagents too, so I tried it!
I had it look up the title of example.com, and organized the execution order by cross-referencing the events the Lambda received during testing with the invocation results (the Lambda used for publication only outputs event names and tool names so as not to leave the request text in the logs).
before_tool_call subagent {"tools": ["web_fetch"], "task": "Fetch the URL https://example.com/ ..."} → allow
before_tool_call web_fetch {"url": "https://example.com/"} → deny(サブエージェントの呼び出し)
before_tool_call web_fetch {"url": "https://example.com/"} → deny(親が自分で試した呼び出し)
Even inside the subagent, web_fetch to example.com was blocked just as when called from the parent! It's reassuring that web_fetch can be stopped under the same conditions even via a subagent.
Cleanup
A Harness can be deleted by specifying the harnessId from the creation result, and the managed memory is deleted along with it. The execution role created by the CLI and the hook resources (EventBridge, SNS, SQS, Lambda, IAM role) remain, so it's convenient to have a script that deletes them all at once.
Deletion script (cleanup.sh)
#!/bin/bash
# Usage: bash cleanup.sh <harnessId>
set -uo pipefail
REGION=us-east-1
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
HARNESS_ID=${1:?harnessIdを指定してください}
ROLE_NAME=AgentCoreHarness-${HARNESS_ID%-*}
agentcore harness delete --region $REGION --id "$HARNESS_ID"
aws events remove-targets --region $REGION --event-bus-name harness-events --rule harness-hook-to-sqs --ids sqs
aws events delete-rule --region $REGION --event-bus-name harness-events --name harness-hook-to-sqs
aws events delete-event-bus --region $REGION --name harness-events
aws sns delete-topic --region $REGION --topic-arn arn:aws:sns:$REGION:$ACCOUNT_ID:harness-tool-events
aws sqs delete-queue --region $REGION --queue-url https://sqs.$REGION.amazonaws.com/$ACCOUNT_ID/harness-hook-events
aws lambda delete-function --region $REGION --function-name harness-hook-policy
for p in $(aws iam list-role-policies --role-name "$ROLE_NAME" --query 'PolicyNames[]' --output text); do
aws iam delete-role-policy --role-name "$ROLE_NAME" --policy-name "$p"
done
aws iam delete-role --role-name "$ROLE_NAME"
aws iam detach-role-policy --role-name harness-hook-lambda-role \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
aws iam delete-role --role-name harness-hook-lambda-role
Conclusion
AgentCore Harness is easy to create, so I'm grateful that it has become this convenient! I'd like to keep exploring AI agents that can quickly become useful.
I hope this article was of some help. Thank you for reading to the end!