您可以將 Azure AI Foundry 代理程式的功能連線至遠端 模型內容通訊協定 (MCP) 伺服器上裝載的工具,以擴充其功能(自備 MCP 伺服器端點)。
如何使用模型內容通訊協定工具
本節說明如何使用 Azure Foundry (Azure AI) 搭配裝載的模型內容通訊協定 (MCP) 伺服器整合來建立 AI 代理程式。 代理程式可以利用由 Azure Foundry 服務管理和執行的 MCP 工具,從而允許對外部資源進行安全且受控的存取。
主要功能
- 託管 MCP 伺服器:MCP 伺服器由 Azure AI Foundry 託管和管理,無需管理伺服器基礎設施
- 持久代理:代理在伺服器端建立和存儲,允許進行有狀態對話
- 工具核准工作流程:MCP 工具調用的可配置核准機制
運作方式
1. 環境設置
此範例需要兩個環境變數:
-
AZURE_FOUNDRY_PROJECT_ENDPOINT:您的 Azure AI 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 Foundry 持續性代理程式 SDK 在伺服器端建立:
var persistentAgentsClient = new PersistentAgentsClient(endpoint, new DefaultAzureCredential());
var agentMetadata = await persistentAgentsClient.Administration.CreateAgentAsync(
model: model,
name: AgentName,
instructions: AgentInstructions,
tools: [mcpTool]);
警告
DefaultAzureCredential 開發方便,但在生產過程中需謹慎考量。 在生產環境中,建議使用特定的憑證(例如 ManagedIdentityCredential),以避免延遲問題、意外的憑證探測,以及備援機制帶來的安全風險。
這會建立一個持續代理程式,該代理程式:
- 位於 Azure AI Foundry 服務上
- 可以存取指定的 MCP 工具
- 可以在多個互動中維護對話狀態
5. 代理檢索和執行
已建立的代理程式會擷取為 AIAgent 實例:
AIAgent agent = await persistentAgentsClient.GetAIAgentAsync(agentMetadata.Value.Id);
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 persistentAgentsClient.Administration.DeleteAgentAsync(agent.Id);
小提示
完整可執行範例請參閱 .NET 範例 。
Azure AI Foundry 透過 Python 代理程式架構提供與模型內容通訊協定 (MCP) 伺服器的無縫整合。 該服務管理 MCP 伺服器託管和執行,消除基礎設施管理,同時提供對外部工具的安全、受控存取。
環境設定
透過環境變數設定您的 Azure AI Foundry 專案認證:
import os
from azure.identity.aio import AzureCliCredential
from agent_framework.azure import AzureAIAgentClient
# Required environment variables
os.environ["AZURE_AI_PROJECT_ENDPOINT"] = "https://<your-project>.services.ai.azure.com/api/projects/<project-id>"
os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"] = "gpt-4o-mini" # Optional, defaults to this
基本 MCP 集成
使用託管的 MCP 工具建立 Azure AI Foundry 代理程式:
import asyncio
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential
async def basic_foundry_mcp_example():
"""Basic example of Azure AI Foundry agent with hosted MCP tools."""
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(async_credential=credential) as client,
):
# 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
agent = client.as_agent(
name="MicrosoftLearnAgent",
instructions="You answer questions by searching Microsoft Learn content only.",
tools=learn_mcp,
)
# Simple query without approval workflow
result = await agent.run(
"Please summarize the Azure AI Agent documentation related to MCP tool calling?"
)
print(result)
if __name__ == "__main__":
asyncio.run(basic_foundry_mcp_example())
多功能工具 MCP 配置
將多個託管的 MCP 工具與單一代理程式搭配使用:
async def multi_tool_mcp_example():
"""Example using multiple hosted MCP tools."""
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(async_credential=credential) as client,
):
# 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.github.com/mcp",
approval_mode="always_require", # Require approval for GitHub operations
headers={"Authorization": "Bearer github-token"},
)
# Create agent with multiple MCP tools
agent = client.as_agent(
name="MultiToolAgent",
instructions="You can search documentation and access GitHub repositories.",
tools=[learn_mcp, github_mcp],
)
result = await agent.run(
"Find Azure documentation and also check the latest commits in microsoft/semantic-kernel"
)
print(result)
if __name__ == "__main__":
asyncio.run(multi_tool_mcp_example())
Python 代理程式架構提供與 Azure AI Foundry 託管 MCP 功能的無縫集成,實現對外部工具的安全且可擴展的訪問,同時保持生產應用程式所需的靈活性和控制。
完整範例
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from agent_framework import Agent
from agent_framework.openai import OpenAIResponsesClient
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)
- OPENAI_API_KEY: Your OpenAI API key (required)
- OPENAI_RESPONSES_MODEL_ID: Your OpenAI model ID (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 = OpenAIResponsesClient()
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())