9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

どうもこんにちは。
今回は、Amazon Bedrock AgentCore Web Search を AWS CDK で構築して、Strands Agents から使ってみます。

Amazon Bedrock AgentCore Web Search は、AgentCore Gateway の組み込みツールとして提供されている Web 検索機能です。エージェントが最新情報や変化しやすい情報を扱うときに、外部 Web の検索結果を根拠として利用できます。

この記事は誰向け?

この記事は以下のような方向けに執筆しています。

  • Amazon Bedrock AgentCore を使ってみたい方
  • Amazon Bedrock AgentCore Web Search を試してみたい方
  • Strands Agents から AgentCore Gateway の MCP ツールを呼びたい方
  • AWS CDK(Python)で Amazon Bedrock AgentCore Runtime へエージェントをデプロイしたい方

デモコードの場所

実際に動かしたい方は、以下を参照ください。

この検証でやりたいこと

今回のゴールは次の3点です。

  • AgentCore Gateway に Web Search connector target を作成する
  • Strands Agents で作成した Python エージェントを AgentCore Runtime にデプロイする
  • Runtime 上のエージェントから Web Search を呼び、検索結果に基づいて回答させる

構成としては以下のようになります。

User
  |
  v
AgentCore Runtime
  |
  | Strands tool: web_search
  v
AgentCore Gateway
  |
  | MCP tools/call: WebSearch
  v
AgentCore Web Search

前提

今回の検証では、Web Search connector の対応リージョンに合わせて us-east-1 にデプロイしています。

手元では以下を利用しました。

  • Python 3.12
  • AWS CDK CLI
  • Docker
  • AWS CLI
  • CDK bootstrap 済みの AWS アカウント

また、Bedrock のモデルアクセスが有効化されている必要があります。

実装の流れ

0. 作業プロジェクトの用意

mkdir bedrock-agentcore-web-search-demo
cd bedrock-agentcore-web-search-demo

1. CDK プロジェクトの雛形を整える

1-1. 依存パッケージ

CDK 側の依存関係は以下です。

requirements.txt
aws-cdk-lib==2.256.1
constructs>=10.0.0,<11.0.0
cdk-ecr-deployment>=4.0.0,<5.0.0

開発用には pytest も入れます。

requirements-dev.txt
-r requirements.txt
pytest>=8.0.0,<9.0.0

cdk-ecr-deployment は、CDK がビルドした Docker image asset を、Runtime 用に作成した専用 ECR Repository へコピーするために使っています。

Runtime コンテナ側の依存関係は以下です。

agent/requirements.txt
bedrock-agentcore>=1.3.0,<2.0.0
strands-agents>=1.0.0,<2.0.0
boto3>=1.42.0
requests>=2.32.0,<3.0.0

requests は AgentCore Gateway の MCP endpoint を HTTP で呼ぶために使います。

1-2. CDK エントリーポイント

app.py は通常の CDK エントリーポイントです。

app.py
#!/usr/bin/env python3
import os

import aws_cdk as cdk

from infra.agentcore_web_search_stack import AgentCoreWebSearchDemoStack


app = cdk.App()

AgentCoreWebSearchDemoStack(
    app,
    "AgentCoreWebSearchDemoStack",
    env=cdk.Environment(
        account=os.environ.get("CDK_DEFAULT_ACCOUNT"),
        region="us-east-1",
    ),
)

app.synth()

今回は Web Search connector に合わせて us-east-1 固定にしています。

1-3. cdk.json

cdk.json では、CDK CLI が常にプロジェクト内の仮想環境を使うようにしています。

cdk.json
{
  "app": ".venv/bin/python app.py",
  "context": {
    "@aws-cdk/core:newStyleStackSynthesis": true
  }
}

これで、仮想環境を activate していない状態でも cdk synth や cdk deploy が同じ Python 環境を使ってくれます。

1-4. 仮想環境

python3.12 -m venv .venv
source .venv/bin/activate
pip install -r requirements-dev.txt -r agent/requirements.txt

AWS 認証を確認します。

aws sts get-caller-identity
export AWS_REGION=us-east-1

初回のみ bootstrap します。

cdk bootstrap

2. AgentCore Gateway に Web Search connector target を作る

Web Search は AgentCore Gateway の connector target として作成します。

現時点の CDK L2 construct ではなく、CfnResource で CloudFormation resource を直接定義しました。

from aws_cdk import CfnResource


def _create_gateway(self, gateway_role: iam.Role) -> CfnResource:
    return CfnResource(
        self,
        "WebSearchGateway",
        type="AWS::BedrockAgentCore::Gateway",
        properties={
            "Name": "AgentCoreWebSearchDemo",
            "Description": "Gateway exposing the managed WebSearch MCP tool.",
            "AuthorizerType": "AWS_IAM",
            "ProtocolType": "MCP",
            "RoleArn": gateway_role.role_arn,
        },
    )

Gateway target 側では ConnectorId に web-search を指定します。

return CfnResource(
    self,
    "WebSearchGatewayTarget",
    type="AWS::BedrockAgentCore::GatewayTarget",
    properties={
        "GatewayIdentifier": gateway.ref,
        "Name": "web-search-tool",
        "Description": "Managed Web Search connector target.",
        "TargetConfiguration": {
            "Mcp": {
                "Connector": {
                    "Source": {"ConnectorId": "web-search"},
                    "Configurations": [
                        {
                            "Name": "WebSearch",
                            "ParameterValues": parameter_values,
                        }
                    ],
                }
            }
        },
        "CredentialProviderConfigurations": [
            {"CredentialProviderType": "GATEWAY_IAM_ROLE"}
        ],
    },
)

除外したいドメインがある場合は、CDK context の excludedDomains を domainFilter に渡せるようにしています。

excluded_domains = self.node.try_get_context("excludedDomains") or []

parameter_values: dict[str, object] = {}
if excluded_domains:
    parameter_values["domainFilter"] = {"exclude": excluded_domains}

デプロイ時は以下のように指定できます。

cdk deploy -c 'excludedDomains=["example.com","blocked.example"]'

3. IAM ロール

今回作るロールは大きく2つです。

  • Gateway 用 IAM ロール
  • Runtime 用 IAM ロール

Gateway 用ロールには、Web Search の実行権限を付与します。

WEB_SEARCH_TOOL_ARN = (
    f"arn:{Aws.PARTITION}:bedrock-agentcore:{Aws.REGION}:aws:tool/web-search.v1"
)

gateway_role.add_to_policy(
    iam.PolicyStatement(
        actions=["bedrock-agentcore:InvokeWebSearch"],
        resources=[WEB_SEARCH_TOOL_ARN],
    )
)

Runtime 用ロールには、Bedrock モデル呼び出し、ECR pull、CloudWatch Logs、Gateway 呼び出しの権限を付与します。

runtime_role.add_to_policy(
    iam.PolicyStatement(
        actions=["bedrock-agentcore:InvokeGateway"],
        resources=[gateway_arn],
    )
)

Runtime から Gateway を呼ぶため、この bedrock-agentcore:InvokeGateway が必要です。

4. Runtime コンテナを作る

Runtime 用の Dockerfile はシンプルです。

agent/Dockerfile
FROM public.ecr.aws/docker/library/python:3.12-slim

ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
ENV PORT=8080

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY web_search_agent ./web_search_agent

EXPOSE 8080

CMD ["python", "-m", "web_search_agent.runtime_app"]

AgentCore Runtime は HTTP protocol で起動し、bedrock_agentcore.runtime.BedrockAgentCoreApp を使って entrypoint を公開します。

agent/web_search_agent/runtime_app.py
from bedrock_agentcore.runtime import BedrockAgentCoreApp

from .agent import create_agent, extract_text

app = BedrockAgentCoreApp()


def invoke_agent(payload: dict) -> dict:
    prompt = payload.get("prompt")
    if not isinstance(prompt, str) or not prompt.strip():
        raise ValueError("payload.prompt must be a non-empty string")

    result = create_agent()(prompt.strip())
    return {
        "response": extract_text(result),
        "evidence": {
            "webSearchGatewayConfigured": True,
        },
    }


@app.entrypoint
def invoke(payload: dict) -> dict:
    return invoke_agent(payload)


@app.ping
def ping() -> dict:
    return {"status": "Healthy"}


if __name__ == "__main__":
    app.run()

5. AgentCore Runtime を CDK で作成する

CDK では Docker image asset を作り、専用 ECR Repository にコピーしてから Runtime に渡しています。

image_repository = ecr.Repository(
    self,
    "AgentImageRepository",
    repository_name="agentcore-web-search-demo",
    image_scan_on_push=True,
    image_tag_mutability=ecr.TagMutability.IMMUTABLE,
    removal_policy=RemovalPolicy.DESTROY,
    empty_on_delete=True,
)

image_asset = ecr_assets.DockerImageAsset(
    self,
    "AgentImageAsset",
    directory=str(Path(__file__).resolve().parents[1] / "agent"),
    platform=ecr_assets.Platform.LINUX_ARM64,
)

runtime_image_uri = image_repository.repository_uri_for_tag(image_asset.asset_hash)

Runtime には、Gateway URL を環境変数として渡します。

runtime = bedrock_agentcore.CfnRuntime(
    self,
    "AgentRuntime",
    agent_runtime_name="AgentCoreWebSearchDemoRuntime",
    description="Strands agent using AgentCore Gateway Web Search.",
    agent_runtime_artifact=bedrock_agentcore.CfnRuntime.AgentRuntimeArtifactProperty(
        container_configuration=bedrock_agentcore.CfnRuntime.ContainerConfigurationProperty(
            container_uri=runtime_image_uri,
        )
    ),
    network_configuration=bedrock_agentcore.CfnRuntime.NetworkConfigurationProperty(
        network_mode="PUBLIC",
    ),
    protocol_configuration="HTTP",
    role_arn=runtime_role.role_arn,
    environment_variables={
        "AWS_REGION": self.region,
        "BEDROCK_MODEL_ID": model_id,
        "AGENTCORE_GATEWAY_URL": gateway_url,
        "WEB_SEARCH_MAX_RESULTS": "5",
    },
)

AGENTCORE_GATEWAY_URL は、Runtime 側で MCP endpoint として使います。

6. Strands Agents から Web Search を呼ぶ

Strands Agents 側では web_search という tool を定義します。

agent/web_search_agent/agent.py
@tool
def web_search(query: str, max_results: int | None = None) -> str:
    """Search the live web with Amazon Bedrock AgentCore Web Search.

    Args:
        query: Search query. Keep it specific and at most 200 characters.
        max_results: Maximum number of results to return. Valid range is 1-25.
    """
    client = AgentCoreGatewayMcpClient(gateway_url=get_gateway_url())
    result_limit = max_results if max_results is not None else get_default_max_results()
    return format_search_results(client.web_search(query=query, max_results=result_limit))

Agent にはこの tool を渡します。

def create_agent(callback_handler=None) -> Agent:
    region = get_region()
    model = BedrockModel(
        model_id=get_model_id(),
        boto_session=boto3.Session(region_name=region),
    )
    return Agent(
        model=model,
        tools=[web_search],
        system_prompt=SYSTEM_PROMPT,
        callback_handler=callback_handler,
    )

システムプロンプトでは、最新情報や根拠が必要な情報では Web Search を使い、最終回答には出典リンクを含めるように指示しています。

SYSTEM_PROMPT = """You are a Japanese research assistant with access to WebSearch.

Use web_search whenever the user asks about current, recent, changing, or
source-sensitive information. Base your final answer on the search results and
include source links. If the search tool fails or returns no relevant results,
say so plainly. Do not invent citations.
"""

7. Gateway の MCP endpoint を SigV4 署名付きで呼ぶ

AgentCore Gateway の Output で取得できる GatewayUrl は、MCP endpoint として使うために末尾 /mcp に正規化しておきます。

def normalize_gateway_url(gateway_url: str) -> str:
    normalized = gateway_url.strip().rstrip("/")
    if urlparse(normalized).path.rstrip("/").endswith("/mcp"):
        return normalized
    return f"{normalized}/mcp"

また、MCP の流れに合わせて、最初に initialize と notifications/initialized を送ってから tools/call を実行します。

self._json_rpc(
    method="initialize",
    params={
        "protocolVersion": MCP_PROTOCOL_VERSION,
        "capabilities": {},
        "clientInfo": {
            "name": "agentcore-web-search-demo",
            "version": "0.1.0",
        },
    },
)
self._json_rpc(
    method="notifications/initialized",
    params={},
    expect_response=False,
)

その後、tools/list で Gateway が公開している tool 名を取得します。AWS Blog の例では Web Search の tool 名は WebSearchTool です。target configuration の name に指定した WebSearch と、MCP tool として公開される WebSearchTool は一致しないため、固定文字列で呼ばずに tools/list の結果から選ぶようにしました。

response = self._json_rpc(method="tools/list", params={})
tool_names = extract_tool_names(response)
tool_name = select_web_search_tool_name(tool_names)

最後に、解決した tool 名で AgentCore Gateway の MCP endpoint に対して tools/call を投げています。

payload = {
    "jsonrpc": "2.0",
    "id": str(uuid.uuid4()),
    "method": "tools/call",
    "params": {
        "name": tool_name,
        "arguments": {
            "query": query,
            "maxResults": max(1, min(max_results, 25)),
        },
    },
}

Gateway は AWS IAM 認証にしているので、リクエストは SigV4 で署名します。

request = AWSRequest(
    method="POST",
    url=url,
    data=body,
    headers=signing_headers,
)
SigV4Auth(
    credentials.get_frozen_credentials(),
    "bedrock-agentcore",
    self.region,
).add_auth(request)

HTTP header には MCP protocol version も指定しています。

headers = {
    "content-type": "application/json",
    "accept": "application/json, text/event-stream",
    "mcp-protocol-version": "2025-03-26",
}

Web Search の結果は MCP response の content にテキストとして返ってくるため、JSON として取り出して Strands tool の戻り値に整形しています。

def format_search_results(results: list[SearchResult]) -> str:
    if not results:
        return "No web search results were returned."

    lines: list[str] = []
    for index, result in enumerate(results, start=1):
        date_suffix = f" ({result.published_date})" if result.published_date else ""
        lines.append(f"[{index}] {result.title}{date_suffix}")
        if result.url:
            lines.append(f"URL: {result.url}")
        if result.text:
            lines.append(f"Snippet: {result.text}")
        lines.append("")
    return "\n".join(lines).strip()

ここで title、URL、snippet を明示しておくと、モデルが最終回答で出典リンクを使いやすくなります。

8. デプロイ

テストと synth を実行します。

pytest
cdk synth

今回 cdk synth で以下の表示が出ました。

79 feature flags are not configured. Run 'cdk flags --unstable=flags' to learn more.

これは CDK の feature flag が cdk.json に明示固定されていないという情報表示です。今回の検証では、このまま進めています。

以前 `aws-cdk-lib==2.255.0` を使っていたときは、`NOTICE 37949` も出ました。これは `aws-cdk-lib==2.256.1` に上げることで出なくなりました。

問題なければデプロイします。

cdk deploy

デプロイが成功すると、以下のような Output が出ます。

AgentRuntimeArn
AgentRuntimeId
GatewayArn
GatewayId
GatewayUrl
WebSearchTargetId
AgentImageRepositoryUri
AgentImageUri

9. 動作確認

AgentCore コンソールから AgentCoreWebSearchDemoRuntime を選び、以下のような payload を送信します。

{
  "prompt": "2026年7月7日の日本のプロ野球の日程を調べてください。"
}

Runtime からは以下のような形式で返ります。

{
  "response": "複数の検索結果から、2026年7月7日(火曜日)のNPB試合情報をまとめることができました。以下にご報告します。\n\n---\n\n## ⚾ 2026年7月7日(火)日本プロ野球(NPB)試合日程・情報\n\n### 🔵 パシフィック・リーグ\n\n| 対戦カード | 会場 | 開始時刻 | 予告先発 |\n|---|---|---|---|\n| **北海道日本ハム vs 千葉ロッテ** | ZOZOマリンスタジアム(千葉) | 18:00 | 日本ハム:**北山亘基**(9勝目狙い・パ単独トップ) |\n| **埼玉西武 vs 東北楽天** | 沖縄セルラースタジアム那覇 | 18:30 | 西武:**平良海馬**(12試合5勝2敗、防御率1.05)/楽天:**荘司康誠**(13試合4勝7敗、防御率4.22) |\n| **福岡ソフトバンク vs オリックス** | みずほPayPayドーム(福岡) | 18:00 | ソフトバンク:**上沢直之**/オリックス:**ショーン・ジェリー** |\n\n### 🔴 セントラル・リーグ\n\n| 対戦カード | 会場 | 開始時刻 |\n|---|---|---|\n| **広島東洋カープ vs 阪神タイガース** | マツダスタジアム(広島)など | 18:00 |\n| **読売ジャイアンツ vs 中日ドラゴンズ** | 東京ドームなど | 18:00 |\n| **横浜DeNAベイスターズ vs 東京ヤクルトスワローズ** | 横浜スタジアムなど | 18:00 |\n\n---\n\n### 📝 注目ポイント・補足情報\n\n- **西武 vs 楽天(那覇)**は注目の一戦。西武・平良海馬投手は沖縄県出身で\"地元凱旋登板\"となります。沖縄出身投手の地元試合初勝利がかかります。\n- **ソフトバンク vs オリックス**では、上沢直之が先発予定と報じられていました(7月6日時点の情報)。\n- **オリックス**は頓宮裕真の右膝手術が発表されたばかりで、チーム状況に影響がありそうです。\n- **セ・リーグ順位**(7月7日直前時点):阪神・巨人が首位争い中(ともに勝率.542)。\n\n---\n\n> 📌 **出典**\n> - NPB公式スケジュールページ: https://npb.jp/bis/eng/2026/games/gm20260707.html\n> - パ・リーグ公式: https://pacificleague.com/news/2026/7/84429\n> - パ・リーグ公式: https://pacificleague.com/news/2026/7/10052305\n> - パ・リーグ公式: https://pacificleague.com/news/2026/7/10052302\n\nなお、試合は本日18時前後に始まるため、**最終的なスコア・結果はNPB公式サイト(https://npb.jp)やスポーツニュースで随時ご確認ください。**",
  "evidence": {
    "requestId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "webSearchGatewayConfigured": true
  }
}

response の中に Web Search で取得した情報と出典リンクが含まれていれば成功です。

ただ、2026年7月7日のプロ野球の組み合わせが違かったり・球場が違かったり...
やはり、噂通りではありますが、精度は高くないですね...
tavilyやBrave APIを使うのが現時点では得策ですね!

CloudWatch Logs 側では、Runtime の起動や invocation のログを確認できます。

agent_invocation_started requestId=...
agent_invocation_completed requestId=...

ハマりどころ

Web Search connector は us-east-1 に寄せる

今回の実装では app.py で us-east-1 固定にしています。

region="us-east-1"

手元の AWS CLI の default region が東京リージョンになっている場合でも、CDK stack は us-east-1 に作られます。

Runtime から Gateway を呼ぶには InvokeGateway が必要

Runtime 側の IAM Role に bedrock-agentcore:InvokeGateway がないと、Gateway の MCP endpoint 呼び出しで失敗します。

また、Gateway 側の role には Web Search 実行用に bedrock-agentcore:InvokeWebSearch が必要です。

GatewayUrl は /mcp endpoint として使う

GatewayUrl をそのまま POST すると、MCP endpoint に届かず Web Search tool が失敗する場合があります。Runtime 側では GatewayUrl の末尾に /mcp がなければ追加するようにしました。

また、MCP server として扱うため、tools/call の前に initialize と notifications/initialized も送っています。また、tool 名は WebSearch 固定ではなく、tools/list で取得できる WebSearchTool を使います。検索ツールがモデル上で「技術的なエラー」として扱われる場合は、Runtime の CloudWatch Logs で gateway_mcp_call_failed または gateway_mcp_error を確認すると HTTP status や Gateway からの error body を見られます。

今回の検証とは関係ないところでミスったところ

ping handler は dict ではなく PingStatus を返す

BedrockAgentCoreApp の @app.ping で dict を返すと、SDK 側の ping endpoint で以下のようなエラーになります。

AttributeError: 'dict' object has no attribute 'value'

bedrock-agentcore の Runtime SDK は ping handler の戻り値として PingStatus enum、または PingStatus に変換できる文字列を期待しています。

そのため、以下のように PingStatus.HEALTHY を返します。

from bedrock_agentcore.runtime import BedrockAgentCoreApp, PingStatus

app = BedrockAgentCoreApp()

@app.ping
def ping() -> PingStatus:
    return PingStatus.HEALTHY

片付け

検証が終わったら destroy します。

cdk destroy

今回の構成では ECR Repository も RemovalPolicy.DESTROY かつ empty_on_delete=True にしているため、スタック削除時に一緒に削除されます。

まとめ

Amazon Bedrock AgentCore Web Search を、AgentCore Gateway の connector target として CDK で作成し、AgentCore Runtime 上の Strands Agent から呼び出してみました。

ポイントは以下です。

  • Web Search は AgentCore Gateway の web-search connector target として作る
  • Runtime には Gateway URL を環境変数で渡す
  • Gateway 呼び出しは MCP の tools/call を SigV4 署名付き HTTP request として送る
  • Strands Agents 側では通常の tool として web_search を定義できる

AgentCore Browser や Code Interpreter と同じように、Runtime に載せた Strands Agent から AgentCore の各種ツールを組み合わせられるので、今後は Web Search、Browser、Code Interpreter を用途に応じて使い分ける構成も試していきたいと思います。

9
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?