Amazon Bedrock AgentCore と Mistral AI Studio を活用した、本番環境対応の EC モデルコンテキストプロトコルサーバーの構築と接続
AWS と Mistral AI が共同で、EC サイト向けに標準化された MCP サーバーを構築・接続する具体的な実装ガイドとアーキテクチャを提供し、開発期間の短縮とセキュリティ強化を実現した。
キーポイント
MCP と AgentCore の統合による開発効率化
Amazon Bedrock AgentCore Runtime を活用することで、コンテナ管理や認証ミドルウェアの手間を省き、標準化された MCP プロトコル上で EC 機能を迅速に実装できる。
二層 JWT 認証とデータ分離の実装
Amazon Cognito を用いた OAuth 2.1 と二層 JWT 認証により、顧客ごとのデータアクセススコープを厳密に制御し、セキュリティリスクを低減する仕組みが解説されている。
Mistral AI Vibe による多様なクライアント接続
構築した MCP サーバーを Mistral AI の Vibe に接続することで、Web、iOS、Android から自然言語で商品検索や注文処理が可能になるエンドツーエンドのソリューション。
認証ベースの顧客データアクセス制御
API は Authorization ヘッダーを必須とし、匿名ユーザーに対してはエラーを返すことでセキュリティを確保しています。
注文履歴取得ロジックの実装
有効な顧客IDに基づいて過去注文のステータス、製品詳細、価格情報をリスト形式で返却する処理が定義されています。
データ拡張によるレスポンス最適化
注文データを製品情報と結合し、AI モデルが追加の呼び出しを行わずに自然言語で応答できるよう、機械識別子と人間向けのラベルを同時に返す。
二層認証アーキテクチャ
インフラ層で JWT の暗号学的検証を行い、アプリ層でトークンから顧客 ID を解決する役割分担により、セキュリティと柔軟性を両立させる。
影響分析・編集コメントを表示
影響分析
この記事は、AI エージェントの実用化における最大のボトルネックである「個別統合コスト」と「セキュリティ管理」を解決する具体的なパターンの提示であり、業界全体が MCP 標準へ移行する際の重要な指針となる。AWS と Mistral AI の連携により、企業は複雑なインフラ構築なしで高機能な AI エコシステムを迅速に展開できるようになるため、EC 分野における AI 導入のスピードと質が飛躍的に向上すると予想される。
編集コメント
AWS と Mistral AI の連携により、MCP という標準規格を実際の EC シナリオでどう実装するかを詳細に示した非常に実践的な記事です。特にセキュリティとスケーラビリティを両立するアーキテクチャは、開発者が即座に適用可能な価値があります。
ECMチームがAIを活用した顧客体験の市場投入を迅速化したい場合、通常は数週間にわたるカスタム統合作業に直面し、ローンチが遅れ、セキュリティリスクが高まります。本番環境で動作するAIアシスタントを構築・接続するには、各クライアントごとにカスタムAPIコードを作成し、コンテナインフラストラクチャの管理や複雑な認証処理が必要となります。Amazon Bedrock AgentCoreとMistral AI Studioはこのプロセスを簡素化します。Amazon Bedrock AgentCore上で本番環境対応のECM向けModel Context Protocol (MCP) サーバーを構築し、Mistral AI Studioに接続することで開発が効率化されます。MCPは標準化された統合プロトコルを提供し、AgentCore Runtimeはコンテナ管理とトークンの検証を担当し、Amazon Cognitoがアイデンティティ管理を行います。
本稿では、そのサーバーをエンドツーエンドで構築・接続する方法を解説します。MCPツールの実装、2層構造のJSON Web Token (JWT) 認証の設定、AWS Cloud Development Kit (AWS CDK) を用いたデプロイ、そしてMistral AIのVibeとの接続を行います。また、前提条件、ソリューションアーキテクチャ、MCPサーバーおよびVibeコネクタに関するベストプラクティス、リソースのクリーンアップについても取り上げます。構築するECMサーバーは、Amazon DynamoDBをデータストレージに、Amazon Cognitoをアイデンティティ管理に用いながら、商品検索、注文処理、レビュー投稿、返品対応をサポートします。
Amazon Bedrock AgentCore は、大規模に AI エージェントを構築・接続・最適化するためのプラットフォームです。その中核となる AgentCore Runtime は、エージェントおよび MCP ワークロードのホスティングのための完全に管理されたサーバーレスコンポーネントであり、セッションの分離、長時間実行されるリクエストのサポート、組み込みの JWT 検証、観測可能性を提供します。これにより、コンテナやロードバランサー、認証ミドルウェアの管理は不要となります。本稿では、Python と FastMCP を用いて MCP サーバーを構築し、それを Runtime にデプロイして管理されたホスティングを実現する方法を解説します。Amazon Cognito は OAuth 2.1 を通じてユーザーアイデンティティを管理し、各顧客のデータを分離します。MCP を利用すれば、各クライアントごとに個別の統合を構築するのではなく、複数の AI クライアントが接続できる単一のサーバーを書くだけで済みます。Mistral AI の Vibe は、Web、iOS、Android 上でユーザーにサーバーへの会話型インターフェースを提供します。
最終的には、Amazon Cognito を通じてユーザー認証を行い、顧客ごとにデータアクセスのスコープを制限し、Vibe からの自然言語クエリに応答する動作する EC MCP サーバーが完成します。このサーバーは MCP スタンダードを採用しているため、他の MCP 互換クライアントも接続可能です。
ソリューションの実行例を確認するには、以下のデモ動画をご覧ください。その後、本稿を詳しく読むことで、ご自身で生産環境対応の MCP サーバーを実装し、Vibe からクエリする詳細なガイドをご参照いただけます。
前提条件
Amazon DynamoDB(NoSQL データベース)テーブル、Amazon Cognito ユーザープール(ユーザー ID、OAuth 2.1)、AWS Identity and Access Management (IAM) ロール、および Amazon Elastic Container Registry (Amazon ECR) リポジトリの作成権限と、Amazon Bedrock AgentCore(AI エージェントの構築・実行プラットフォーム)へのアクセス権限を持つ AWS アカウントが必要です。ローカル開発ツールとしては、Python 3.10 以降、Node.js 18 以降、AWS CDK (npm install -g aws-cdk)、認証情報を設定した AWS Command Line Interface (AWS CLI)、および Amazon Bedrock AgentCore CLI (pip install bedrock-agentcore) をインストールしてください。また、Vibe にアクセスできる Mistral AI アカウントも必要です。AgentCore Runtime は AWS CodeBuild を使用してクラウド上でコンテナイメージを構築するため、Docker のインストールは不要です。
ソリューションの概要
ここでは、製品検索、注文の作成、レビューの投稿、返品処理といった実際のショッピング操作を実行する EC MCP サーバーの構築方法をご紹介します。このプロセスでは、3 つのレイヤーを扱います。
- アプリケーション層:MCP サーバーは、MCP サーバー構築用のフレームワークである FastMCP を用いて構築された Python アプリケーションです。/mcp エンドポイントを通じて 6 つの EC ツールを公開し、監視用の /health エンドポイントを備えています。AgentCore Runtime は、このサーバーをコンテナとして実行します。
- データ層:5 つの Amazon DynamoDB テーブルが EC データを格納しています。これらは「Products(製品)」「Customers(顧客)」「Orders(注文)」「Reviews(レビュー)」「Returns(返品)」です。自動スケーリングのためにオンデマンド容量でテーブルをプロビジョニングします。Global Secondary Indexes は、効率的なクエリパターンをサポートします。
- セキュリティ層:各顧客のデータを秘匿化する 2 段階認証方式を採用しています。Amazon Cognito がアイデンティティプロバイダーとして機能し、AgentCore Runtime がインフラレベルで JWT トークンを検証します。アプリケーションはユーザー固有の属性を抽出し、認証された顧客にのみデータアクセスをスコープします。
このソリューションは、4 つのインフラストラクチャスタックを用いた AWS CDK によってデプロイされます。DynamoDBStack は、5 つのデータテーブルを作成し、インデックスを設定して開発環境で簡単に削除できるよう構成します。CognitoStack は、顧客識別用のカスタム属性を持つユーザープールをプロビジョニングし、Mistral AI Vibe 統合用に設定された OAuth 2.1 アプリクライアントを作成します。DataLoaderStack は、AWS Lambda カスタムリソースを使用して、データベースに現実的なテストデータ(製品 50 件、顧客 10 名、注文 50 件、レビュー、返品)をシードし、デプロイ直後にサーバーをテストできるようにします。AgentCoreRuntimeStack は、必要な権限を持つ IAM ロールを作成し、コンテナイメージ用の ECR リポジトリをプロビジョニングし、デプロイコマンドが参照する設定パラメータを保存します。

図 1. EC モデル MCP サーバーのリクエストフローアーキテクチャ
図は、ユーザーが Mistral Vibe を通じて EC MCP サーバーと対話する際のリクエストフローを示しています。最初のリクエストの前に、ユーザーは OAuth 2.1 ログインフローを通じて認証を行います:Vibe が Cognito でホストされたログインページを開き、ユーザーが資格情報を入力すると、Cognito が JWT トークンを発行し、Vibe がセッションのためにこれを保存します。ユーザーが「最近の注文を表示して」と尋ねると、AI モデルは get_order_history MCP ツールを呼び出す必要があると判断し、HTTPS を介して AgentCore エンドポイントに MCP リクエストを送信します。このリクエストには、OAuth 2.1 ログインフローから得られた Bearer JWT トークンが含まれています。アプリケーションコードに到達する前に、AgentCore の JWT バリデーターが Cognito User Pool と連携してトークンを検証し、署名、有効期限、クライアントの権限を確認した後、無効なトークンは拒否します。検証が完了すると、リクエストは MCP サーバーコンテナに到達し、そこでは認証されたユーザーを EC プロフィールと紐付ける顧客 ID 属性を取得するために Cognito を呼び出します。顧客の身元が確認されると、サーバーは関連する DynamoDB テーブルに対してクエリを実行します。この操作はプライバシーと分離性を確保するため、該当顧客のデータにのみスコープが限定されます。その後、サーバーは構造化された応答を AgentCore を経由して Vibe に返し、Vibe は「最近の注文が 2 つあります:ワイヤレスヘッドフォンの注文 #1234(配送完了)とラップトップスタンドの注文 #1236(処理中)」といった自然言語による回答を生成します。
このアーキテクチャは階層型セキュリティを採用しています。AgentCore Runtime は、JWT の署名と有効期限を検証することでインフラストラクチャ層でリクエストの認証を行います。その後、アプリケーションはこの認証されたアイデンティティを用いて、データアクセスを特定の顧客の注文、レビュー、返品にスコープ制限し、あるユーザーが別のユーザーのデータにアクセスできないようにします。サーバーレス設計は需要に応じてスケールし、ステートレスなコンテナは可用性ゾーン全体に分散されます。
技術的な解説
このセクションでは、プロジェクト構造やツール定義から、Amazon Bedrock AgentCore 上での認証とデプロイに至るまで、Ecommerce MCP サーバーの主要コンポーネントを順を追って解説します。
プロジェクト構成
完全なソースコードと詳細な実装は、この GitHub リポジトリ で確認できます。MCP サーバーを形成する主要コンポーネントとして、以下の 3 つが連携して動作します:
- MCP サーバーアプリケーションは mcp_server/ ディレクトリに存在し、中核となるビジネスロジックを含んでいます。server.py は FastMCP デコレータを使用して 6 つの EC ツールを定義し、HTTP トランスポートを設定します。utils/auth.py は JWT トークンから顧客のアイデンティティを抽出する処理を担当します。utils/dynamodb_client.py は、商品検索、注文作成、レビュー照会などの一般的な操作を処理しつつ、5 つの DynamoDB テーブルに対するクリーンなインターフェースを提供します。
- ecommerce-mcp-cdk/ 内のインフラストラクチャコードは、CDK スacks を使用して AWS リソースを定義しています。DynamoDB スack は効率的な照会に適した適切なインデックスを持つ 5 つのテーブルを作成します。Cognito スack は、カスタム属性と 2 つの OAuth クライアント(一般的な API アクセス用と Mistral AI Studio 用に特別に設定されたもの)を備えたユーザープールをプロビジョニングします。DataLoader スack は、初回デプロイ時にデータベースに現実的なテストデータをシードします。AgentCoreRuntime スack は、DynamoDB、Cognito、Amazon CloudWatch に対する適切な権限を持つ IAM 実行ロールを作成し、コンテナイメージ用の ECR リポジトリをプロビジョニングし、デプロイ中に参照できるよう設定値を SSM Parameter Store に保存します。
- デプロイメント構成は .bedrock_agentcore.yaml ファイルに記述されており、これは agentcore configure コマンドによって生成されます。このファイルは、JWT 検証のために AgentCore が Cognito ユーザープールを見つける場所、接続が許可されているクライアント ID、およびアプリケーションに転送すべきリクエストヘッダーを指定します。
MCP ツールの定義
MCP ツールは、@mcp.tool() デコレータで装飾された Python 関数として定義されます。関数のパラメータ、型ヒント、およびドキュストリング(docstring)がツールスキーマとなります。AI モデルはこのスキーマを読み取り、各ツールの呼び出しタイミングと方法を決定します。
認証を含む注文履歴ツールの定義例を以下に示します:
@mcp.tool()
def get_order_history(limit: int = 10) -> dict:
"""
認証されたユーザーの注文履歴を取得します。
REQUIRES AUTHENTICATION - Authorization ヘッダーを渡してください。
Args:
limit: 返す注文の最大数
Returns:
ステータス、製品詳細、価格情報を含む過去の注文リスト
"""
customer_id = get_current_customer_id()
if customer_id == 'anonymous':
return {"success": False, "error": "Authentication required"}
try:
orders = db.get_customer_orders(customer_id, limit=limit)
# Enrich orders with product names
enriched_orders = []
for order in orders:
product_id = order.get('product_id')
if product_id:
product = db.get_product(product_id)
if product:
order['product_name'] = product.get('name', 'Unknown Product')
order['product_category'] = product.get('category', 'Unknown')
enriched_orders.append(order)
return {"success": True, "order_count": len(enriched_orders), "orders": enriched_orders}
except Exception as e:
return {"success": False, "error": str(e)}
このツールは、いくつかの重要なパターンを示しています。ドキュストリング(注釈)には明確に「認証が必要」と記載されており、AI モデルがこのツールの利用にはログインしたユーザーが必要であることを理解します。最初の数行では顧客の身元を確認し、ユーザーが匿名の場合には即座にエラーを返します。これは、AgentCore Runtime がインフラ層で JWT を既に検証しているにもかかわらず、防御の深さ(ディフェンス・イン・デプス)を実現するものです。このレスポンスは、製品情報と結合することで注文データを拡張し、機械可読な ID と人間に優しいラベルの両方を返します。これにより、AI モデルは追加の呼び出しを行わずに自然言語での応答を生成できるようになります。
サーバーは負荷分散のために AgentCore が要求するステートレス(状態非依存)動作用に構成されます:
mcp = FastMCP("ecommerce-mcp-server")
mcp_app = mcp.http_app(path="/mcp", stateless_http=True)
二層認証
認証は、それぞれ特定の責任を持つ二つのレイヤーに分割されます。AgentCore Runtime が暗号化検証を担い、アプリケーションコードは検証されたトークンを顧客アイデンティティに変換する役割のみを持ちます。
インフラストラクチャ層では、リクエストがアプリケーションに到達する前に AgentCore Runtime がすべての JWT を検証します。Cognito の公開鍵に対して暗号化署名を検証し、発行者、有効期限、クライアント ID 許可リストとの照合を行います。無効なトークンは即座に拒否されます。認証されていないリクエストに対するアプリケーションコードの実行は行われません。
アプリケーション層では、サーバーは検証された JWT を顧客アイデンティティに変換します。OAuth 2.1 トークンにはペイロード内にカスタム属性が含まれていないため、サーバーは Cognito に呼び出しを行い、ユーザーを e コマースデータにリンクさせる custom:customer_id を取得します。異なるトークンタイプを処理するために、二重メソッドアプローチを採用しています:
def extract_customer_id_from_token(access_token: str) -> Optional[str]:
"""
Cognito アクセストークンから custom:customer_id を抽出する。
IAM を介した AdminGetUser を使用して OAuth 2.1 トークンを処理する。
"""
cognito = boto3.client('cognito-idp', region_name=AWS_REGION)
OAuth 2.1 認証コードトークンのための主要メソッド:AdminGetUser
try:
payload = _decode_jwt_payload(access_token)
username = payload.get('username') or payload.get('sub')
user_pool_id = payload.get('iss', '').rstrip('/').split('/')[-1]
if username and user_pool_id:
user_info = cognito.admin_get_user(
UserPoolId=user_pool_id,
Username=username
)
for attr in user_info['UserAttributes']:
if attr['Name'] == 'custom:customer_id':
return attr['Value']
except (ClientError, Exception):
pass
# 管理権限スコープを含むトークンタイプ向けのフォールバックメソッド:get_user()
try:
user_info = cognito.get_user(AccessToken=access_token)
for attr in user_info['UserAttributes']:
if attr['Name'] == 'custom:customer_id':
return attr['Value']
except ClientError:
pass
return None
主要メソッドは、JWT ペイロードをデコードしてユーザー名とユーザープール ID を抽出し、IAM 権限を使用して admin_get_user() を呼び出します。このアプローチは、Mistral Le Chat からの OAuth 2.1 トークンを処理します。フォールバックメソッドは、トークンに管理スコープが含まれている場合に get_user() を直接呼び出します。取得後、顧客 ID はリクエストコンテキストに保存され、認証されたツールによって、データベース操作をそのユーザーのデータにスコープするために使用されます。
注:AgentCore Identity は JWT トークンのカスタムクレームをサポートしており、これにより customer_id などの属性を追加の API 呼び出しなしでアプリケーションに直接転送できます。詳細については、AgentCore Runtime の OAuth 設定 および インバウンド JWT オーサライザー を参照してください。本記事では、OpenID Connect (OIDC) 互換のアイデンティティプロバイダーと連携し、認証フローを段階的に示すため、明示的な admin_get_user() アプローチを使用します。
デプロイメントワークフロー
MCP サーバーのデプロイには、4 つのステップが必要です:インフラストラクチャのプロビジョニング、ユーザー作成、AgentCore の設定、およびコンテナのデプロイです。
インフラストラクチャのプロビジョニング では、AWS CDK を使用して必要なリソースを作成します。ecommerce-mcp-cdk ディレクトリから cdk deploy --all を実行すると、4 つのスタックが順次デプロイされます。このデプロイには約 5 分かかり、次のステップに必要な値(IAM ロールの ARN、ECR リポジトリ URI、Cognito のディスカバリー URL、クライアント ID など)を出力します。これらの値は、迅速な取得のために SSM Parameter Store にも保存されます。
ユーザー作成 では、デモアカウントで Cognito ユーザープールに初期データをセットします。create_cognito_users.py スクリプトは、10 のテストユーザー(demo1@example.com から demo10@example.com)を作成し、それぞれに一意の顧客 ID を割り当てます。これにより、DynamoDB 内の注文やレビューと各ユーザーがリンクされます。
AgentCore の設定は、ランタイムがトークンをどのように検証し、リクエストを転送するかを指示します。agentcore configure コマンドは、必要な設定を含む .bedrock_agentcore.yaml ファイルを作成します:
agentcore configure \
-e server.py \
-p MCP \
-n ecommerce_mcp_server \
-er $ROLE_ARN \
-ecr $ECR_URI \
-ac '{"customJWTAuthorizer":{"discoveryUrl":"$DISC_URL","allowedClients":["$CLIENT_ID","$MISTRAL_CLIENT_ID"]}}' \
-rha "Authorization" \
-r us-west-2 \
--non-interactive生成された YAML ファイル内の重要な設定要素は以下の通りです:
authorizer_configuration:
customJWTAuthorizer:
discoveryUrl: https://cognito-idp.us-west-2.amazonaws.com/us-west-2_xxxxx/.well-known/openid-configuration
allowedClients:
- xxxxxxxxxxxxxxxxxxxxxxxxxx # mcp-client
- yyyyyyyyyyyyyyyyyyyyyyyyyy # mistral-oauth-client
request_header_configuration:
requestHeaderAllowlist:
- AuthorizationdiscoveryUrl は、AgentCore が JWT 検証用の公開鍵を取得する Cognito の OIDC(OpenID Connect)設定エンドポイントを指しています。allowedClients リストは、承認された OAuth クライアントへのアクセスを制限します。requestHeaderAllowlist は、AgentCore に Authorization ヘッダーをアプリケーションへ転送するように指示します。この設定がない場合、リクエストは匿名のものとして扱われてしまいます。
コンテナデプロイメントには、クラウドベースのビルドとデプロイメントをオーケストレーションする agentcore deploy コマンドが使用されます。AgentCore はお客様の AWS アカウント内に CodeBuild プロジェクトを作成し、ソースコードを Amazon Simple Storage Service (Amazon S3) にアップロードした後、CodeBuild 内で ARM64 形式の Docker イメージをビルドします。ローカル環境に Docker をインストールする必要はありません。その後、AgentCore はそのイメージを ECR にプッシュし、Bedrock AgentCore API を呼び出してランタイムを作成・起動します。最初の呼び出しではコンテナが初期化される際に 10〜20 秒の冷間開始(コールドスタート)が発生します。次
原文を表示
When ecommerce teams need faster time-to-market for AI-powered customer experiences, they face weeks of custom integration work that delays launches and increases security risks. Building and connecting a production-ready AI assistant typically requires custom API code for each client, container infrastructure management, and complex authentication. Amazon Bedrock AgentCore and Mistral AI Studio streamline this process. A production-ready ecommerce Model Context Protocol (MCP) server on Amazon Bedrock AgentCore, connected to Mistral AI Studio, streamlines development. The MCP provides standardized integration protocols, AgentCore Runtime manages containers and validates tokens, and Amazon Cognito handles identity.
In this post, you build and connect that server end to end. You will implement MCP tools, set up two-layer JSON Web Token (JWT) authentication, deploy with AWS Cloud Development Kit (AWS CDK), and connect the result to Mistral AI’s Vibe. The post also covers prerequisites, solution architecture, best practices for MCP servers and Vibe connectors, and resource cleanup. The ecommerce server that you build supports product search, order placement, review submission, and returns processing using Amazon DynamoDB for data and Amazon Cognito for identity management.
Amazon Bedrock AgentCore is a platform to build, connect, and optimize AI agents at scale. Within it, AgentCore Runtime is the fully managed serverless component for hosting agent and MCP workloads, with session isolation, long-running request support, built-in JWT validation, and observability, so you don’t manage containers, load balancers, or auth middleware. In this post, you build the MCP server with Python and FastMCP, then deploy it to Runtime for managed hosting. Amazon Cognito manages user identity through OAuth 2.1, keeping each customer’s data isolated. With MCP, you write one server that multiple AI clients connect to, rather than building a separate integration for each client. Mistral AI’s Vibe gives users a conversational interface to the server on web, iOS, and Android.
By the end, you will have a working ecommerce MCP server that authenticates users through Amazon Cognito, scopes data access per customer, and responds to natural language queries from Vibe. Because the server uses the MCP standard, other MCP-compatible clients can also connect to it.
To see the solution in action, watch the following demo. Then, explore the full post for a detailed guide on implementing your own production-ready MCP server and querying it from Vibe.
Prerequisites
You need an AWS account with permissions to create Amazon DynamoDB tables (NoSQL database), Amazon Cognito user pools (user identity, OAuth 2.1), AWS Identity and Access Management (IAM) roles, and Amazon Elastic Container Registry (Amazon ECR) repositories, and to access Amazon Bedrock AgentCore (platform for building and running AI agents). For local development tools, install Python 3.10 or later, Node.js 18 or later, AWS CDK (npm install -g aws-cdk), the AWS Command Line Interface (AWS CLI) configured with credentials, and the Amazon Bedrock AgentCore CLI (pip install bedrock-agentcore). You also need a Mistral AI account with access to Vibe. Docker isn’t required because AgentCore Runtime builds container images in the cloud using AWS CodeBuild.
Solution overview
We show you how to build an ecommerce MCP server that performs real shopping operations: searching products, placing orders, submitting reviews, and processing returns. You work with three layers:
- Application layer: The MCP server is a Python application built with FastMCP, a framework for building MCP servers. It exposes six ecommerce tools through an /mcp endpoint and a /health endpoint for monitoring. AgentCore Runtime runs the server as a container.
- Data layer: Five Amazon DynamoDB tables store ecommerce data: Products, Customers, Orders, Reviews, and Returns. You provision the tables with on-demand capacity for automatic scaling. Global Secondary Indexes support efficient query patterns.
- Security layer: Two-tier authentication that keeps each customer’s data private. Amazon Cognito serves as the identity provider, AgentCore Runtime validates JWT tokens at the infrastructure level, and the application extracts user-specific attributes to scope data access to the authenticated customer.
You deploy the solution using AWS CDK with four infrastructure stacks. The DynamoDBStack creates the five data tables with indexes and configures them for straightforward teardown in development environments. The CognitoStack provisions the user pool with custom attributes for customer identification and creates OAuth 2.1 app clients configured for Mistral AI Vibe integration. The DataLoaderStack uses an AWS Lambda custom resource to seed the database with realistic test data (50 products, 10 customers, 50 orders, reviews, and returns), so you can test the server immediately after deployment. The AgentCoreRuntimeStack creates an IAM role with the required permissions, provisions an ECR repository for the container image, and stores configuration parameters that the deployment command references.

Figure 1. Request flow architecture for the ecommerce MCP server
The diagram illustrates the request flow when a user interacts with the ecommerce MCP server through Mistral Vibe. Before the first request, the user authenticates through an OAuth 2.1 login flow: Vibe opens a Cognito-hosted login page, the user enters their credentials, and Cognito issues a JWT token that Vibe stores for the session. When a user asks, “Show me my recent orders,” the AI model determines it needs to call the get_order_history MCP tool and sends an MCP request over HTTPS to the AgentCore endpoint. The request includes the Bearer JWT token from the OAuth 2.1 login flow. Before reaching the application code, AgentCore’s JWT Validator verifies the token with Cognito User Pool. It checks the signature, expiration, and client authorization, then rejects invalid tokens. Once validated, the request reaches the MCP Server container, which calls Cognito to retrieve the customer ID attribute that links the authenticated user to their ecommerce profile. With the customer identity confirmed, the server queries the relevant DynamoDB tables. The operation is scoped to only that customer’s data to enforce privacy and isolation. The server then sends the structured response back through AgentCore to Vibe, which generates a natural language answer like “You have 2 recent orders: Order #1234 for Wireless Headphones (delivered) and Order #1236 for Laptop Stand (processing).”
This architecture uses layered security. AgentCore Runtime authenticates requests at the infrastructure layer by validating the JWT signature and expiration. The application then uses the authenticated identity to scope data access to that specific customer’s orders, reviews, and returns, so one user can’t access another user’s data. The serverless design scales based on demand, and stateless containers distribute across availability zones.
Technical walkthrough
In this section, we walk through the key components of the ecommerce MCP server, from project structure and tool definitions to authentication and deployment on Amazon Bedrock AgentCore.
Project organization
You can find the complete source code and detailed implementation at this GitHub repo. Three main components work together to form the MCP server:
- The MCP server application lives in the mcp_server/ directory and contains the core business logic. server.py defines the six ecommerce tools using FastMCP decorators and configures the HTTP transport. utils/auth.py handles customer identity extraction from JWT tokens. utils/dynamodb_client.py provides a clean interface to the five DynamoDB tables, handling common operations like product search, order creation, and review queries.
- The infrastructure code in ecommerce-mcp-cdk/ defines the AWS resources using CDK stacks. The DynamoDB stack creates five tables with appropriate indexes for efficient queries. The Cognito stack provisions the user pool with custom attributes and two OAuth clients, one for general API access and one specifically configured for Mistral AI Studio. The DataLoader stack seeds the database with realistic test data on first deployment. The AgentCoreRuntime stack creates the IAM execution role with appropriate permissions for DynamoDB, Cognito, and Amazon CloudWatch, provisions the ECR repository for container images, and stores configuration values in SSM Parameter Store for reference during deployment.
- The deployment configuration is captured in .bedrock_agentcore.yaml, which is generated by the agentcore configure command. This file tells AgentCore where to find the Cognito user pool for JWT validation, which client IDs are authorized to connect, and which request headers should be forwarded to the application.
Defining MCP tools
You define MCP tools as Python functions decorated with @mcp.tool(). The function’s parameters, type hints, and docstring become the tool schema. The AI model reads this schema to decide when and how to call each tool.
Here’s an example showing how the order history tool is defined with authentication:
@mcp.tool()
def get_order_history(limit: int = 10) -> dict:
"""
Get order history for the authenticated user.
REQUIRES AUTHENTICATION - Pass Authorization header.
Args:
limit: Maximum number of orders to return
Returns:
List of past orders with status, product details, and pricing
"""
customer_id = get_current_customer_id()
if customer_id == 'anonymous':
return {"success": False, "error": "Authentication required"}
try:
orders = db.get_customer_orders(customer_id, limit=limit)
# Enrich orders with product names
enriched_orders = []
for order in orders:
product_id = order.get('product_id')
if product_id:
product = db.get_product(product_id)
if product:
order['product_name'] = product.get('name', 'Unknown Product')
order['product_category'] = product.get('category', 'Unknown')
enriched_orders.append(order)
return {"success": True, "order_count": len(enriched_orders), "orders": enriched_orders}
except Exception as e:
return {"success": False, "error": str(e)}This tool demonstrates several important patterns. The docstring clearly states “REQUIRES AUTHENTICATION” so the AI model understands this tool needs a logged-in user. The first lines check the customer identity and immediately return an error if the user is anonymous. This is defense in depth even though AgentCore Runtime has already validated the JWT at the infrastructure layer. The response enriches order data by joining with product information, returning both machine-readable IDs and human-friendly labels so the AI model can generate natural language responses without making additional calls.
You configure the server for stateless operation, which AgentCore requires for load balancing:
mcp = FastMCP("ecommerce-mcp-server")
mcp_app = mcp.http_app(path="/mcp", stateless_http=True)Two-layer authentication
You split authentication across two layers, each with a specific responsibility. AgentCore Runtime owns cryptographic validation. The application code only needs to resolve the validated token into a customer identity.
At the infrastructure layer, AgentCore Runtime validates every JWT before it reaches the application. It verifies the cryptographic signature against Cognito’s public keys and checks the issuer, expiry, and client ID against the allowed list. Invalid tokens are rejected immediately. The application code doesn’t run for unauthenticated requests.
At the application layer, the server resolves the validated JWT into a customer identity. Since OAuth 2.1 tokens don’t include custom attributes in their payload, the server calls Cognito to retrieve the custom:customer_id that links the user to their ecommerce data. It uses a dual-method approach to handle different token types:
def extract_customer_id_from_token(access_token: str) -> Optional[str]:
"""
Extract custom:customer_id from a Cognito access token.
Handles OAuth 2.1 tokens using AdminGetUser via IAM.
"""
cognito = boto3.client('cognito-idp', region_name=AWS_REGION)
# Primary method: AdminGetUser for OAuth 2.1 Authorization Code tokens
try:
payload = _decode_jwt_payload(access_token)
username = payload.get('username') or payload.get('sub')
user_pool_id = payload.get('iss', '').rstrip('/').split('/')[-1]
if username and user_pool_id:
user_info = cognito.admin_get_user(
UserPoolId=user_pool_id,
Username=username
)
for attr in user_info['UserAttributes']:
if attr['Name'] == 'custom:customer_id':
return attr['Value']
except (ClientError, Exception):
pass
# Fallback method: get_user() for token types with admin scope
try:
user_info = cognito.get_user(AccessToken=access_token)
for attr in user_info['UserAttributes']:
if attr['Name'] == 'custom:customer_id':
return attr['Value']
except ClientError:
pass
return NoneThe primary method decodes the JWT payload to extract the username and user pool ID, then calls admin_get_user() using IAM permissions. This approach handles OAuth 2.1 tokens from Mistral Le Chat. The fallback method calls get_user() directly when tokens include admin scope. After it’s retrieved, the customer ID is stored in request context and used by authenticated tools to scope database operations to that user’s data.
Note: AgentCore Identity supports custom claims in JWT tokens, which can forward attributes like customer_id directly to your application without an additional API call. For more information, see Configuring OAuth for AgentCore Runtime and Inbound JWT Authorizer. This post uses the explicit admin_get_user() approach instead, because it works with OpenID Connect (OIDC)-compatible identity providers and shows the full authentication flow step by step.
Deployment workflow
Deploying the MCP server involves four steps: infrastructure provisioning, user creation, AgentCore configuration, and container deployment.
Infrastructure provisioning uses AWS CDK to create the required resources. Running cdk deploy --all from the ecommerce-mcp-cdk directory deploys four stacks in sequence. The deployment takes about 5 minutes and outputs the values needed for the next steps. These include the IAM role ARN, ECR repository URI, Cognito discovery URL, and client IDs. These values are also stored in SSM Parameter Store for quick retrieval.
User creation seeds the Cognito user pool with demo accounts. The create_cognito_users.py script creates ten test users (demo1@example.com through demo10@example.com) and assigns each a unique customer ID that links them to their orders and reviews in DynamoDB.
AgentCore configuration tells the runtime how to validate tokens and forward requests. The agentcore configure command creates the .bedrock_agentcore.yaml file with the necessary settings:
agentcore configure \
-e server.py \
-p MCP \
-n ecommerce_mcp_server \
-er $ROLE_ARN \
-ecr $ECR_URI \
-ac '{"customJWTAuthorizer":{"discoveryUrl":"$DISC_URL","allowedClients":["$CLIENT_ID","$MISTRAL_CLIENT_ID"]}}' \
-rha "Authorization" \
-r us-west-2 \
--non-interactiveThe key configuration elements in the generated YAML file are:
authorizer_configuration:
customJWTAuthorizer:
discoveryUrl: https://cognito-idp.us-west-2.amazonaws.com/us-west-2_xxxxx/.well-known/openid-configuration
allowedClients:
- xxxxxxxxxxxxxxxxxxxxxxxxxx # mcp-client
- yyyyyyyyyyyyyyyyyyyyyyyyyy # mistral-oauth-client
request_header_configuration:
requestHeaderAllowlist:
- AuthorizationThe discoveryUrl points to Cognito’s OIDC configuration endpoint, where AgentCore fetches the public keys for JWT verification. The allowedClients list restricts access to authorized OAuth clients. The requestHeaderAllowlist tells AgentCore to forward the Authorization header to the application. Without this setting, requests would appear anonymous.
Container deployment uses the agentcore deploy command, which orchestrates a cloud-based build and deployment. AgentCore creates a CodeBuild project in your AWS account, uploads your source code to Amazon Simple Storage Service (Amazon S3), and builds an ARM64 Docker image in CodeBuild. You don’t need Docker installed locally. AgentCore then pushes the image to ECR and calls the Bedrock AgentCore API to create and start the runtime. The first invocation has a cold start of 10 to 20 seconds while the container initializes. Subsequen
関連記事
今日のまとめ
AI日報で今日の重要ニュースをまとめ読み