MCP ツールを使用して、Foundry エージェントを モデル コンテキスト プロトコル (MCP) サーバーに接続します。 この接続により、外部ツールとデータ ソースを使用してエージェントの機能が拡張されます。 リモート MCP サーバー エンドポイントに接続することで、エージェントの Foundry モデルは、Foundry Agent Service などの MCP と互換性のあるクライアントが使用できる開発者や組織がホストするツールにアクセスできます。
MCP は、アプリケーションが大規模言語モデル (LLM) にツールとコンテキスト データを提供する方法を定義するオープン標準です。 これにより、外部ツールをモデル ワークフローに一貫性のあるスケーラブルに統合できます。
ヒント
ツールボックスを使用してこのツールを追加することを検討 してください。 ツールボックスを使用すると、エージェントとランタイム間でツールを再利用できるほか、マネージド MCP エンドポイントを介して資格情報の管理、バージョン管理、ポリシーの適用を一元化できます。 ツールボックスの クイック スタートを参照してください。
この記事では、次の方法について説明します。
- リモート MCP サーバーをツールとして追加します。
- プロジェクト接続を使用して MCP サーバーに対して認証します。
- MCP ツールの呼び出しを確認して承認します。
- MCP 統合に関する一般的な問題のトラブルシューティングを行います。
GitHub Copilotなどのコーディング エージェントを使用する場合、Microsoft Foundry Skill は、MCP ツール接続、認証、承認動作、トラブルシューティング手順の構成に役立ちます。
前提 条件
開始する前に、次の内容を確認してください。
アクティブな Microsoft Foundry プロジェクトを含むAzure サブスクリプション。
エージェントを作成およびテストするための Foundry プロジェクトの Foundry ユーザー ロール。 MCP 認証用のproject接続を作成する場合は、そのprojectに対する Foundry Project Manager ロールも必要です。
Important
Foundry RBAC ロールの名前が最近変更されました。 Foundry User, Foundry Owner, Foundry Account Owner、および Foundry Project Manager は、以前は、AZURE AI ユーザー、Azure AI 所有者、Azure AI アカウント所有者、および AZURE AI Project Manager という名前でした。 名前の変更がロールアウトされている間、以前の名前が表示される場合があります。ロール ID とコア アクセス許可は、名前の変更によって変更されません。
言語の最新の SDK パッケージ。 .NET SDK は現在プレビュー段階です。 インストールの詳細については、 クイック スタートを参照してください。
Azure認証用に構成された資格情報 (
DefaultAzureCredentialなど)。リモート MCP サーバー エンドポイント (
https://api.githubcopilot.com/mcpにある GitHub の MCP サーバーなど) へのアクセス。
タスクを選択する
| Task | Path |
|---|---|
| エージェントを接続し、最初に成功したツール呼び出しを確認する | 接続に従い、ルートを承認、確認、クリーンアップします。 |
| 資格情報または ID ベースのアクセスを追加する | セカンダリ:認証を構成します。 |
| プライベート MCP エンドポイントに接続する | セカンダリ:パブリックエンドポイントとプライベートエンドポイントの要件を確認します。 |
| バックグラウンド モードで長い操作を実行する | セカンダリ:実行時間の長い操作を構成します。 |
| ストリーミングとタイムアウトの動作について | セカンダリ:既知の制限事項を確認します。 |
| サーバー オプションを構成するか、ローカル サーバーをホストする | セカンダリ:MCP 接続を設定 するか 、ローカル MCP サーバーをホストします。 |
MCP 統合のしくみの概念の詳細については、「 しくみ」を参照してください。
使用サポート
次の表に、MCP 接続の SDK とセットアップのサポートを示します。
| Microsoft Foundry のサポート | Python SDK | C# SDK | JavaScript SDK | Java SDK | REST API | 基本的なエージェントのセットアップ | 標準エージェントのセットアップ |
|---|---|---|---|---|---|---|---|
| ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
パブリックおよびプライベート MCP サーバー エンドポイント
Agent Service では、パブリックとプライベートの両方の MCP サーバー エンドポイントがサポートされます。
- パブリック エンドポイント: パブリックにアクセスできるリモート MCP サーバーに接続します。 このオプションは、Basic エージェントと Standard エージェントの両方のセットアップで機能します。
- プライベート エンドポイント: パブリック インターネットに公開されていない MCP サーバーに接続します。 プライベート MCP には 、プライベート ネットワークのセットアップ と、仮想ネットワーク内の専用 MCP サブネットが必要です。
プライベート MCP サーバーの場合は、Microsoft.App/environments に委任された専用 MCP サブネットに内部専用イングレスを使用して、Azure Container Appsに MCP サーバーをデプロイします。 まず、 19-private-network-agents-tools-setup テンプレートを使用します。MCP サブネットや 11-private-network-basic-project を含む必要なネットワーク インフラストラクチャをプロビジョニングします (独自のリソースを持ち込む必要がない場合)。
ネットワーク分離環境でのツールのサポートの詳細については、ネットワーク分離を 使用したエージェント ツールに関するページを参照してください。
Foundry ツールボックスを MCP エンドポイントとして使用する
Foundry ツールボックスを使用すると、Web Search、コード インタープリター、ファイル検索、Azure AI 検索、MCP サーバー、OpenAPI ツール、エージェント間接続など、複数のツールを 1 つの MCP 互換エンドポイントにバンドルできます。 すべてのエージェントで各ツールを個別に構成する代わりに、Foundry にツールボックスを作成し、標準の mcp ツール構成 (server_url と server_label) を使用して、エージェントをツールボックス エンドポイントにポイントします。
ツールボックス エンドポイントは MCP と互換性があるため、MCP サーバーを使用できるランタイムもツールボックスを使用できます。 この互換性には、Foundry Agent Service、Microsoft Agent Framework、LangGraph、GitHub Copilot SDK、およびその他の MCP 対応クライアントが含まれます。 エージェント コードを変更することなく、ツールボックスのツールを追加、削除、または再構成できます。
セットアップ手順については、「 Foundry ツールボックスの作成と使用」を参照してください。
ツールボックス MCP エンドポイントは、プレビュー段階の MCP タスクを通じて実行時間の長い操作をサポートします。 実行時間の長いツールを使用するには、エージェント ハーネスで MCP タスクがサポートされていることを確認します。
ツールボックス MCP の認証と構成
シナリオに一致する認証の種類を使用して MCP サーバーのプロジェクト接続を作成し、最小限のツールボックス YAML からそれを参照します。
ステップ 1. 接続の作成
プロジェクト エンドポイントをエクスポートし、 azd ai コマンドのアクティブなプロジェクトとして設定します。
PROJECT_ENDPOINT="https://<account>.services.ai.azure.com/api/projects/<project>"
azd ai project set $PROJECT_ENDPOINT
必要な認証バリアントを選択します。
# No auth — public MCP server
azd ai connection create my-mcp-conn \
--kind remote-tool \
--target https://learn.microsoft.com/api/mcp \
--auth-type none
# Custom-keys header (for example, GitHub PAT)
azd ai connection create my-mcp-conn \
--kind remote-tool \
--target https://api.githubcopilot.com/mcp/ \
--auth-type custom-keys \
--custom-key "Authorization=******"
# OAuth — bring your own app registration
azd ai connection create my-mcp-conn \
--kind remote-tool \
--target https://your-mcp-server.example.com \
--auth-type oauth2 \
--authorization-url https://auth.example.com/authorize \
--token-url https://auth.example.com/token \
--client-id <oauth-client-id> \
--client-secret <oauth-client-secret> \
--scopes "<scope1> <scope2>"
# User Entra token (managed user identity passthrough; for example, Microsoft Fabric)
azd ai connection create my-mcp-conn \
--kind remote-tool \
--target https://api.fabric.microsoft.com/v1/mcp/fabricaihub/integrations/m365 \
--auth-type user-entra-token \
--audience https://analysis.windows.net/powerbi/api
# Project managed identity — the project's system-assigned MI
azd ai connection create my-mcp-conn \
--kind remote-tool \
--target https://<resource>.cognitiveservices.azure.com/language/mcp \
--auth-type project-managed-identity \
--audience https://cognitiveservices.azure.com
# Agentic identity — the agent's per-project identity
azd ai connection create my-mcp-conn \
--kind remote-tool \
--target https://<resource>.cognitiveservices.azure.com/language/mcp \
--auth-type agentic-identity \
--audience https://cognitiveservices.azure.com
--auth-type |
その他のフラグ |
|---|---|
none |
— |
custom-keys |
--custom-key "Header=Value" (反復可能) |
oauth2 |
--authorization-url、--token-url、--client-id、--client-secret、--scopes |
user-entra-token |
--audience <entra-audience> |
project-managed-identity |
--audience <entra-audience> (任意) |
agentic-identity |
--audience <entra-audience> |
ID ベースの認証 (user-entra-token、 project-managed-identity、 agentic-identity) の場合は、ツールボックスを呼び出す前に、対応するプリンシパルにターゲット リソースに必要な RBAC ロールを割り当てます。
ステップ 2. ツールボックスを定義する
# my-toolbox.yaml
description: MCP server tools
connections:
- name: my-mcp-conn
ステップ 3. ツールボックスを作成する
azd ai toolbox create my-toolbox --from-file my-toolbox.yaml
ユーザーがプロジェクトで OAuth ベースの MCP を使用してツールボックスを初めて呼び出した場合、MCP エンドポイントは同意 URL を持つ CONSENT_REQUIRED エラー (コード -32006) を返します。
{
"error": {
"code": -32006,
"message": "User consent is required. Please visit: https://..."
}
}
このエラーは想定されています。 ブラウザーで同意 URL を開き、OAuth 承認フローを完了してから、エージェントの呼び出しを再試行します。 後続の呼び出しは、再プロンプトを表示せずに成功します。
認証
セカンダリ パス: MCP サーバーで資格情報または ID ベースのアクセスが必要な場合は、最初の成功ルートの後に認証を構成します。
多くの MCP サーバーでは認証が必要です。
Foundry Agent Service では、アプリで資格情報をハードコーディングする代わりに、プロジェクト接続を使用して、API キーやベアラー トークンなどの認証の詳細を格納します。
キーベース、Microsoft Entra ID、OAuth ID パススルーなど、サポートされている認証オプションについては、MCP サーバー認証に関するページを参照してください。
メモ
project_connection_idをプロジェクト接続の ID に設定します。
ヒント
Add Tools カタログを使用して Azure DevOps MCP Server (プレビュー) を追加すると、組織の接続手順中にAzure DevOpsに対して認証が行われ、認証がプロジェクト接続として格納されます。 組織を接続する際は、必要最小限の特権アクセスを用い、スコープを見直してください。
Foundry Toolbox MCP エンドポイントを使用すると、ツールボックスによって認証が一元的に管理されます。 ツールボックスは、バンドル内のすべてのツールについて、実行時に資格情報の挿入、トークンの更新、およびポリシーの適用を処理します。 エージェントは、DefaultAzureCredential などのMicrosoft Entra資格情報を使用してツールボックス エンドポイント自体に対して認証を行い、個々のツール資格情報を各エージェントで渡す必要はありません。 ツールボックス認証の構成については、「 ツールボックスの前提条件」を参照してください。
Microsoft サービスおよびサーバー以外の使用に関する考慮事項
接続された非Microsoft サービスを使用する場合、お客様とサービス プロバイダーの間の条件が適用されます。 Microsoft以外のサービスに接続すると、プロンプト コンテンツなどのデータの一部を非Microsoft サービスに渡すか、アプリケーションが非Microsoft サービスからデータを受信する可能性があります。 お客様は、Microsoft サービスおよびデータ以外の使用と、その使用に関連する料金について責任を負います。
Microsoftではなく、サード パーティは、この記事で説明する MCP ツールで使用することを決定したリモート MCP サーバーを作成します。 Microsoftは、これらのサーバーをテストまたは検証しません。 Microsoftは、リモート MCP サーバーの使用に関して、お客様または他のユーザーに対して一切の責任を負いません。
Foundry Agent Service に追加する MCP サーバーを慎重に確認して追跡します。 プロキシではなく、信頼されたサービス プロバイダー自体によってホストされているサーバーに依存します。
MCP ツールを使用すると、リモート MCP サーバーが必要とする可能性がある認証キーやスキーマなどのカスタム ヘッダーを渡すことができます。 リモート MCP サーバーと共有するすべてのデータを確認し、監査のためにデータをログに記録します。 データの保持と場所に関するMicrosoft以外のプラクティスに注意してください。
メモ
Foundry ツールボックスは、サードパーティの MCP サーバーとは異なります。 ツールボックスは、Microsoft Foundry プロジェクト内で作成および管理する組織が管理するリソースです。 ただし、ツールボックスのコンテンツをキュレーションする場合、ツールの選択、データ処理、コンプライアンスは引き続き担当します。
ベスト プラクティス
ツールの使用方法に関する一般的なガイダンスについては、「 Foundry Agent Service Microsoft でツールを使用するためのベスト プラクティスを参照してください。
MCP サーバーを使用する場合は、次のプラクティスに従います。
-
allowed_toolsを使用して、ツールの許可リストを使用します。 - リモート MCP サーバーからのツールの説明、注釈、結果を信頼できない入力として扱います。 これらには、間接的なプロンプト挿入命令を含めることができます。
- リスクの高い操作 、特にデータを書き込んだりリソースを変更したりするツールに対して承認が必要です。
- 承認する前に、要求されたツール名と引数を確認します。
- サーバーのオペレーター、公開されているツール、または動作が変更されたときに、
allowed_tools、承認設定、接続のアクセス許可を確認します。 - 監査とトラブルシューティングのための承認とツール呼び出しをログに記録します。
ヒント
Add Tools カタログを使用して Azure DevOps MCP サーバーを追加すると、ツールの選択構成は、この記事で説明する allowed_tools 動作にマップされます。 カタログ UI でツールのサブセットを選択することは、コードで allowed_tools リストを指定することと同じです。
最初の成功ルート: 接続、承認、検証、クリーンアップ
選択した言語の prompt-agent サンプルを使用します。 サンプルにエージェントの種類のタブがある場合は、[ エージェントのプロンプト] を選択します。 このルートでは、最初の実行が 1 つのタスク (1 つの MCP サーバーの接続、1 つのツールの呼び出し、結果の検査) に集中し続けます。
-
接続:
require_approvalをalwaysに設定して MCP ツールを構成し、エージェントにアタッチします。 - 承認: サンプルを実行し、要求されたサーバー、ツール、引数を確認し、予想される呼び出しのみを承認します。
- 確認: 予想される出力に示すように、最終的な応答に MCP ツールによって返される情報が含まれていることを確認します。
- クリーンアップ: サンプルのクリーンアップ操作を実行します。 prompt-agent サンプルではエージェントのバージョンが削除され、TypeScript サンプルでは会話も削除されます。
MCP ツールを使用してPythonでエージェントを作成する
次のコード サンプルを使用して、エージェントを作成し、関数を呼び出します。 .NET SDK は現在プレビュー段階です。 詳細については、 クイック スタート を参照してください。
次の例では、GitHub MCP サーバーをツールボックスに追加し、そのツールボックスをエージェントにアタッチする方法を示します。 Azure AI Projects SDK を使用してサーバー側プロンプト エージェントを作成する場合は Prompt Agents を選択します。エージェント フレームワーク を使用してエフェメラルなインプロセス エージェントを作成するには、FoundryChatClient を選択します。
エージェントに指示を促す
import json
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition, MCPTool
from openai.types.responses.response_input_param import McpApprovalResponse, ResponseInputParam
# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
MCP_CONNECTION_NAME = "my-mcp-connection"
# Create clients to call Foundry API
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
# [START tool_declaration]
tool = MCPTool(
server_label="api-specs",
server_url="https://api.githubcopilot.com/mcp",
require_approval="always",
project_connection_id=MCP_CONNECTION_NAME,
)
# [END tool_declaration]
# Create a prompt agent with MCP tool capabilities
agent = project.agents.create_version(
agent_name="MyAgent7",
definition=PromptAgentDefinition(
model="gpt-5-mini",
instructions="Use MCP tools as needed",
tools=[tool],
),
)
print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})")
# Create a conversation to maintain context across multiple interactions
conversation = openai.conversations.create()
print(f"Created conversation (id: {conversation.id})")
# Send initial request that will trigger the MCP tool
response = openai.responses.create(
conversation=conversation.id,
input="What is my username in my GitHub profile?",
extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)
# Process any MCP approval requests that were generated
input_list: ResponseInputParam = []
for item in response.output:
if item.type == "mcp_approval_request" and item.id:
print("MCP approval requested")
print(f" Server: {item.server_label}")
print(f" Tool: {getattr(item, 'name', '<unknown>')}")
print(
f" Arguments: {json.dumps(getattr(item, 'arguments', None), indent=2, default=str)}"
)
# Approve only after you review the tool call.
# In production, implement your own approval UX and policy.
should_approve = (
input("Approve this MCP tool call? (y/N): ").strip().lower() == "y"
)
input_list.append(
McpApprovalResponse(
type="mcp_approval_response",
approve=should_approve,
approval_request_id=item.id,
)
)
# Send the approval response back to continue the agent's work
response = openai.responses.create(
input=input_list,
previous_response_id=response.id,
extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)
print(f"Response: {response.output_text}")
# Clean up resources by deleting the agent version
project.agents.delete_version(agent_name=agent.name, agent_version=agent.version)
print("Agent deleted")
予期される出力
次の例は、サンプルの実行時に予想される出力を示しています。
Agent created (id: <agent-id>, name: MyAgent7, version: 1)
Created conversation (id: <conversation-id>)
Response: Your GitHub username is "example-username".
Agent deleted
ホスト型エージェント
このサンプルでは、Microsoft Agent Framework からのFoundryChatClientを使用し、GitHub MCP サーバーを含むツールボックスを作成し、FoundryToolboxを使用してツールボックス エンドポイントをホストされたエージェントにアタッチします。
pip install agent-framework-foundryでパッケージをインストールし、FOUNDRY_PROJECT_ENDPOINTとFOUNDRY_MODEL環境変数を設定し、az loginでサインインします。
import asyncio
from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient, FoundryToolbox
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import MCPToolboxTool
from azure.identity import AzureCliCredential
PROJECT_ENDPOINT = "https://<account>.services.ai.azure.com/api/projects/<project>"
MCP_CONNECTION_NAME = "my-mcp-connection"
async def main() -> None:
credential = AzureCliCredential()
# 1. Add the GitHub MCP server to a toolbox.
project = AIProjectClient(endpoint=PROJECT_ENDPOINT, credential=credential)
server_tool = MCPToolboxTool(
server_label="api-specs",
server_url="https://api.githubcopilot.com/mcp",
require_approval="always",
project_connection_id=MCP_CONNECTION_NAME,
)
toolbox = project.toolboxes.create_version(
name="mcp-server-toolbox",
description="Toolbox with the GitHub MCP server",
tools=[server_tool],
)
# 2. The toolbox exposes an MCP-compatible endpoint.
TOOLBOX_MCP_URL = (
f"{PROJECT_ENDPOINT}/toolboxes/{toolbox.name}"
f"/versions/{toolbox.version}/mcp?api-version=v1"
)
# 3. Attach the toolbox to the hosted agent as an MCP tool.
,
timeout=120.0,
)
toolbox_tool = FoundryToolbox(credential, url=TOOLBOX_MCP_URL)
agent = Agent(
client=FoundryChatClient(credential=credential),
instructions="You are a helpful assistant that uses your MCP tool "
"to help with Microsoft documentation questions.",
tools=[toolbox_tool],
)
result = await agent.run("What is Microsoft Agent Framework?")
print(f"Agent: {result.text}")
if __name__ == "__main__":
asyncio.run(main())
予期される出力
エージェントは、ツールボックス エンドポイントを介して Microsoft Learn MCP サーバーを呼び出し、ドキュメントベースのテキストを返します。
Agent: Microsoft Agent Framework is an open-source framework for building, orchestrating, and deploying AI agents ...
完全なツールボックスのホステッド エージェント パターンについては、「 ホストされたエージェントでツールボックスを使用する」を参照してください。
MCP ツールを使用してエージェントを作成する
次の例では、リモート MCP サーバーをツールボックスに追加し、そのツールボックスをエージェントにアタッチする方法を示します。 Prompt Agents を選択して、Azure AI Projects SDK を使用してサーバー側プロンプト エージェントを作成するか、Hosted Agents を使用して、Microsoft Agent Framework を使用してエフェメラルなインプロセス エージェントを構築します。
エージェントに指示を促す
この例では、同期メソッドを使用してエージェントを作成します。 非同期メソッドについては、GitHubのリポジトリのAzure SDKの
using System;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
var projectEndpoint = "your_project_endpoint";
// Create project client to call Foundry API
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Create Agent with the `MCPTool`. Note that in this scenario
// GlobalMcpToolCallApprovalPolicy.AlwaysRequireApproval is used,
// which means that any calls to the MCP server must be approved.
DeclarativeAgentDefinition agentDefinition = new(model: "gpt-5-mini")
{
Instructions = "You are a helpful agent that can use MCP tools to assist users. Use the available MCP tools to answer questions and perform tasks.",
Tools = { ResponseTool.CreateMcpTool(
serverLabel: "api-specs",
serverUri: new Uri("https://gitmcp.io/Azure/azure-rest-api-specs"),
toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.AlwaysRequireApproval
)) }
};
AgentVersion agentVersion = projectClient.AgentAdministrationClient.CreateAgentVersion(
agentName: "myAgent",
options: new(agentDefinition));
// If the tool approval is required, the response item is
// of `McpToolCallApprovalRequestItem` type and contains all
// the information about tool call. This example checks that
// the server label is "api-specs" and approves the tool call.
// All other calls are denied because they should not occur for
// the current configuration.
ProjectResponsesClient responseClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentVersion.Name);
CreateResponseOptions nextResponseOptions = new([ResponseItem.CreateUserMessageItem("Please summarize the Azure REST API specifications README")]);
ResponseResult latestResponse = null;
while (nextResponseOptions is not null)
{
latestResponse = responseClient.CreateResponse(nextResponseOptions);
nextResponseOptions = null;
foreach (ResponseItem responseItem in latestResponse.OutputItems)
{
if (responseItem is McpToolCallApprovalRequestItem mcpToolCall)
{
nextResponseOptions = new CreateResponseOptions()
{
PreviousResponseId = latestResponse.Id,
};
if (string.Equals(mcpToolCall.ServerLabel, "api-specs"))
{
Console.WriteLine($"Approval requested for {mcpToolCall.ServerLabel} (tool: {mcpToolCall.ToolName})");
Console.Write("Approve this MCP tool call? (y/N): ");
bool approved = string.Equals(Console.ReadLine(), "y", StringComparison.OrdinalIgnoreCase);
nextResponseOptions.InputItems.Add(ResponseItem.CreateMcpApprovalResponseItem(approvalRequestId: mcpToolCall.Id, approved: approved));
}
else
{
Console.WriteLine($"Rejecting unknown call {mcpToolCall.ServerLabel}...");
nextResponseOptions.InputItems.Add(ResponseItem.CreateMcpApprovalResponseItem(approvalRequestId: mcpToolCall.Id, approved: false));
}
}
}
}
// Output the final response from the agent.
Console.WriteLine(latestResponse.GetOutputText());
// Clean up resources by deleting the agent version.
projectClient.AgentAdministrationClient.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
予期される出力
次の例は、サンプルの実行時に予想される出力を示しています。
Approval requested for api-specs...
Response: The Azure REST API specifications repository contains the OpenAPI specifications for Azure services. It is
organized by service and includes guidelines for contributing new specifications. The repository is intended for use by developers building tools and services that interact with Azure APIs.
ホスト型エージェント
このサンプルでは、Azure AI Projects SDK を使用して MCP サーバー ツールボックスを作成し、Microsoft Agent Framework AddFoundryToolboxes統合を使用して、ツールボックス ツールをホストされたエージェントに公開します。
AZURE_AI_PROJECT_ENDPOINT、AZURE_OPENAI_ENDPOINT、およびAZURE_AI_MODEL_DEPLOYMENT_NAME環境変数を設定し、az loginを使用してサインインします。
using Azure.AI.AgentServer.Responses;
using Azure.AI.AgentServer.Responses.Models;
using Azure.AI.OpenAI;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Foundry.Hosting;
using Microsoft.Extensions.DependencyInjection;
using OpenAI.Chat;
string projectEndpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT")
?? "https://<account>.services.ai.azure.com/api/projects/<project>";
string openAiEndpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-5-mini";
DefaultAzureCredential credential = new();
// 1. Create the MCP server tool and add it to a toolbox.
AIProjectClient projectClient = new(endpoint: new Uri(projectEndpoint), tokenProvider: credential);
McpTool mcpTool = ResponseTool.CreateMcpTool(
serverLabel: "api-specs",
serverUri: new Uri("https://gitmcp.io/Azure/azure-rest-api-specs"),
toolCallApprovalPolicy: new McpToolCallApprovalPolicy(
GlobalMcpToolCallApprovalPolicy.AlwaysRequireApproval));
ToolboxVersion toolboxVersion = projectClient.AgentAdministrationClient
.GetAgentToolboxes().CreateToolboxVersion(
toolboxName: "mcp-server-toolbox",
tools: [ProjectsAgentTool.AsProjectTool(mcpTool)],
description: "Toolbox with the GitHub MCP server");
// Create the hosted agent and register the toolbox integration.
AIAgent agent = projectClient.AsAIAgent(
model: deploymentName,
instructions: "You are a helpful assistant with access to the toolbox tools.",
name: "hosted-toolbox-agent");
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddFoundryResponses(agent);
builder.Services.AddFoundryToolboxes(credential, toolboxVersion.Name);
var app = builder.Build();
app.MapFoundryResponses();
app.Run();
予期される出力
ホストされるエージェントは、呼び出されると、ツールボックス エンドポイントを介して Microsoft Learn MCP サーバーに対してクエリを実行し、ドキュメント スニペットと回答を確認します。
User: How does one create an Azure storage account using the az CLI?
Agent: To create an Azure storage account using the az CLI, run: `az storage account create --name <name> --resource-group <rg> --location <region> --sku Standard_LRS` ...
管理されている .NET Agent Framework の統合については、「ホストされたエージェントでツールボックスを使用する」を参照してください。
プロジェクト接続認証で MCP ツールを使用してエージェントを作成する
この例では、ツールボックス内の GitHub MCP サーバーに対して認証を行い、ツールボックス MCP エンドポイントをエージェントにアタッチする方法について説明します。 この例では、同期メソッドを使用してツールボックスとエージェントを作成します。 非同期メソッドについては、GitHubのリポジトリのAzure SDKの
プロジェクト接続を設定する
サンプルを実行する前に、次の手順を実行します。
- GitHub プロファイルにサインインします。
- 右上隅にあるプロファイル画像を選択します。
- [ 設定] を選択します。
- 左側のパネルで、[ 開発者設定] と [ 個人用アクセス トークン] > [トークン (クラシック)]を選択します。
- 上部にある [ 新しいトークンの生成] を選択し、パスワードを入力して、パブリック リポジトリを読み取ることができるトークンを作成します。
- 大事な: トークンを保存するか、ページを閉じるとページを開いたままにしておきます。トークンを再度表示することはできません。
- Azure ポータルで、Foundry Microsoft開きます。
- 右上のナビゲーションで [管理] を選択し、Project詳細を選択し、[接続されているリソース] タブを選択します。
- カスタム キーの種類の新しい接続を作成します。
- 名前を付け、キーと値のペアを追加します。
- キー名を
Authorizationに設定すると、値はBearer your_github_tokenの形式になります。
エージェントを作成するコード サンプル
using System;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
var projectEndpoint = "your_project_endpoint";
var mcpConnectionName = "my-mcp-connection";
// Create project client to call Foundry API
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: new DefaultAzureCredential());
// 1. Add the GitHub MCP server to a toolbox. Using a toolbox is the recommended
// way to give agents tools. See /azure/foundry/agents/concepts/toolbox-overview
AgentToolboxes toolboxClient = projectClient.AgentAdministrationClient.GetAgentToolboxes();
McpTool mcpTool = ResponseTool.CreateMcpTool(
serverLabel: "api-specs",
serverUri: new Uri("https://api.githubcopilot.com/mcp"),
toolCallApprovalPolicy: new McpToolCallApprovalPolicy(
GlobalMcpToolCallApprovalPolicy.AlwaysRequireApproval));
mcpTool.ProjectConnectionId = mcpConnectionName;
ToolboxVersion toolboxVersion = toolboxClient.CreateToolboxVersion(
toolboxName: "mcp-server-toolbox",
tools: [ProjectsAgentTool.AsProjectTool(mcpTool)],
description: "Toolbox with the GitHub MCP server");
// 2. The toolbox exposes an MCP-compatible endpoint.
var toolboxMcpUrl = new Uri(
$"{projectEndpoint}/toolboxes/{toolboxVersion.Name}" +
$"/versions/{toolboxVersion.Version}/mcp?api-version=v1");
// 3. Create a remote-tool project connection that points at the toolbox endpoint.
// Use a user Entra token so the caller's identity is passed through
// (audience https://ai.azure.com). Create the connection once, for example
// with the Azure Developer CLI:
//
// azd ai connection create mcp-server-toolbox-conn \
// --kind remote-tool \
// --target "<toolboxMcpUrl>" \
// --auth-type user-entra-token \
// --audience https://ai.azure.com
var toolboxConnectionName = "mcp-server-toolbox-conn";
// 4. Attach the toolbox to a prompt agent as an MCP tool. Note that in this scenario
// GlobalMcpToolCallApprovalPolicy.AlwaysRequireApproval is used, which means that
// any calls to the toolbox MCP endpoint must be approved.
McpTool toolboxTool = ResponseTool.CreateMcpTool(
serverLabel: "toolbox",
serverUri: toolboxMcpUrl,
toolCallApprovalPolicy: new McpToolCallApprovalPolicy(
GlobalMcpToolCallApprovalPolicy.AlwaysRequireApproval));
toolboxTool.ProjectConnectionId = toolboxConnectionName;
DeclarativeAgentDefinition agentDefinition = new(model: "gpt-5-mini")
{
Instructions = "You are a helpful agent that can use MCP tools to assist users. Use the available MCP tools to answer questions and perform tasks.",
Tools = { toolboxTool }
};
AgentVersion agentVersion = projectClient.AgentAdministrationClient.CreateAgentVersion(
agentName: "myAgent",
options: new(agentDefinition));
// If the tool approval is required, the response item is
// of McpToolCallApprovalRequestItem type and contains all
// the information about tool call. This example checks that
// the server label is "toolbox" and approves the tool call.
// All other calls are denied because they shouldn't happen given
// the current configuration.
ProjectResponsesClient responseClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentVersion.Name);
CreateResponseOptions nextResponseOptions = new([ResponseItem.CreateUserMessageItem("What is my username in my GitHub profile?")]);
ResponseResult latestResponse = null;
while (nextResponseOptions is not null)
{
latestResponse = responseClient.CreateResponse(nextResponseOptions);
nextResponseOptions = null;
foreach (ResponseItem responseItem in latestResponse.OutputItems)
{
if (responseItem is McpToolCallApprovalRequestItem mcpToolCall)
{
nextResponseOptions = new()
{
PreviousResponseId = latestResponse.Id,
};
if (string.Equals(mcpToolCall.ServerLabel, "toolbox"))
{
Console.WriteLine($"Approval requested for {mcpToolCall.ServerLabel} (tool: {mcpToolCall.ToolName})");
Console.Write("Approve this MCP tool call? (y/N): ");
bool approved = string.Equals(Console.ReadLine(), "y", StringComparison.OrdinalIgnoreCase);
nextResponseOptions.InputItems.Add(ResponseItem.CreateMcpApprovalResponseItem(approvalRequestId: mcpToolCall.Id, approved: approved));
}
else
{
Console.WriteLine($"Rejecting unknown call {mcpToolCall.ServerLabel}...");
nextResponseOptions.InputItems.Add(ResponseItem.CreateMcpApprovalResponseItem(approvalRequestId: mcpToolCall.Id, approved: false));
}
}
}
}
// Output the final response from the agent.
Console.WriteLine(latestResponse.GetOutputText());
// Clean up resources by deleting the agent version.
projectClient.AgentAdministrationClient.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
予期される出力
次の例は、サンプルの実行時に予想される出力を示しています。
Approval requested for toolbox...
Response: Your GitHub username is "example-username".
MCP ツールを使用して TypeScript でエージェントを作成する
次の TypeScript サンプルでは、ツールボックスに MCP サーバーを追加する方法、ツールボックスをエージェントにアタッチする方法、MCP 承認ワークフローをトリガーする要求を送信する方法、承認要求を処理する方法、リソースをクリーンアップする方法を示します。 JavaScript のバージョンについては、GitHub の JavaScript リポジトリのAzure SDKのサンプル コードを参照してください。
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
import OpenAI from "openai";
import * as readline from "readline";
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
export async function main(): Promise<void> {
// Create clients to call Foundry API
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = project.getOpenAIClient();
console.log("Creating agent with MCP tool...");
// 1. Add the Azure REST API specifications MCP server to a toolbox. Using a toolbox is
// the recommended way to give agents tools. See /azure/foundry/agents/concepts/toolbox-overview
const toolbox = await project.toolboxes.createVersion(
"mcp-server-toolbox",
[
{
type: "mcp",
server_label: "api-specs",
server_url: "https://gitmcp.io/Azure/azure-rest-api-specs",
require_approval: "always",
},
],
{ description: "Toolbox with the Azure REST API specifications MCP server" },
);
// 2. The toolbox exposes an MCP-compatible endpoint.
const toolboxMcpUrl =
`${PROJECT_ENDPOINT}/toolboxes/${toolbox.name}` +
`/versions/${toolbox.version}/mcp?api-version=v1`;
// 3. Create a remote-tool project connection that points at the toolbox endpoint.
// Use a user Entra token so the caller's identity is passed through
// (audience https://ai.azure.com). Create the connection once, for example
// with the Azure Developer CLI:
//
// azd ai connection create mcp-server-toolbox-conn \
// --kind remote-tool \
// --target "<toolboxMcpUrl>" \
// --auth-type user-entra-token \
// --audience https://ai.azure.com
const toolboxConnectionName = "mcp-server-toolbox-conn";
// 4. Attach the toolbox to a prompt agent as an MCP tool.
// The toolbox tool requires approval for each operation to ensure user control over external requests.
const agent = await project.agents.createVersion("agent-mcp", {
kind: "prompt",
model: "gpt-5-mini",
instructions:
"You are a helpful agent that can use MCP tools to assist users. Use the available MCP tools to answer questions and perform tasks.",
tools: [
{
type: "mcp",
server_label: "toolbox",
server_url: toolboxMcpUrl,
require_approval: "always",
project_connection_id: toolboxConnectionName,
},
],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);
// Create a conversation thread to maintain context across multiple interactions
console.log("\nCreating conversation...");
const conversation = await openai.conversations.create();
console.log(`Created conversation (id: ${conversation.id})`);
// Send initial request that will trigger the MCP tool to access Azure REST API specs
// This will generate an approval request since requireApproval="always"
console.log("\nSending request that will trigger MCP approval...");
const response = await openai.responses.create(
{
conversation: conversation.id,
input: "Please summarize the Azure REST API specifications Readme",
},
{
body: { agent_reference: { name: agent.name, type: "agent_reference" } },
},
);
// Process any MCP approval requests that were generated
// When requireApproval="always", the agent will request permission before accessing external resources
const inputList: OpenAI.Responses.ResponseInputItem.McpApprovalResponse[] = [];
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const ask = (q: string) => new Promise<string>((resolve) => rl.question(q, resolve));
for (const item of response.output) {
if (item.type === "mcp_approval_request") {
if (item.server_label === "toolbox" && item.id) {
console.log(`\nReceived MCP approval request (id: ${item.id})`);
console.log(` Server: ${item.server_label}`);
console.log(` Tool: ${item.name}`);
// Approve only after you review the tool call.
// In production, implement your own approval UX and policy.
const answer = (await ask("Approve this MCP tool call? (y/N): ")).trim().toLowerCase();
const approve = answer === "y";
inputList.push({
type: "mcp_approval_response",
approval_request_id: item.id,
approve,
});
}
}
}
rl.close();
console.log(`\nProcessing ${inputList.length} approval request(s)`);
console.log("Final input:");
console.log(JSON.stringify(inputList, null, 2));
// Send the approval response back to continue the agent's work
// This allows the MCP tool to access the GitHub repository and complete the original request
console.log("\nSending approval response...");
const finalResponse = await openai.responses.create(
{
input: inputList,
previous_response_id: response.id,
},
{
body: { agent_reference: { name: agent.name, type: "agent_reference" } },
},
);
console.log(`\nResponse: ${finalResponse.output_text}`);
// Clean up resources by deleting the agent version and conversation
// This prevents accumulation of unused resources in your project
console.log("\nCleaning up resources...");
await openai.conversations.delete(conversation.id);
console.log("Conversation deleted");
await project.agents.deleteVersion(agent.name, agent.version);
console.log("Agent deleted");
console.log("\nMCP sample completed!");
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
予期される出力
次の例は、サンプルの実行時に予想される出力を示しています。
Creating agent with MCP tool...
Agent created (id: <agent-id>, name: agent-mcp, version: 1)
Creating conversation...
Created conversation (id: <conversation-id>)
Sending request that will trigger MCP approval...
Received MCP approval request (id: <approval-request-id>)
Server: api-specs
Tool: get-readme
Processing 1 approval request(s)
Final input:
[
{
"type": "mcp_approval_response",
"approval_request_id": "<approval-request-id>",
"approve": true
}
]
Sending approval response...
Response: The Azure REST API specifications repository contains the OpenAPI specifications for Azure services. It is organized by service and includes guidelines for contributing new specifications. The repository is intended for use by developers building tools and services that interact with Azure APIs.
Cleaning up resources...
Conversation deleted
Agent deleted
MCP sample completed!
プロジェクト接続認証で MCP ツールを使用してエージェントを作成する
次の TypeScript サンプルでは、認証された MCP サーバーをツールボックスに追加し、ツールボックス MCP エンドポイントをエージェントにアタッチし、MCP 承認ワークフローをトリガーする要求を送信し、承認要求を処理し、リソースをクリーンアップする方法を示します。 JavaScript のバージョンについては、GitHub の JavaScript リポジトリのAzure SDKのサンプル コードを参照してください。
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
import OpenAI from "openai";
import * as readline from "readline";
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
const MCP_CONNECTION_NAME = "my-mcp-connection";
export async function main(): Promise<void> {
// Create clients to call Foundry API
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = project.getOpenAIClient();
console.log("Creating agent with MCP tool using project connection...");
// 1. Add the GitHub MCP server to a toolbox with project connection authentication.
// The project connection should have Authorization header configured with "Bearer <GitHub PAT token>"
// Token can be created at https://github.com/settings/personal-access-tokens/new
const toolbox = await project.toolboxes.createVersion(
"mcp-server-toolbox",
[
{
type: "mcp",
server_label: "api-specs",
server_url: "https://api.githubcopilot.com/mcp",
require_approval: "always",
project_connection_id: MCP_CONNECTION_NAME,
},
],
{ description: "Toolbox with the GitHub MCP server" },
);
// 2. The toolbox exposes an MCP-compatible endpoint.
const toolboxMcpUrl =
`${PROJECT_ENDPOINT}/toolboxes/${toolbox.name}` +
`/versions/${toolbox.version}/mcp?api-version=v1`;
// 3. Create a remote-tool project connection that points at the toolbox endpoint.
// Use a user Entra token so the caller's identity is passed through
// (audience https://ai.azure.com). Create the connection once, for example
// with the Azure Developer CLI:
//
// azd ai connection create mcp-server-toolbox-conn \
// --kind remote-tool \
// --target "<toolboxMcpUrl>" \
// --auth-type user-entra-token \
// --audience https://ai.azure.com
const toolboxConnectionName = "mcp-server-toolbox-conn";
// 4. Attach the toolbox to a prompt agent as an MCP tool.
const agent = await project.agents.createVersion("agent-mcp-connection-auth", {
kind: "prompt",
model: "gpt-5-mini",
instructions: "Use MCP tools as needed",
tools: [
{
type: "mcp",
server_label: "toolbox",
server_url: toolboxMcpUrl,
require_approval: "always",
project_connection_id: toolboxConnectionName,
},
],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);
// Create a conversation thread to maintain context across multiple interactions
console.log("\nCreating conversation...");
const conversation = await openai.conversations.create();
console.log(`Created conversation (id: ${conversation.id})`);
// Send initial request that will trigger the MCP tool
console.log("\nSending request that will trigger MCP approval...");
const response = await openai.responses.create(
{
conversation: conversation.id,
input: "What is my username in my GitHub profile?",
},
{
body: { agent_reference: { name: agent.name, type: "agent_reference" } },
},
);
// Process any MCP approval requests that were generated
const inputList: OpenAI.Responses.ResponseInputItem.McpApprovalResponse[] = [];
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const ask = (q: string) => new Promise<string>((resolve) => rl.question(q, resolve));
for (const item of response.output) {
if (item.type === "mcp_approval_request") {
if (item.server_label === "toolbox" && item.id) {
console.log(`\nReceived MCP approval request (id: ${item.id})`);
console.log(` Server: ${item.server_label}`);
console.log(` Tool: ${item.name}`);
// Approve only after you review the tool call.
// In production, implement your own approval UX and policy.
const answer = (await ask("Approve this MCP tool call? (y/N): ")).trim().toLowerCase();
const approve = answer === "y";
inputList.push({
type: "mcp_approval_response",
approval_request_id: item.id,
approve,
});
}
}
}
rl.close();
console.log(`\nProcessing ${inputList.length} approval request(s)`);
console.log("Final input:");
console.log(JSON.stringify(inputList, null, 2));
// Send the approval response back to continue the agent's work
// This allows the MCP tool to access the GitHub repository and complete the original request
console.log("\nSending approval response...");
const finalResponse = await openai.responses.create(
{
input: inputList,
previous_response_id: response.id,
},
{
body: { agent_reference: { name: agent.name, type: "agent_reference" } },
},
);
console.log(`\nResponse: ${finalResponse.output_text}`);
// Clean up resources by deleting the agent version and conversation
// This prevents accumulation of unused resources in your project
console.log("\nCleaning up resources...");
await openai.conversations.delete(conversation.id);
console.log("Conversation deleted");
await project.agents.deleteVersion(agent.name, agent.version);
console.log("Agent deleted");
console.log("\nMCP with project connection sample completed!");
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
予期される出力
次の例は、サンプルの実行時に予想される出力を示しています。
Creating agent with MCP tool using project connection...
Agent created (id: <agent-id>, name: agent-mcp-connection-auth, version: 1)
Creating conversation...
Created conversation (id: <conversation-id>)
Sending request that will trigger MCP approval...
Received MCP approval request (id: <approval-request-id>)
Server: toolbox
Tool: get-github-username
Processing 1 approval request(s)
Final input:
[
{
"type": "mcp_approval_response",
"approval_request_id": "<approval-request-id>",
"approve": true
}
]
Sending approval response...
Response: Your GitHub username is "example-username".
Cleaning up resources...
Conversation deleted
Agent deleted
MCP with project connection sample completed!
Java エージェントで MCP ツールを使用する
ヒント
ほとんどのエージェントは 、ツールボックス を使用してファイル検索ツールを追加し、MCP ツールとしてツールボックスをエージェントにアタッチします。 *Java SDK を使用している場合、ツールボックスを作成するための API はまだ使用できません。 Python、REST API、C#、TypeScript、または Foundry ポータルを使用してツールボックスを作成し、Java エージェントから MCP エンドポイントをMcpToolとして参照します。
依存関係を pom.xmlに追加します。
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.2.0</version>
</dependency>
MCP ツールを使用してエージェントを作成する
import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.ResponsesClient;
import com.azure.ai.agents.models.AgentReference;
import com.azure.ai.agents.models.AgentVersionDetails;
import com.azure.ai.agents.models.AzureCreateResponseOptions;
import com.azure.ai.agents.models.McpTool;
import com.azure.ai.agents.models.PromptAgentDefinition;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import java.util.Collections;
public class McpToolExample {
public static void main(String[] args) {
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
String projectEndpoint = "your_project_endpoint";
// Create the toolbox out-of-band by using Python, REST, the Foundry portal, C#, or TypeScript.
String toolboxMcpUrl = projectEndpoint + "/toolboxes/mcp-server-toolbox/versions/1/mcp?api-version=v1";
String toolboxConnectionName = "mcp-server-toolbox-conn";
AgentsClientBuilder builder = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint);
AgentsClient agentsClient = builder.buildAgentsClient();
ResponsesClient responsesClient = builder.buildResponsesClient();
// Attach the toolbox MCP endpoint with server label, URL, connection, and approval mode.
McpTool mcpTool = new McpTool("toolbox")
.setServerUrl(toolboxMcpUrl)
.setProjectConnectionId(toolboxConnectionName)
.setRequireApproval("always");
// Create agent with MCP tool
PromptAgentDefinition agentDefinition = new PromptAgentDefinition("gpt-5-mini")
.setInstructions("You are a helpful assistant that can use MCP tools.")
.setTools(Collections.singletonList(mcpTool));
AgentVersionDetails agent = agentsClient.createAgentVersion("mcp-agent", agentDefinition);
System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion());
// Create a response
AgentReference agentReference = new AgentReference(agent.getName())
.setVersion(agent.getVersion());
Response response = responsesClient.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(agentReference),
ResponseCreateParams.builder()
.input("Summarize the Azure REST API specifications"));
System.out.println("Response: " + response.output());
// Clean up
agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion());
}
}
予期される出力
Agent created: mcp-agent (version 1)
Response: [ResponseOutputItem containing MCP tool results ...]
REST API で MCP ツールを使用する
次の例は、MCP ツールを使用してエージェントを作成し、Responses API を使用して呼び出す方法を示しています。
typeがmcp_approval_requestに設定された出力項目が応答に含まれている場合は、mcp_approval_response項目を含むフォローアップ要求を送信します。
前提 条件
次の環境変数を設定します。
-
FOUNDRY_PROJECT_ENDPOINT: プロジェクト エンドポイントの URL。 -
FOUNDRY_MODEL_DEPLOYMENT_NAME: モデルのデプロイ名。 -
AGENT_TOKEN: Foundry のベアラー トークン。 -
MCP_PROJECT_CONNECTION_NAME(省略可能): MCP プロジェクトの接続名。
アクセス トークンを取得します。
export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)
ツールボックス内の MCP サーバーで認証が必要ない場合は、ツールボックス ツール定義から project_connection_id を省略します。 エージェントの MCP ツールでは、ツールボックス エンドポイントへのリモート ツール接続に project_connection_id が引き続き使用されます。
メモ
REST API の場合は、エージェントの MCP ツールで project_connection_id としてツールボックス エンドポイント用に作成したリモート ツール プロジェクト接続名を使用します。
ヒント
MCP ツールのスキーマと承認項目の詳細については、Microsoft Foundry REST API リファレンスを参照してください。
1. MCP サーバーを使用してツールボックスを作成する
MCP サーバーを追加する推奨される方法は、ツールボックスを使用して、MCP ツールとしてエージェントにツールボックスをアタッチすることです。 ツールボックスとは
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/toolboxes/mcp-server-toolbox/versions?api-version=v1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d '{
"description": "Toolbox with the Azure REST API specifications MCP server",
"tools": [
{
"type": "mcp",
"server_label": "api-specs",
"server_url": "https://gitmcp.io/Azure/azure-rest-api-specs",
"require_approval": "never"
}
]
}'
ツールボックスは、 $FOUNDRY_PROJECT_ENDPOINT/toolboxes/mcp-server-toolbox/versions/<version>/mcp?api-version=v1で MCP 互換エンドポイントを公開します。ここで、 <version> は前の呼び出しによって返されたバージョンです。
2. ツールボックスへのリモート ツール接続を作成する
ツールボックス エンドポイントを指すリモート ツール プロジェクト接続を作成します。 呼び出し元の ID が渡されるようにユーザー Entra トークンを使用します (対象ユーザー https://ai.azure.com)。
azd ai connection create mcp-server-toolbox-conn \
--kind remote-tool \
--target "$FOUNDRY_PROJECT_ENDPOINT/toolboxes/mcp-server-toolbox/versions/<version>/mcp?api-version=v1" \
--auth-type user-entra-token \
--audience https://ai.azure.com
3. MCP エージェントを作成する
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/agents?api-version=v1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d '{
"name": "<AGENT_NAME>-mcp",
"description": "MCP agent",
"definition": {
"kind": "prompt",
"model": "'$FOUNDRY_MODEL_DEPLOYMENT_NAME'",
"instructions": "You are a helpful agent that can use MCP tools to assist users. Use the available MCP tools to answer questions and perform tasks.",
"tools": [
{
"type": "mcp",
"server_label": "toolbox",
"server_url": "'$FOUNDRY_PROJECT_ENDPOINT'/toolboxes/mcp-server-toolbox/versions/<version>/mcp?api-version=v1",
"require_approval": "always",
"project_connection_id": "mcp-server-toolbox-conn"
}
]
}
}'
ツールボックス内で認証された MCP サーバーを使用するには、ツールボックス ツール定義に "project_connection_id": "'$MCP_PROJECT_CONNECTION_NAME'" を追加します。
server_urlを認証されたサーバー エンドポイント (たとえば、https://api.githubcopilot.com/mcp) に変更します。
4. 応答を作成する
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d '{
"agent": {"type": "agent_reference", "name": "<AGENT_NAME>-mcp"},
"input": "Please summarize the Azure REST API specifications Readme"
}'
typeがmcp_approval_requestに設定された出力項目が応答に含まれている場合は、承認要求項目をidとしてAPPROVAL_REQUEST_IDコピーします。 また、最上位レベルの応答 id を PREVIOUS_RESPONSE_IDとしてコピーします。
5. 承認応答を送信する
MCP ツールで承認が必要な場合は、フォローアップ要求を送信します。
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d '{
"previous_response_id": "'$PREVIOUS_RESPONSE_ID'",
"input": [
{
"type": "mcp_approval_response",
"approval_request_id": "'$APPROVAL_REQUEST_ID'",
"approve": true
}
]
}'
6.リソースをクリーンアップする
エージェントを削除します。
curl -X DELETE "$FOUNDRY_PROJECT_ENDPOINT/agents/<AGENT_NAME>-mcp?api-version=v1" \
-H "Authorization: Bearer $AGENT_TOKEN"
しくみ
リモート MCP サーバー (既存の MCP サーバー エンドポイント) を Foundry Agent Service に持ち込む必要があります。 複数のリモート MCP サーバーをツールとして追加することで持ち込むことができます。 ツールごとに、同じエージェント内で一意の server_label 値と、リモート MCP サーバーを指す server_url 値を指定する必要があります。 Foundry Agent Service に追加する MCP サーバーを慎重に確認してください。
任意のリモート MCP サーバーを URL で接続するだけでなく、Foundry Add Tools カタログから一部の MCP サーバーを直接追加することもできます。 たとえば、Azure DevOps MCP Server (プレビュー) はカタログ エントリとして使用できます。 カタログ エントリは、接続のセットアップを簡略化し、この記事に記載されているのと同じ承認と監査メカニズムに合わせて調整します。
MCP の使用の詳細については、以下を参照してください。
- モデル コンテキスト プロトコル Web サイトのセキュリティのベスト プラクティス。
- MCP 実装におけるセキュリティ リスクの理解と軽減 Microsoft Security コミュニティ ブログを参照してください。
MCP 接続を設定する
セカンダリ パス - 高度な操作: 最初の成功ルートの後にこの参照を使用して、ツールの制限、承認動作の変更、またはプロジェクト接続の追加を行います。
次の手順では、Foundry Agent Service からリモート MCP サーバーに接続する方法について説明します。
- GitHub MCP サーバーなど、接続先のリモート MCP サーバーを見つけます。 次の情報を使用して、
mcpツールを使用して Foundry エージェントを作成または更新します。-
server_url: MCP サーバーの URL (https://api.githubcopilot.com/mcp/など)。 -
server_label: エージェントに対するこの MCP サーバーのユニークID、例えばgithub。 -
allowed_tools: このエージェントがアクセスして使用できるツールのオプションの一覧。 この値を指定しない場合、既定値には MCP サーバー内のすべてのツールが含まれます。 -
require_approval: 必要に応じて、承認が必要かどうかを判断します。 既定値はalwaysです。 サポートされる値は次のとおりです。-
always: 開発者は、すべての呼び出しに対して承認を提供する必要があります。 値を指定しない場合は、これが既定値です。 -
never: 承認は必要ありません。 -
{"never":[<tool_name_1>, <tool_name_2>]}: 承認を必要としないツールの一覧を指定します。 -
{"always":[<tool_name_1>, <tool_name_2>]}: 承認が必要なツールの一覧を指定します。
-
-
-
project_connection_id: MCP サーバーの認証とその他の接続の詳細を格納するプロジェクト接続 ID。 - モデルが承認が必要な MCP サーバーでツールを呼び出そうとすると、応答出力項目の種類が
mcp_approval_requestとして取得されます。 応答出力項目では、MCP サーバーで呼び出されるツールと渡される引数の詳細を取得できます。 ツールと引数を確認して、承認に関する十分な情報に基づいた意思決定を行えるようにします。 -
previous_response_idを使用し、approveをtrueに設定して、エージェントに承認を送信します。
Azure DevOps MCP サーバーに接続する
Azure DevOps MCP Server (プレビュー) は Foundry のカタログ エントリとして使用できます。 追加するには:
- Foundry ポータルで、プロジェクトに移動します。
- Add Tools>Catalog を選択し、"Azure DevOps" を検索します。
- Azure DevOps MCP Server (プレビュー) を選択し、Create を選択します。
- Azure DevOps組織名を入力し、Connect を選択します。
- エージェントに公開するAzure DevOpsツールを選択します。 ツールのサブセットを選択して、エージェントがアクセスできる内容を正確に制御できます。
このカタログ ベースのセットアップでは、コードの変更を必要とせずに、エージェントが使用する MCP ツールが作成されます。 このツールを運用コードに統合する前に、Foundry チャット テスト エクスペリエンスで接続とツールの動作を検証できます。
ヒント
ツールボックスのバージョン管理: Foundry ツールボックスではバージョン管理がサポートされているため、運用エージェントに影響を与えずに新しいバージョンを反復処理できます。 運用エージェントには コンシューマー エンドポイント ({project_endpoint}/toolboxes/{name}/mcp?api-version=v1) を使用します。これは常に昇格された既定のバージョンを提供します。 昇格する前に、 バージョン固有のエンドポイント ({project_endpoint}/toolboxes/{name}/versions/{version}/mcp?api-version=v1) を使用してテストします。 ツールボックスのバージョンを切り替える場合でも、エージェントごとに一意の server_label を保持します。 詳細については、「 バージョンを既定に昇格させる」を参照してください。
実行時間の長い操作 (プレビュー)
セカンダリ パス - バックグラウンド モード: このモードは、MCP 操作が標準の同期タイムアウト内で完了できない場合にのみ使用します。
一部の MCP サーバーでは、結果を返すために標準の同期タイムアウトよりも長い時間がかかるツールが公開されています。 これらの操作をサポートするには、 バックグラウンド モードでエージェントを実行します。 バックグラウンド モードでは応答が非同期的に実行されるため、MCP ツールの呼び出しは開いている接続を保持せずに続行でき、完了するまで応答の状態をポーリングします。 この方法により、MCP ツールの呼び出しは、「 既知の制限事項」で説明されている 100 秒のストリーミング以外のタイムアウトを超えます。
メモ
実行時間の長い MCP 操作はプレビュー段階です。 プレビュー機能は、サービス レベル アグリーメントなしで提供され、運用環境のワークロードには推奨されません。 動作とサポートされているモデルは変更される可能性があります。
MCP サーバーの要件
エージェント ランタイムは、MCP サーバーに依存して操作を非同期的に実行し、進行状況を報告します。 サーバーは次の手順を実行する必要があります。
- モデル コンテキスト プロトコル タスク機能を実装して、作業が完了するまでブロックするのではなく、ツール呼び出しでタスク参照を返すことができるようにします。
- 実行時間の長い操作を開始するときに、ツールの結果メタデータ (
io.modelcontextprotocol/related-taskを含むtaskIdフィールド) に関連するタスク識別子を返します。 - ランタイムがタスクの状態をポーリングし、タスクの完了後に最終的な結果を取得する方法を公開します。
- 他の MCP ツールと同じように、リモート MCP エンドポイントとして到達可能である。 リモート エンドポイントを提供するには、ローカル MCP サーバーをセルフホステッドする必要があります。 「ローカル MCP サーバーをホストする」を参照してください。
エージェント ランタイムが実行時間の長い操作を開始するツールを呼び出すと、サーバーはタスク参照を返し、ランタイムは応答をバックグラウンドで保持します。 ランタイムは応答を開始し、応答idとstatusのqueuedをすぐに返し、タスクの終了時に結果を収集します。
idがstatusになるまで応答completedをポーリングし、最終的な出力を読み取ります。
実行時間の長い MCP 操作のバックグラウンド モードは、 gpt-5.4 や gpt-5.5など、バックグラウンド モードをサポートする任意のモデルで動作します。
エージェントがバックグラウンド モードをサポートしていないモデルを使用している場合、MCP ツール呼び出しは同期的に実行され、100 秒のタイムアウトが発生します。
Microsoft Foundry ポータルでバックグラウンド モードを有効にする
コードを記述せずに、Microsoft Foundry ポータルのプレイグラウンドでエージェントのバックグラウンド モードを有効にすることができます。
エージェントを開き、[ プレイグラウンド ] タブを選択します。
[ モデル ] ボックスの一覧で、
gpt-5.4やgpt-5.5など、バックグラウンド モードをサポートするモデルを選択します。モデルの横にあるパラメーター アイコンを選択し、 バックグラウンド モードをオンにします。
[ツール] で、MCP サーバーが MCP タスクをサポートするツール (Fabric IQ ツールを使用して追加されたFabric データ エージェントなど) を追加します。 手順については、「Fabric IQ を使用してエージェントをMicrosoft Fabricに接続する」を参照してください。
メッセージを送信します。 エージェントはバックグラウンド実行を開始し、実行時間の長いツール呼び出しが完了するまでの進行状況を示します。 実行が完了すると、応答がチャットに表示されます。
コードを使用してバックグラウンド モードを実行する
次の例では、MCP ツールで既に構成されているエージェントを呼び出し、 background を true に設定し、応答が完了するまでポーリングします。 プレースホルダーの値を独自の値に置き換えます。
from time import sleep
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
PROJECT_ENDPOINT = "your_project_endpoint"
AGENT_NAME = "your_mcp_agent_name"
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
# Start a background response. It returns immediately with status "queued".
response = openai.responses.create(
extra_body={
"agent_reference": {
"name": AGENT_NAME,
"type": "agent_reference",
}
},
input="Run the long-running task and summarize the result.",
background=True,
)
# Poll the response ID until the MCP tool call completes.
while response.status in ("queued", "in_progress"):
sleep(5)
response = openai.responses.retrieve(response.id)
print(response.output_text)
using Azure.Identity;
using Azure.AI.Projects;
var projectEndpoint = "your_project_endpoint";
var agentName = "your_mcp_agent_name";
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: new DefaultAzureCredential());
ProjectResponsesClient responsesClient
= projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentName);
// Start a background response. It returns immediately with status "queued".
ResponseResult response = await responsesClient.CreateResponseAsync(
new CreateResponseOptions
{
InputItems = { ResponseItem.CreateUserMessageItem(
"Run the long-running task and summarize the result.") },
Background = true,
});
// Poll the response ID until the MCP tool call completes.
while (response.Status is "queued" or "in_progress")
{
await Task.Delay(5000);
response = await responsesClient.RetrieveResponseAsync(response.Id);
}
Console.WriteLine(response.GetOutputText());
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
const PROJECT_ENDPOINT = "your_project_endpoint";
const AGENT_NAME = "your_mcp_agent_name";
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = project.getOpenAIClient();
// Start a background response. It returns immediately with status "queued".
let response = await openai.responses.create(
{
input: "Run the long-running task and summarize the result.",
background: true,
},
{ body: { agent_reference: { name: AGENT_NAME, type: "agent_reference" } } },
);
// Poll the response ID until the MCP tool call completes.
while (response.status === "queued" || response.status === "in_progress") {
await new Promise((r) => setTimeout(r, 5000));
response = await openai.responses.retrieve(response.id);
}
console.log(response.output_text);
import com.azure.ai.agents.*;
import com.azure.ai.agents.models.AgentReference;
import com.azure.ai.agents.models.AzureCreateResponseOptions;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
String projectEndpoint = "your_project_endpoint";
String agentName = "your_mcp_agent_name";
AgentsClientBuilder builder = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint);
ResponsesClient responsesClient = builder.buildResponsesClient();
AgentReference agentRef = new AgentReference(agentName);
// Start a background response. It returns immediately with status "queued".
Response response = responsesClient.createAzureResponse(
new AzureCreateResponseOptions()
.setAgentReference(agentRef)
.setBackground(true),
ResponseCreateParams.builder()
.input("Run the long-running task and summarize the result."));
// Poll the response ID until the MCP tool call completes.
while (response.status().equals("queued") || response.status().equals("in_progress")) {
Thread.sleep(5000);
response = responsesClient.getAzureResponse(response.id());
}
System.out.println(response.output());
バックグラウンド応答を作成します。 この要求は、応答 id および status の queued を伴って直ちに返されます。
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d '{
"agent": {"type": "agent_reference", "name": "<AGENT_NAME>-mcp"},
"input": "Run the long-running task and summarize the result.",
"background": true
}'
結果から応答 id をコピーし、 status が completedされるまでポーリングします。
curl "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses/$RESPONSE_ID" \
-H "Authorization: Bearer $AGENT_TOKEN"
statusがcompletedされると、output配列には MCP ツールの呼び出し結果と最後のアシスタント メッセージが含まれます。
既知の制限事項
セカンダリ パス - ストリーミング動作: クライアントが応答をストリーム配信するか、MCP 呼び出しが同期タイムアウトに近づく場合は、最初の成功ルートの後にこれらの制限を確認します。
- 非ストリーミング MCP ツール呼び出しタイムアウト: 非ストリーミング MCP ツール呼び出しのタイムアウトは 100 秒です。 MCP サーバーの応答に 100 秒を超える時間がかかる場合、呼び出しは失敗します。 タイムアウトを回避するには、MCP サーバーがこの制限内で応答することを確認します。 ユース ケースで処理時間が長くなる場合は、サポートされているモデルを使用して バックグラウンド モード でエージェントを実行するか、サーバー側ロジックを最適化するか、操作をより小さな手順に分割します。
- プライベート MCP には Standard エージェントのセットアップが必要です。プライベート MCP サーバー接続は、プライベート ネットワーク (BYO VNet) を使用 した Standard エージェントセットアップ でのみ使用できます。 基本的なエージェントのセットアップでは、プライベート MCP エンドポイントはサポートされていません。
- Private MCP ホスティング: 専用 MCP サブネット上のAzure Container Appsは、プライベート MCP サーバーのテスト済み構成です。 プライベート MCP サーバー ホストとしての Function Apps または App Services は機能する可能性がありますが、内部的には検証されません。
一般的な質問とエラー
Foundry Agent Service で MCP ツールを使用すると、次の一般的な問題が発生する可能性があります。
"無効なツール スキーマ":
通常、このエラーは、MCP サーバー定義に
anyOfまたはallOfが含まれている場合、またはパラメーターが複数の型の値を受け入れる場合に発生します。 MCP サーバー定義を更新してから、やり直してください。MCP サーバーからの「認証されていない」または「禁止されています」:
MCP サーバーで認証方法がサポートされていることを確認し、プロジェクト接続に格納されている資格情報を確認します。 GitHubの場合は、最小特権トークンを使用し、定期的にローテーションします。
このモデルでは、MCP ツールは呼び出されません。
エージェントの指示に従ってツールの使用を促し、
server_label、server_url、allowed_toolsの値を確認します。allowed_tools設定する場合は、ツール名が MCP サーバーで公開されているものと一致していることを確認します。承認後、エージェントは決して続行しません。
previous_response_id元の応答 ID に設定されたフォローアップ要求を送信し、承認要求項目 ID をapproval_request_idとして使用することを確認します。
ローカル MCP サーバーをホストする
エージェント サービス ランタイムは、リモート MCP サーバー エンドポイントのみを受け入れます。 ローカル MCP サーバーからツールを追加する場合は、リモート MCP サーバー エンドポイントを取得するには、Azure Container Apps または Azure Functions でセルフホストする必要があります。
リモート エンドポイントには、VNet 内のパブリック エンドポイントまたはプライベート エンドポイントのいずれかを指定できます。 プライベート MCP サーバーの場合は、専用 MCP サブネットに内部専用イングレス (--internal-only true) を使用してコンテナー アプリをデプロイします。 セットアップの詳細については、 パブリックおよびプライベートの MCP サーバー エンドポイントを 参照してください。
クラウドでローカル MCP サーバーをホストする場合は、次の要因を考慮してください。
| ローカル MCP サーバーのセットアップ | Azure Container Appsでのホスティング | Azure Functionsでのホスティング |
|---|---|---|
| トランスポート | HTTP POST/GET エンドポイントが必要です。 | HTTP ストリーミング可能が必要です。 |
| コードの変更 | コンテナーの再構築が必要です。 | ルート ディレクトリに必要なAzure Functions固有の構成ファイル。 |
| 認証 | カスタム認証の実装が必要です。 | キー入力のみ。 OAuth には API Management が必要です。 |
| 言語 | Linux コンテナーで実行される言語 (Python、Node.js、.NET、TypeScript、Go)。 | Python、Node.js、Java、.NETのみ。 |
| コンテナーの要件 | Linux (linux/amd64) のみ。 特権コンテナーはありません。 | コンテナー化されたサーバーはサポートされていません。 |
| 依存 関係 | すべての依存関係はコンテナー イメージ内にある必要があります。 | OS レベルの依存関係 (Playwright など) はサポートされていません。 |
| 状態 | ステートレスのみ。 | ステートレスのみ。 |
| UVX/NPX | サポートされています。 | サポートされていません。
npx start コマンドはサポートされていません。 |