Microsoft Foundry エージェントの機能を拡張するには、リモート モデル コンテキスト プロトコル (MCP) サーバーでホストされているツールに接続します (独自の MCP サーバー エンドポイントを使用します)。
モデル コンテキスト プロトコル ツールの使用方法
このセクションでは、ホストされたモデル コンテキスト プロトコル (MCP) サーバー統合を使用して、Microsoft Foundry でサポートされる Python エージェントを作成する方法について説明します。 エージェントは、Foundry サービスによって管理および実行される MCP ツールを使用して、外部リソースへの安全で制御されたアクセスを可能にします。
主な機能
- ホストされた MCP サーバー: MCP サーバーは Foundry によってホストおよび管理されるため、サーバー インフラストラクチャを管理する必要がなくなります
- 永続的なエージェント: エージェントが作成され、サーバー側に格納され、ステートフルな会話が可能
- ツール承認ワークフロー: MCP ツール呼び出しの構成可能な承認メカニズム
しくみ
1. 環境のセットアップ
このサンプルには、次の 2 つの環境変数が必要です。
-
AZURE_FOUNDRY_PROJECT_ENDPOINT: Foundry プロジェクト のエンドポイント URL -
AZURE_FOUNDRY_PROJECT_MODEL_ID: モデルのデプロイ名 (既定値は "gpt-4.1-mini")
var endpoint = Environment.GetEnvironmentVariable("AZURE_FOUNDRY_PROJECT_ENDPOINT")
?? throw new InvalidOperationException("AZURE_FOUNDRY_PROJECT_ENDPOINT is not set.");
var model = Environment.GetEnvironmentVariable("AZURE_FOUNDRY_PROJECT_MODEL_ID") ?? "gpt-4.1-mini";
2. エージェントの構成
エージェントは、特定の命令とメタデータを使用して構成されます。
const string AgentName = "MicrosoftLearnAgent";
const string AgentInstructions = "You answer questions by searching the Microsoft Learn content only.";
これにより、Microsoft Learn ドキュメントを使用して質問に回答するための特別なエージェントが作成されます。
3. MCP ツールの定義
このサンプルでは、ホストされている MCP サーバーを指す MCP ツール定義を作成します。
var mcpTool = new MCPToolDefinition(
serverLabel: "microsoft_learn",
serverUrl: "https://learn.microsoft.com/api/mcp");
mcpTool.AllowedTools.Add("microsoft_docs_search");
主要コンポーネント:
- serverLabel: MCP サーバー インスタンスの一意識別子
- serverUrl: ホストされている MCP サーバーの URL
- AllowedTools: エージェントが使用できる MCP サーバーのツールを指定します
4. エージェントの作成
エージェントは、Azure AI Projects SDK を使用してサーバー側で作成されます。
var aiProjectClient = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential());
var agentVersion = await aiProjectClient.AgentAdministrationClient.CreateAgentVersionAsync(
AgentName,
new ProjectsAgentVersionCreationOptions(
new DeclarativeAgentDefinition(model)
{
Instructions = AgentInstructions,
Tools = { mcpTool }
}));
Warnung
DefaultAzureCredential は開発には便利ですが、運用環境では慎重に考慮する必要があります。 運用環境では、待機時間の問題、意図しない資格情報のプローブ、フォールバック メカニズムによる潜在的なセキュリティ リスクを回避するために、特定の資格情報 ( ManagedIdentityCredential など) を使用することを検討してください。
これにより、次のバージョン管理されたエージェントが作成されます。
- Foundry サービスに住んでいます
- 指定された MCP ツールにアクセスできる
- 複数の対話の間で会話状態を維持できる
5. エージェントの取得と実行
作成されたエージェントは、 AIAgent インスタンスとして取得されます。
AIAgent agent = aiProjectClient.AsAIAgent(agentVersion);
6. ツール リソースの構成
このサンプルでは、承認設定を使用してツール リソースを構成します。
var runOptions = new ChatClientAgentRunOptions()
{
ChatOptions = new()
{
RawRepresentationFactory = (_) => new ThreadAndRunOptions()
{
ToolResources = new MCPToolResource(serverLabel: "microsoft_learn")
{
RequireApproval = new MCPApproval("never"),
}.ToToolResources()
}
}
};
キーの構成:
- MCPToolResource: MCP サーバー インスタンスをエージェントの実行にリンクします
-
RequireApproval: ツールの呼び出しにユーザーの承認が必要なタイミングを制御します
-
"never": ツールは承認なしで自動的に実行されます -
"always": すべてのツール呼び出しにはユーザーの承認が必要です - カスタム承認規則を構成することもできます
-
7. エージェントの実行
エージェントは質問で呼び出され、構成済みの MCP ツールを使用して実行されます。
AgentSession session = await agent.CreateSessionAsync();
var response = await agent.RunAsync(
"Please summarize the Azure AI Agent documentation related to MCP Tool calling?",
session,
runOptions);
Console.WriteLine(response);
8. クリーンアップ
このサンプルでは、適切なリソースのクリーンアップを示しています。
await aiProjectClient.AgentAdministrationClient.DeleteAgentAsync(agent.Id);
ヒント
実行可能な完全な例については、 .NET Foundry Agent Hosted MCP サンプル を参照してください。
Foundry は、Python エージェント フレームワークを介してモデル コンテキスト プロトコル (MCP) サーバーとのシームレスな統合を提供します。 このサービスは、MCP サーバーのホスティングと実行を管理し、インフラストラクチャ管理を排除しながら、セキュリティで保護された制御された外部ツールへのアクセスを提供します。
環境のセットアップ
環境変数を使用して Foundry プロジェクトの資格情報を構成します。
import os
from azure.identity.aio import AzureCliCredential
from agent_framework.foundry import FoundryChatClient
# Required environment variables
os.environ["FOUNDRY_PROJECT_ENDPOINT"] = "https://<your-project>.services.ai.azure.com/api/projects/<project-id>"
os.environ["FOUNDRY_MODEL"] = "gpt-4o-mini"
基本的な MCP 統合
ホストされている MCP ツールを使用して Foundry エージェントを作成します。
import asyncio
from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient
from azure.identity.aio import AzureCliCredential
async def basic_foundry_mcp_example():
"""Basic example of Foundry agent with hosted MCP tools."""
async with AzureCliCredential() as credential:
client = FoundryChatClient(credential=credential)
# Create a hosted MCP tool using the client method
learn_mcp = client.get_mcp_tool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
)
# Create agent with hosted MCP tool
async with Agent(
client=client,
name="MicrosoftLearnAgent",
instructions="You answer questions by searching Microsoft Learn content only.",
tools=[learn_mcp],
) as agent:
# Simple query without approval workflow
result = await agent.run(
"Please summarize the Azure AI Agent documentation related to MCP tool calling?"
)
print(result.text)
if __name__ == "__main__":
asyncio.run(basic_foundry_mcp_example())
マルチツール MCP 構成
1 つのエージェントで複数のホストされた MCP ツールを使用します。
async def multi_tool_mcp_example():
"""Example using multiple hosted MCP tools."""
async with AzureCliCredential() as credential:
client = FoundryChatClient(credential=credential)
# Create multiple MCP tools using the client method
learn_mcp = client.get_mcp_tool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
approval_mode="never_require", # Auto-approve documentation searches
)
github_mcp = client.get_mcp_tool(
name="GitHub MCP",
url="https://api.githubcopilot.com/mcp/",
approval_mode="always_require", # Require approval for GitHub operations
headers={"Authorization": "Bearer github-token"},
)
# Create agent with multiple MCP tools
async with Agent(
client=client,
name="MultiToolAgent",
instructions="You can search documentation and access GitHub repositories.",
tools=[learn_mcp, github_mcp],
) as agent:
result = await agent.run(
"Find Azure documentation and also check the latest commits in microsoft/semantic-kernel"
)
print(result.text)
if __name__ == "__main__":
asyncio.run(multi_tool_mcp_example())
Python Agent Framework は Foundry のホスト型 MCP 機能とシームレスに統合され、運用アプリケーションに必要な柔軟性と制御を維持しながら、外部ツールへの安全でスケーラブルなアクセスを可能にします。
完全な例
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential
from dotenv import load_dotenv
"""
MCP GitHub Integration with Personal Access Token (PAT)
This example demonstrates how to connect to GitHub's remote MCP server using a Personal Access
Token (PAT) for authentication. The agent can use GitHub operations like searching repositories,
reading files, creating issues, and more depending on how you scope your token.
Prerequisites:
1. A GitHub Personal Access Token with appropriate scopes
- Create one at: https://github.com/settings/tokens
- For read-only operations, you can use more restrictive scopes
2. Environment variables:
- GITHUB_PAT: Your GitHub Personal Access Token (required)
- FOUNDRY_PROJECT_ENDPOINT: Your Foundry project endpoint (required)
- FOUNDRY_MODEL: Your Foundry model deployment name (required)
"""
async def github_mcp_example() -> None:
"""Example of using GitHub MCP server with PAT authentication."""
# 1. Load environment variables from .env file if present
load_dotenv()
# 2. Get configuration from environment
github_pat = os.getenv("GITHUB_PAT")
if not github_pat:
raise ValueError(
"GITHUB_PAT environment variable must be set. Create a token at https://github.com/settings/tokens"
)
# 3. Create authentication headers with GitHub PAT
auth_headers = {
"Authorization": f"Bearer {github_pat}",
}
# 4. Create agent with the GitHub MCP tool using instance method
# The MCP tool manages the connection to the MCP server and makes its tools available
# Set approval_mode="never_require" to allow the MCP tool to execute without approval
client = FoundryChatClient(credential=AzureCliCredential())
github_mcp_tool = client.get_mcp_tool(
name="GitHub",
url="https://api.githubcopilot.com/mcp/",
headers=auth_headers,
approval_mode="never_require",
)
# 5. Create agent with the GitHub MCP tool
async with Agent(
client=client,
name="GitHubAgent",
instructions=(
"You are a helpful assistant that can help users interact with GitHub. "
"You can search for repositories, read file contents, check issues, and more. "
"Always be clear about what operations you're performing."
),
tools=github_mcp_tool,
) as agent:
# Example 1: Get authenticated user information
query1 = "What is my GitHub username and tell me about my account?"
print(f"\nUser: {query1}")
result1 = await agent.run(query1)
print(f"Agent: {result1.text}")
# Example 2: List my repositories
query2 = "List all the repositories I own on GitHub"
print(f"\nUser: {query2}")
result2 = await agent.run(query2)
print(f"Agent: {result2.text}")
if __name__ == "__main__":
asyncio.run(github_mcp_example())