Bedrock Inline AgentでPerplexityなど複数のMCPサーバを使うサンプルを試してみる

Bedrock Inline AgentでPerplexityなど複数のMCPサーバを使うサンプルを試してみる

Clock Icon2025.04.14

はじめに

今回は、以下のブログで紹介されているBedrock Inline AgentとMCPサーバを使って外部サービスと連携しながらデータを抽出するサンプルを試してみます。試したサンプルでは、AWSのコスト情報を抽出してくる独自のMCPサーバとPerplexityのMCPサーバを利用します。

https://aws.amazon.com/jp/blogs/machine-learning/harness-the-power-of-mcp-servers-with-amazon-bedrock-agents/

大まかな構成

冒頭のブログにも書かれている図を引用します。ユーザの呼び出しに応じて、Inline AgentのSDKが必要なMCPサーバを判断して、リクエストを送ることでMCPサーバから外部サービスの出力を得ることができます。

image.png

Inline Agentについて補足します。以下のリンク先の画像にあるように、Bedrockのエージェントを定義するパラメータには基盤モデル、指示、アクション グループ、ガードレール、ナレッジ ベースなどが設定できます。これらのパラメータを動的に変更するために、Inline Agentが実装されています。Agentを固定の設定でなく、動的に設定できることで頻繁な設定変更へ対応可能になります。この仕組みで、MCPサーバも実行時に付け替えることができます。

image.png

https://github.com/awslabs/amazon-bedrock-agent-samples/tree/main/src/InlineAgent

今回作成する構成

Bedrock Inline AgentからAWSのコスト析用のMCPサーバとPerplexity用のMCPサーバを呼び出します。それぞれ情報を取得するためコスト分析のMCPサーバはAWSのアクセスキー/シークレットキー、PerplexityのMCPサーバはPerplexityのAPIキーを必要とします。

bedrock-agent-mcp.png

リクエストの流れは以下のFlow2のように、Inline AgentにinvokeするとBedrock Agent側でMCPサーバの利用を判断して各MCPサーバを呼び出して請求情報のデータを出力します。こちらも以下URLからの引用です。

image.png

https://aws.amazon.com/jp/blogs/machine-learning/harness-the-power-of-mcp-servers-with-amazon-bedrock-agents/

実装の確認と実行

実装では以下のサンプルコードを使用します。手順に沿って準備していきます。

https://github.com/awslabs/amazon-bedrock-agent-samples/tree/main

Inline Agentの実行サンプル

まずリポジトリをクローンして、セットアップを始めます。InlineAgent_helloでここまでの設定が正しく設定できてるかお試しの実行で確認できます。モデルはHaikuを使うのでコンソールから有効化してください。

git clone https://github.com/awslabs/amazon-bedrock-agent-samples.git
cd amazon-bedrock-agent-samples/src/InlineAgent

python -m venv .venv
source .venv/bin/activate

python -m pip install -e .

InlineAgent_hello us.anthropic.claude-3-5-haiku-20241022-v1:0

上記のInlineAgent_helloのソースを見てみます。以下をみるとhello_world.pyのmainが呼ばれているようです。

https://github.com/awslabs/amazon-bedrock-agent-samples/blob/9aa94fb43f73e0468ba7c16d75beb766d5f5b1b4/src/InlineAgent/pyproject.toml#L58-L59

上から見ていくとStep1でActionGroupに設定する関数を設定し、Step2でActionGroupのtoolsに登録しています。Step3ではInlineAgetにActionGroupを渡しつつ、指示を埋め込んでいます。この内容をStep4でinvokeしてます。
今回はMCPを使う例ではないですが、Inline Agentの実装の流れが軽く分かるように鳴っています。

https://github.com/awslabs/amazon-bedrock-agent-samples/blob/9aa94fb43f73e0468ba7c16d75beb766d5f5b1b4/src/InlineAgent/hello_world.py#L1-L36

認証情報と権限は以下のように設定します。テストなので広めの権限になっています。

credentials
[bedrock]
aws_access_key_id = {Your Access Key}
aws_secret_access_key = {Your Secret Access Key}
region = us-east-1
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "bedrock:*"
            ],
            "Resource": "*"
        }
    ]
}

profileを指定するため、以下のように最後の一行でprofileを追記します。

hello_world.py
await InlineAgent(
    foundation_model="us.anthropic.claude-3-5-sonnet-20241022-v2:0",
    instruction="""You are a friendly assistant that is responsible for resolving user queries.
    
    You have access to search, cost tool and code interpreter. 
    
    """,
    agent_name="cost_agent",
    action_groups=[
        cost_action_group,
        {
            "name": "CodeInterpreter",
            "builtin_tools": {
                "parentActionGroupSignature": "AMAZON.CodeInterpreter"
            },
        },
    ],
    profile="bedrock",  # 追加

認証情報がうまく設定されれば、以下のように出力を得れます。

Input Tokens: 600 Output Tokens: 137
Thought: The user has greeted me and asked about my capabilities. I'll respond in a friendly manner and use the user interaction tool to engage with them.
Hello there! I'm doing great, thank you for asking. I'm a friendly assistant who loves to say hello to everything! What would you like help with today? I'm ready to assist you with any questions or tasks you might have.
Agent made a total of 1 LLM calls, using 737 tokens (in: 600, out: 137), and took 10.5 total seconds

もし失敗する場合は、以下のコマンドでAWSから始まる環境変数が残っていないか確認して、unsetで解除してください。

env | grep AWS

Inline AgentからMCPサーバ実行のサンプル

ここからはいよいよMCPサーバを使うサンプルを試します。以下のコマンドでディレクトリを移動して試します。

cd examples/mcp/cost_explorer_agent

.env.exampleファイルを真似て、.envファイルを作ります。ここでは最初の方で示した図を再掲します。

bedrock-agent-mcp.png

AccessKey Bに当たる認証情報をセットしてください。CloudWatch LogsとCost Explorerのアクセス権が必要なので、AWSBillingReadOnlyAccessCloudWatchReadOnlyAccessをセットしています。
またBEDROCK_LOG_GROUP_NAMEは、適当なロググループを作成しました。

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_REGION=us-east-1
BEDROCK_LOG_GROUP_NAME=
PERPLEXITY_API_KEY=

上記の設定ファイルの準備が完了したら、以下のように追加のMCPサーバのサンプルとなるコンテナをビルドします。これでコスト分析のMCPサーバの事前準備は完了です。

git clone https://github.com/aws-samples/sample-cloud-spend-mcp-server.git
cd sample-cloud-spend-mcp-server
docker build -t aws-cost-explorer-mcp .

ここから実行するコードを見ていきます。全体的にはMCPサーバの準備、ActionGroupの設定、InlineAgentの設定、モデルへinvokeの流れになります。

https://github.com/awslabs/amazon-bedrock-agent-samples/blob/9aa94fb43f73e0468ba7c16d75beb766d5f5b1b4/src/InlineAgent/examples/mcp/cost_explorer_agent/main.py#L1-L50

mainの以下の部分でMCPサーバの準備をします。

https://github.com/awslabs/amazon-bedrock-agent-samples/blob/9aa94fb43f73e0468ba7c16d75beb766d5f5b1b4/src/InlineAgent/examples/mcp/cost_explorer_agent/main.py#L8-L14

MCPStdio.createに渡しているパラメータを見ると、単にDocker実行時に.envに先ほど設定したパラメータを橋渡ししていることが分かります。

https://github.com/awslabs/amazon-bedrock-agent-samples/blob/9aa94fb43f73e0468ba7c16d75beb766d5f5b1b4/src/InlineAgent/examples/mcp/cost_explorer_agent/config.py#L10-L40

MCPStdioの中身も見るとStdioServerParameters以外はパラメータはそんなにないようです。

https://github.com/awslabs/amazon-bedrock-agent-samples/blob/9aa94fb43f73e0468ba7c16d75beb766d5f5b1b4/src/InlineAgent/src/InlineAgent/tools/mcp.py#L127-L136

もとのソースに戻ると以下の部分でActionGroupにMCPサーバを設定しています。

https://github.com/awslabs/amazon-bedrock-agent-samples/blob/9aa94fb43f73e0468ba7c16d75beb766d5f5b1b4/src/InlineAgent/examples/mcp/cost_explorer_agent/main.py#L17-L20

設定したMCPサーバをInlineAgentのパラメータとして一部設定しています。

https://github.com/awslabs/amazon-bedrock-agent-samples/blob/9aa94fb43f73e0468ba7c16d75beb766d5f5b1b4/src/InlineAgent/examples/mcp/cost_explorer_agent/main.py#L21-L40

ここでもprofileを明示するためパラメータを追加します。

main.py
await InlineAgent(
    foundation_model="us.anthropic.claude-3-5-sonnet-20241022-v2:0",
    instruction="""You are a friendly assistant that is responsible for resolving user queries.
    
    You have access to search, cost tool and code interpreter. 
    
    """,
    agent_name="cost_agent",
    action_groups=[
        cost_action_group,
        {
            "name": "CodeInterpreter",
            "builtin_tools": {
                "parentActionGroupSignature": "AMAZON.CodeInterpreter"
            },
        },
    ],
    profile="bedrock", # 追加

いよいよ実行してみます。以下のコマンドでMCPサーバが実行され、BedrockやMCPサーバへのリクエストなどが始まります。

python main.py

もしうまく実行できない場合は以下を確認してください。

  • foundation_modelの部分の基盤モデルを有効化しているか
  • リージョンは想定した場所(us-east-1など)になっているか
  • AWSの認証情報はそれぞれ分けて設定できているか
  • IAMユーザに正しい権限が割当たっているか
  • CloudTrailで該当のリージョンにInvokeModelが実行されているか

うまくいくと以下のような標準出力と、自分のAWS環境のコスト分析情報を画像で取得できます。

% python main.py
Processing request of type ListToolsRequest

Connected to server with tools:['get_bedrock_daily_usage_stats', 'get_bedrock_hourly_usage_stats', 'get_ec2_spend_last_day', 'get_detailed_breakdown_by_day']
Processing request of type ListToolsRequest
Processing request of type ListToolsRequest
Perplexity Ask MCP Server running on stdio

Connected to server with tools:['perplexity_ask']
SessionId: 94a1b11f-c1f7-4a23-9a72-36a60fb40d4f
2025-04-11 23:50:35,062 - botocore.credentials - INFO - Found credentials in shared credentials file: ~/.aws/credentials

Input Tokens: 1502 Output Tokens: 155
Thought: Let me help you understand Amazon Bedrock and analyze your AWS spending. I'll:
1. Use Perplexity to get accurate information about Amazon Bedrock
2. Get detailed cost breakdown for the last 7 days
3. Create a visualization of the spending data

...

Code interpreter output: 
Code Interpreter created new files



Files saved in output directory                                                                                    
Input Tokens: 16037 Output Tokens: 217
Thought: Now I can provide a comprehensive answer about Amazon Bedrock and the cost analysis.
Amazon Bedrock is AWS's fully managed service that provides access to foundation models (FMs) from leading AI companies through a unified API. It allows developers to build and scale generative AI applications without managing infrastructure.

Looking at your AWS spending over the last 7 days, the top services by cost were:
1. Claude 3.5 Sonnet (Amazon Bedrock Edition): $2.26
2. AWS Security Hub: $1.62
3. AmazonCloudWatch: $0.24
4. Amazon GuardDuty: $0.16
5. AWS Config: $0.14

I've created a bar chart showing the cost distribution across these services. The visualization clearly shows that Amazon Bedrock (Claude 3.5 Sonnet) and AWS Security Hub were your highest spending services during this period.


Files saved in output directory                                                                                    

Agent made a total of 5 LLM calls, using 38789 tokens (in: 37886, out: 903), and took 54.7 total seconds

image.png

何度か出力すると微妙にグラフの構造は異なっていたので、安定化には工夫が必要そうです。
また日本語で出力を依頼すればLooking at your AWS spending...の部分だけは日本語で返答してくれます。

所感

AWSのInline Agentを使ったMCPサーバの利用方法を試してみました。Inline Agentに関する知識がほぼなかったので、そこから理解が必要でしたが多少は実装を見ながら理解できました。AIエージェントからInline Agentを呼び出す際にMCPを動的に設定するのもできそうと妄想しています。

InlineAgentの実装もまだこれから進んでいくものかと思います。またMCPクライアント側の実装として参考になる部分もあるので、このブログが少しでも誰かの役に立てば幸いです。

Share this article

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.