40
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Strands Agents SDKでMCPホストアプリを作ってみよう!

40
Last updated at Posted at 2025-05-25

こんなWebアプリを簡単に作ろう!

好きなMCPサーバーをセットできます。

スクリーンショット 2025-05-26 3.22.32.png

超簡易構成図

スクリーンショット 2025-05-26 2.49.25.png

完成品は、ここから誰でも試せます!

Strands Agents SDKとは?

AWSが最近発表した、AIエージェント開発用フレームワークです。

LangGraphとかMastraみたいなやつですね。
めちゃシンプルかつ高機能で、特にAWSやBedrockとの親和性が高いです!

手順

AWSアカウントを作成

Bedrockのモデルを有効化

「Bedrock > モデルアクセス」から、すべてのモデルを有効化すればOKです。

CloudShellでアプリを開発

AWSのシェル環境「CloudShell」を使って、ブラウザ完結でアプリを動かしてみます。
もちろんローカルPCで実施してもOKです。

Pythonバージョンを上げます。

CloudShell
# Python 3.13をインストール
sudo dnf -y install python3.13 python3.13-pip zip

# シェルにエイリアスを設定
echo "alias python=python3.13" >> ~/.bashrc
echo "alias pip=pip3.13" >> ~/.bashrc
source ~/.bashrc

nanoエディターでPythonファイルを作成します。

CloudShell
nano app.py

以下のコードを貼り付けます。

app.py
import asyncio
import streamlit as st
from strands import Agent
from strands.tools.mcp import MCPClient
from mcp import stdio_client, StdioServerParameters

# ===== ページ設定 =====
st.title("Strands MCPエージェント")
st.text("👈 サイドバーで好きなMCPサーバーを設定してね!")

# ===== サイドバー =====
with st.sidebar:
    mcp_package = st.text_input(
        "ローカルMCPサーバーのパッケージ名(Python用)",
        "awslabs.aws-documentation-mcp-server@latest"
    )

# ===== 質問入力 =====
question = st.text_input("質問を入力", "Bedrockでマルチエージェントは作れる?")

# ===== ボタンを押したら生成開始 =====
if st.button("質問する"):

    # MCPクライアントを作成
    mcp_client = MCPClient(lambda: stdio_client(
        StdioServerParameters(command="uvx", args=[mcp_package])
    ))

    # エージェントを作成(MCPクライアントを直接渡す新しい書き方)
    agent = Agent(
        model="us.anthropic.claude-haiku-4-5-20251001-v1:0",
        tools=[mcp_client]
    )

    # ストリーミング用の変数
    container = st.container()
    text_holder = container.empty()
    buffer = ""
    shown_tools = set()

    # ストリーミングで回答を生成
    with st.spinner("回答を生成中…"):

        async def run_stream():
            global buffer, text_holder, shown_tools

            async for chunk in agent.stream_async(question):
                if isinstance(chunk, dict):

                    # ツール実行を検出して表示
                    event = chunk.get("event", {})
                    if "contentBlockStart" in event:
                        tool_use = event["contentBlockStart"].get("start", {}).get("toolUse", {})
                        tool_id = tool_use.get("toolUseId")
                        tool_name = tool_use.get("name")
                        if tool_id and tool_name and tool_id not in shown_tools:
                            shown_tools.add(tool_id)
                            if buffer:
                                text_holder.markdown(buffer)
                                buffer = ""
                            container.info(f"🔧 **{tool_name}** ツールを実行中...")
                            text_holder = container.empty()

                    # テキストを抽出して表示
                    text = chunk.get("data") or chunk.get("delta", {}).get("text") or ""
                    if text:
                        buffer += text
                        text_holder.markdown(buffer + "")

            # 最終表示
            if buffer:
                text_holder.markdown(buffer)

        # 非同期実行
        loop = asyncio.new_event_loop()
        loop.run_until_complete(run_stream())
        loop.close()

実行してみましょう。

CloudShell
# Strands Agentsをインストール
pip install uv streamlit strands-agents strands-agents-tools

# アプリを起動
streamlit run app.py

CloudShellで2つ目のタブ(リージョン名)を起動して、PinggyというトンネリングサービスにSSH接続します。(Web公開されます)

CloudShell(2タブ目)
ssh -p 443 -R0:localhost:8501 a.pinggy.io

表示されたURLにアクセスしてみましょう!

スクリーンショット 2025-05-26 3.22.32.png

好きなローカルMCPサーバーを入力して、AIエージェントにツールとして使わせることが可能です。

Pinggyで公開URLを発行しているので、どこからでもアクセスできてしまいます。セキュリティにはご留意ください。

Pinggyの無料セッション経過(60分)、もしくはCloudShellの自動停止(20〜30分)でアプリは止まってしまいます。

ソースコード

こちらに公開しています。

次のステップ

今回作ったアプリをコンテナにしてWeb公開してみる

GUIで簡単にAIエージェントを作ってみる

LLMOps(監視と評価)に入門してみる

おまけ

Bedrockにちゃんと入門してみたくなったら…

スクリーンショット 2025-05-25 19.39.00.png

MCPの入門書も出版します! すでにアマゾン等で予約可能。

やさしいMCP入門.png

40
20
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
40
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?