[アップデート] Amazon Bedrock AgentCore HarnessがStrands harnessベースになり、組み込みツールとライフサイクルフックが追加されました!

[アップデート] Amazon Bedrock AgentCore HarnessがStrands harnessベースになり、組み込みツールとライフサイクルフックが追加されました!

Amazon Bedrock AgentCore HarnessがStrands harnessベースになり便利になりました!嬉しいですね!
2026.12.01

はじめに

こんにちは、スーパーマーケットが大好きなコンサル部の神野です。

絶賛re:Invent中ですが少し前のアップデートを紹介させてください・・・!
Amazon Bedrock AgentCore Harness(以下Harness)がStrands harnessベースになりました!
デフォルト設定・組み込みツール・ライフサイクルフックが追加されています。

https://aws.amazon.com/jp/blogs/machine-learning/amazon-bedrock-agentcore-harness-adds-strands-harness-defaults-built-in-tools-and-lifecycle-hooks/

Harnessを作ると、サクッとモデルとシステムプロンプトに加えてTODO管理やサブエージェントのツールまで提供されます。手軽さが増えるのはいいですね!

以前紹介したStrands harnessがAgentCore Harnessに組み込まれた感じですね。

https://dev.classmethod.jp/articles/strands-harness-vs-agent/

アップデートの内容

Strands harnessはシステムプロンプトや組み込みツールがそろったエージェントをcreate_harness()で作れるStrands Agentsの仕組みで、手軽に良い感じのAIエージェントを作れます。

デフォルトの設定

モデルやシステムプロンプトを省略してHarnessを作るとAgentCoreのおすすめ設定が入ります。

項目 省略したときの設定
モデル Claude Opus 5(global.anthropic.claude-opus-5)
システムプロンプト マネージドのシステムプロンプト(作業を最後までやり切る・完了の前に確認するなどの指示)
コンテキスト管理 古い会話を要約する。直近10件のメッセージはそのまま残す
ツール おすすめの組み込みツール一式(allowedToolsが["*"]の状態)
メモリ マネージドメモリ(AgentCore Memory)が自動で有効になる
プロンプトキャッシュ 対応するBedrockモデルをconverse_stream形式で呼び出すと自動で使われる

ちなみにこのデフォルト値は改善に合わせて変わっていくそうです。明示的に設定した項目はそのまま残ります。
変化が激しい領域でデフォルト設定が良さげなものに変わっていくのは嬉しい反面、アウトプットの品質やコストも変わりやすいので注意が必要ですね。

ライフサイクルフック

今回ライフサイクルフックの対応もアップデートとして追加されています。
エージェントループの決まったタイミングで、Lambda・SNS・EventBridgeにイベントを送れます。

4つのフックの位置とLambda判定・SNS/EventBridge通知の流れ

イベント 動くタイミング Lambdaがdenyを返したとき
before_invocation 依頼を処理する前 呼び出しを止める
before_tool_call ツールを実行する前 そのツールだけ飛ばす
after_tool_call ツールの結果が出た後 その先の推論を止める
after_invocation 呼び出しが終わった後 記録するだけ(出力は取り消せない)

通知や承認プロセスを挟めるイメージですね。
Lambdaは許可か拒否を同期的に返せますが、SNSとEventBridgeは通知を受け取るだけで処理を止めることはできません。

前提

今回は下記前提で進めました。

項目 バージョン・値
AgentCore CLI 1.2.0
Python 3.15.2
boto3 1.44.5
リージョン us-east-1

さっそくやってみましょうか。

デフォルトのままHarnessを作る

名前だけを指定して作ります。

Harnessの作成
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
}

デフォルトの設定が入っていますね。システムプロンプトは以前の記事で全文を載せたStrands harnessのものと同じでした!

作成からREADYになるまでは4分ほどかかりました。

マネージドのシステムプロンプト(全文)
システムプロンプト
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.

組み込みツールを確認する

呼び出しにはboto3のinvoke_harnessを使いました!
作成結果のarnを環境変数HARNESS_ARNに設定して実行します。
サブエージェントを使うと次の応答まで数分空くことがあるため、read_timeoutは900秒にしています。

invoke.py
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)

invoke.pyに質問文を渡して使えるツールを挙げてもらうと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

それぞれの役割を整理すると次の通りです。

ツール 役割
shell シェルコマンドの実行
read・write・edit ファイルの読み取り・作成・編集
web_fetch 指定したURLのページ取得
subagent サブエージェントの起動・作業の委譲
retrieve_context プレビューに省略された長い結果の全文取得
todo_write TODOの記録・更新

このツールを実際に使ってみましょうか。

組み込みツールを連携させて動かす

実際にTODOとサブエージェントを使う指示つきで、AgentCoreとStrands harnessのドキュメントを読み比べて表にする作業を頼みました。

1回の依頼で次のように組み込みツールが連携して動きます。

組み込みツールが1回の依頼で連携して動く流れ(計画・並列調査・全文取得・作成と修正)

実行ログのツール呼び出しを抜粋すると、
計画・並列調査・全文取得・ファイル作成・検証と修正まで自律的に進んでいるのが分かります!

実行結果(ツール呼び出しの抜粋)
[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 {...}

ヘビーな作業をさせる時に役立ちそうです!

プロンプトキャッシュとallowedToolsでトークン数を見る

出力末尾のsession IDを--sessionに渡して続けて質問すると、1回目にキャッシュへ書き込んだ3,375トークンを2回目はそのまま読み込んでいました。cacheReadInputTokensの欄で確認できます。

何も設定しなくてもキャッシュとして使われるのはいいですね!

2回目の実行結果
[usage] {"inputTokens": 2, "outputTokens": 319, "totalTokens": 3758, "cacheReadInputTokens": 3375, "cacheWriteInputTokens": 62}

allowedTools(使わせるツールの一覧)は呼び出しごとに上書きもできます。
読み取りとURL取得だけにしてファイルの作成を頼むと、書き込む手段がないと説明して作業を止めました。

allowedToolsを指定して実行
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` を保存することができませんでした(できていないので「完了」とは言えません)。

キャッシュへの書き込みも全ツールのときの3,375から1,299トークンに減りました。おすすめのツール一式でリクエストごとに約3,000トークン増えるそうなので、不要なツールや許可しない操作は明示的に外しておきたいですね。

ライフサイクルフックを試す

「依頼文にAWSアクセスキーをうっかり含めてしまったときにモデルへ渡る前に止めたい」「web_fetchで許可した公式サイト以外のURLを勝手に取得するのを防ぎたい」といった制御を入れたいケースがあるかもしれません。こうしたルールはシステムプロンプトに書いてもモデルが必ず守ってくれるとは限らないので、コード側から確実に止めるためにライフサイクルフックを試してみます!

そこで今回は、次のシナリオを4つのフックでまとめて試します。

  • 依頼文にAKIAで始まる20文字のアクセスキーIDらしき文字列があれば、before_invocationのLambdaでモデル呼び出し前にブロックする
  • 意図しない外部サイトへのアクセスを防ぐためにbefore_tool_callのLambdaで許可ドメイン(およびサブドメイン)以外のweb_fetchを止める
  • 実行を通知するためにafter_tool_callはSNS、after_invocationはEventBridgeを使用する
    • どちらも使っているのは連携できるかの検証で使い分けの意図はないです

同期判定の2つは1つのLambda関数にまとめ、SNSとEventBridgeの通知は確認しやすいように1つのSQSキューへ集約した構成にしています。

ライフサイクルフック検証の構成図。判定用の1つのLambdaと、SNS・EventBridgeからの通知を集めるSQSキューのつながり

hook_lambda/lambda_function.py
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 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": "依頼文にアクセスキーらしき文字列が含まれています"}

    # web_fetch は許可したドメインだけ取得させる
    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"}

送り先はHarnessの実行ロールで呼び出されます。

hook_lambdaディレクトリと同じ作業ディレクトリにsetup_hooks.shを置いて実行し、出力されたQUEUE_URLを控えます。

続けてhook_targets_policy.jsonの<アカウントID>を自分のAWSアカウントIDに置き換えてから、CLIが作ったロールに権限を足します。

フック用のリソースと権限の作成
setup_hooks.sh
#!/bin/bash
set -euo pipefail
REGION=us-east-1
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)

# Lambda(判定用)
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_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(ツール実行後の通知)
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(呼び出し完了の通知)
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

# SNSとEventBridgeからキューへの送信を許可
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"
hook_targets_policy.json
{
  "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

続いて4つのフックと送り先の対応をhooks.jsonに定義します。
Lambdaを呼び出すフックでは応答を待つ上限の秒数(timeoutSeconds)と、タイムアウトやエラーが発生したときの判定(failureMode)を指定できます。
failureModeは省略するとdenyになり、Lambda側で障害が起きても処理を止める仕組みです。

hooks.json
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"}}
    }
  }
]

今回はAWS CLIのupdate-harnessで4つのフックを設定しました。
hooks.jsonの<アカウントID>は自分のAWSアカウントIDに置き換え、--harness-idには最初の作成結果に表示されたharnessIdを指定します。

フックの設定
aws bedrock-agentcore-control update-harness --region us-east-1 \
  --harness-id <harnessId> --hooks file://hooks.json

アクセスキーを含む依頼を止める

AWSのドキュメントにあるサンプルのアクセスキー(AKIAIOSFODNN7EXAMPLE)を入れて、どのIAMユーザーのものか調べるよう頼んでみました。

実行結果(IDは一部省略)
[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でdenyが返り、hook_stoppedで終わっています。usageの行がなく、モデルは一度も呼び出されていません。
ライフサイクルを活用して意図通りブロックできましたね!

通知用のSQSキューはsetup_hooks.shが出力したキューURLで確認します。同じキューへ両方の通知を流しているので、JSONのeventがafter_tool_callならSNS経由で、detail.eventがafter_invocationならEventBridge経由となります。

SQSキューに届いた通知を確認
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'

EventBridgeから届いたafter_invocationの通知でもトークン数は0だったので推論されていないことがわかりますね。

EventBridgeから届いたafter_invocationの通知(抜粋)
{
  "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 }
    }
  }
}

取得できるドメインを限定する

許可していないドメインと許可したドメインのページを1つずつ取得させます。

2つのURLを取得させる
uv run invoke.py "次の2つのページをweb_fetchで取得して、それぞれのタイトルを教えてください。
- https://example.com/
- https://aws.amazon.com/jp/about-aws/whats-new/" --actor hooks-demo
実行結果(抜粋、hookEventIdは省略)
[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 は取得を許可していないドメインです`

example.comだけが飛ばされ、エージェントはそのままAWSのページを取得しました。
こちらも意図通りになっていますね!
ツール実行後はSNSに拒否されたweb_fetchの結果がエラーとして届いていました。

SNSから届いたafter_tool_callの通知(抜粋)
{
  "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 は取得を許可していないドメインです" }
      ]
    }
  }
}

サブエージェントにもフックがかかるか試す

サブエージェントにも適用されるか気になり試してみました!
example.comのタイトルを調べさせ、検証時にLambdaが受け取ったイベントと呼び出し結果を照合して実行順を整理しました(掲載用のLambdaでは依頼文をログへ残さないようイベント名とツール名だけ出力しています)。

Lambdaが受け取ったbefore_tool_callの順番(ログから整理)
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(親が自分で試した呼び出し)

サブエージェントの中でも親から呼び出したときと同じように、example.comへのweb_fetchを止められました!サブエージェント経由でも同じ条件でweb_fetchを止められるのは安心ですね。

後片付け

Harnessは作成結果のharnessIdを指定して削除でき、マネージドメモリも一緒に削除されます。CLIが作った実行ロールとフック用のリソース(EventBridge・SNS・SQS・Lambda・IAMロール)は残るため、まとめて削除するスクリプトを用意しておくと便利です。

削除用スクリプト(cleanup.sh)
cleanup.sh
#!/bin/bash
# 使い方: 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

おわりに

AgentCore Harnessは作るのが簡単なのでこのように便利になるのはありがたいですね!サクッと便利になるAIエージェントを模索していきたいです。

本記事が少しでも役に立ちましたら幸いです。最後までご覧いただきありがとうございました!

この記事をシェアする

関連記事