🛠️

Azure AI Foundry AgentでMCPをToolとして使ってみる

に公開

1. Foundry Agent Service が MCP Client に

今回のプレビューで Azure AI Foundry Agent Service は正式に MCP クライアント対応しました。

  • セルフホストでも SaaS でも … 任意の MCP サーバーを数秒でインポート
  • 自動更新 … サーバー側のツール更新を自動で追従
  • エンタープライズ機能 … 例: Bring Your Own thread storage など

2. コードサンプルで試す

以下は MCP サーバーをツールとして追加し、スレッドを実行してレスポンスを取得 するまでの最小サンプルです。

前提
PROJECT_ENDPOINTMODEL_DEPLOYMENT_NAME は環境に合わせて設定
サクッと試す際はBasic Agent setup を新規デプロイしてから検証するのが無難

https://learn.microsoft.com/en-us/azure/ai-foundry/agents/environment-setup#deployment-options

Remote MCP Server を利用する際の主要ポイント

1. 既存 MCP サーバーの準備が必要

Azure AI Foundry Agent Service で MCP ツールを利用する場合、すでに稼働している MCP サーバーエンドポイント(例: MicrosoftDocs Server など)を自分で用意する必要があります。

2.ラン作成時に tool_resources でヘッダーを渡す

tool_label: 作成時のラベル
headers: MCP サーバーが要求するヘッダー(例: 認証トークン等)

3. 利用できる開発スタック

サポート状況 Python SDK C# SDK JavaScript SDK REST API Basic Agent Setup Standard Agent Setup
Azure AI Foundry - - - ✔️ ✔️ ✔️

4. サポートリージョン

いつも同じみeastus2とかが最近の新機能では初期対象外になってました。
westus, westus2, uaenorth, southindia, switzerlandnorth

随時更新される可能性もあるので、試す前に以下を参照することを推奨します。
https://learn.microsoft.com/en-us/azure/ai-foundry/agents/how-to/tools/model-context-protocol

ステップ 1 — パッケージをインポート

import time
import json

from azure.ai.agents.models import MessageTextContent, ListSortOrder
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential

ステップ 2 — AI Project Client とエージェント生成

project_client = AIProjectClient(
    endpoint=PROJECT_ENDPOINT,
    credential=DefaultAzureCredential()
)

with project_client:
    agent = project_client.agents.create_agent(
        model=MODEL_DEPLOYMENT_NAME, #gpt-4.1がおすすめ
        name="my-mcp-agent",
        instructions=(
            "You are a helpful assistant. "
            "Use the tools provided to answer the user's questions. "
            "Be sure to cite your sources."
        ),
        tools=[
             {
                "type": "mcp",
                "server_label": "MicrosoftDocs",
                "server_url": "https://learn.microsoft.com/api/mcp",
                "allowed_tools": ["never"]   
            }
        ]
    )
    print(f"Created agent, ID: {agent.id}")

ステップ 3 — スレッド・メッセージ・ラン作成

thread = project_client.agents.threads.create()
print(f"Created thread, ID: {thread.id}")

message = project_client.agents.messages.create(
    thread_id=thread.id,
    role="user",
    content="Azure AI の最新情報は?"
)
print(f"Created message, ID: {message.id}")

run = project_client.agents.runs.create(
    thread_id=thread.id,
    agent_id=agent.id
)

ステップ 4 — 実行&レスポンス取得

# queued / in_progress / requires_action 中はポーリング
while run.status in ["queued", "in_progress", "requires_action"]:
    time.sleep(1)
    run = project_client.agents.runs.get(thread_id=thread.id, run_id=run.id)
    print(f"Run status: {run.status}")

if run.status == "failed":
    raise RuntimeError(run.last_error)

# 実行ステップを列挙
for step in project_client.agents.run_steps.list(thread_id=thread.id, run_id=run.id):
    print(f"Step: {step.id}, status: {step.status}, type: {step.type}")
    if step.type == "tool_calls":
        print(json.dumps(step.step_details.tool_calls, indent=2))

# メッセージを取得して表示
for msg in project_client.agents.messages.list(thread_id=thread.id, order=ListSortOrder.ASCENDING):
    content = msg.content[-1]
    if isinstance(content, MessageTextContent):
        print(f"{msg.role}: {content.text.value}")

3. デプロイ後の動き

実際に利用したのはおなじみ 🌟Microsoft Learn Docs MCP Server🌟
https://github.com/microsoftdocs/mcp

試しに、以下で質問してみました。

Azure openAI Serviceの2025年6月の更新内容を教えてください。またその際の該当リンクを教えてください。

回答はこちら👇

### 回答
2025年6月のAzure OpenAI Serviceの主な更新内容は、「codex-mini」と「o3-pro」モデルのリリースです。これらのモデルが新たに利用可能となりました。詳細については、「Reasoningモデルの利用開始ガイド」をご参照ください。

### ドキュメント抜粋 (原文 & 日本語訳)
> ## June 2025
> ### codex-mini & o3-pro models released
> 1. `codex-mini` and `o3-pro` are now available. To learn more, see the [getting started with reasoning models page](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/reasoning)

> 2025年6月
> codex-miniおよびo3-proモデルがリリースされました。詳細については、「Reasoningモデルの利用開始ガイド」をご覧ください。

### ドキュメントリンク
- https://learn.microsoft.com/en-us/azure/ai-services/openai/whats-new
- https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/reasoning

蛇足ですが、この Microsoft Learn Docs MCP Server のおかげで回答を作成する際に、根拠となる原文の英語と日本語訳、そしてそのドキュメントリンクを送ってくれていて、非常に日々の調べ物の手間が省けます。最新情報は英語ドキュメントから更新されるのですが、英語苦手なので日本語訳も欲しいという英語への苦しみから上記のような回答になるようにしてます。

Azure AI Foundry Portal からも確認

IDも同じで反映されてますね。

プレイグランドで利用することもできます。素晴らしい!

ToolとしてMPCを読んでいることもログからわかります。

4. 最後に運用上の注意事項

  • ⚠️ Microsoft 以外のサービスと接続する場合の責任範囲
  • 利用条件は 利用者とサービスプロバイダー間の契約 に従う
  • MCP Server を通じてプロンプトやコンテキストが第三者に送信される可能性
  • 使用料・データ保持ポリシーは要確認
  • 信頼できるプロバイダーがホストする MCP Server を推奨

またMCP toolはカスタムヘッダーをサポートしているため、必要な認証スキームを使用してこれらのサーバーに接続したり、MCP Serverに必要な他のヘッダーを渡したりできます。
ヘッダーを指定できるのは、API key、OAuth access、その他の認証情報などを各実行でリクエストに直接含めることだけです。 最も一般的に使用されるヘッダーは、認証ヘッダーです。
MCP の使用の詳細については、以下を参照してください。
server_label server_url tool_resources

セキュリティのベストプラクティス

MCP 実装におけるセキュリティリスクを理解し、適切に軽減することが重要です。以下のリソースも必ず参照してください。

📎引用

https://devblogs.microsoft.com/foundry/announcing-model-context-protocol-support-preview-in-azure-ai-foundry-agent-service/

おまけ

個人的に使っているプロンプトで触ってみたい方は以下をコピーしてお使いください。

You are an AI assistant that must **always** ground your answers in official Microsoft documentation via the Microsoft Docs MCP Server.

### Objectives
1. **Retrieve authoritative content**  
   - Use the MCP Server endpoints as your primary and only knowledge source.  
   - When a user asks a question, issue an MCP search query, select the most relevant passages, and store their URLs.

2. **Compose responses per question**  
   For each individual question in the user’s message, output the following three blocks in this exact order:  
   1. **回答** – A clear, concise, and complete answer in the user’s language.  
   2. **ドキュメント抜粋 (原文 & 日本語訳)** –  
      - Start with `> ` and paste the exact English sentence(s) you relied on.  
      - Add an empty line, then another `> ` block containing your Japanese translation.  
   3. **ドキュメントリンク** –  
      - Bullet list of the full documentation URLs you quoted from.  
      - If you quoted multiple passages **from the same page**, list that URL once after the final excerpt for that page; otherwise place the link immediately after each excerpt.

3. **Citation discipline**  
   - Every factual claim in **Answer** must be supported by at least one excerpt.  
   - Cite only Microsoft-owned domains.  
   - Do **not** cite non-Microsoft pages, social posts, blogs, or unofficial wikis.

4. **Formatting rules**  
   - Use Markdown.  
   - Never nest code blocks inside quotes.  
   - Separate the three blocks and `###` headings.  
   - **In the output format, do not insert any empty line or line break after any ### heading. The content for each section must start immediately on the next line, directly after the heading, without any blank line in between. If a blank line appears after a ###, it is a formatting error.**.
   - Produce *no* extra commentary outside the mandated blocks.

5. **Fallback behaviour**  
   - If the MCP Server returns no results, apologize once and ask the user to clarify or narrow their request.  
   - Do **not** hallucinate information; respond only with validated content or a clarification request.

6. **Language**  
   - Mirror the user’s language (Japanese or English).  
   - Maintain polite, professional tone in Japanese; plain but courteous tone in English.
Microsoft (有志)

Discussion