Hinweis
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, sich anzumelden oder das Verzeichnis zu wechseln.
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, das Verzeichnis zu wechseln.
Sie können die Funktionen Ihres Azure AI Foundry-Agents erweitern, indem Sie sie mit Tools verbinden, die auf MCP-Servern (Remote Model Context Protocol) gehostet werden (bringen Sie Ihren eigenen MCP-Serverendpunkt).
So verwenden Sie das Modellkontextprotokoll-Tool
In diesem Abschnitt wird erläutert, wie Sie einen KI-Agent mit Azure Foundry (Azure AI) mit einer gehosteten MCP-Serverintegration (Model Context Protocol) erstellen. Der Agent kann MCP-Tools verwenden, die vom Azure Foundry-Dienst verwaltet und ausgeführt werden, sodass der sichere und kontrollierte Zugriff auf externe Ressourcen ermöglicht wird.
Wichtige Merkmale
- Gehosteter MCP-Server: Der MCP-Server wird von Azure AI Foundry gehostet und verwaltet, sodass keine Serverinfrastruktur verwaltet werden muss
- Persistent Agents: Agents werden auf serverseitiger Seite erstellt und gespeichert, sodass zustandsbehaftete Unterhaltungen möglich sind.
- Toolgenehmigungsworkflow: Konfigurierbare Genehmigungsmechanismen für MCP-Toolaufrufe
Funktionsweise
1. Umgebungseinrichtung
Für das Beispiel sind zwei Umgebungsvariablen erforderlich:
-
AZURE_FOUNDRY_PROJECT_ENDPOINT: Ihre Azure AI Foundry-Projektendpunkt-URL -
AZURE_FOUNDRY_PROJECT_MODEL_ID: Der Name der Modellbereitstellung (standardmäßig "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. Agent-Konfiguration
Der Agent ist mit bestimmten Anweisungen und Metadaten konfiguriert:
const string AgentName = "MicrosoftLearnAgent";
const string AgentInstructions = "You answer questions by searching the Microsoft Learn content only.";
Dadurch wird ein Agent erstellt, der auf die Beantwortung von Fragen mit der Microsoft Learn-Dokumentation spezialisiert ist.
3. MCP-Tooldefinition
Im Beispiel wird eine MCP-Tooldefinition erstellt, die auf einen gehosteten MCP-Server verweist:
var mcpTool = new MCPToolDefinition(
serverLabel: "microsoft_learn",
serverUrl: "https://learn.microsoft.com/api/mcp");
mcpTool.AllowedTools.Add("microsoft_docs_search");
Wichtige Komponenten:
- serverLabel: Ein eindeutiger Bezeichner für die MCP-Serverinstanz
- serverUrl: Die URL des gehosteten MCP-Servers
- AllowedTools: Gibt an, welche Tools vom MCP-Server, den der Agent verwenden kann
4. Erstellung persistenter Agent
Der Agent wird serverseitig mit dem Azure AI Foundry Persistent Agents SDK erstellt:
var persistentAgentsClient = new PersistentAgentsClient(endpoint, new DefaultAzureCredential());
var agentMetadata = await persistentAgentsClient.Administration.CreateAgentAsync(
model: model,
name: AgentName,
instructions: AgentInstructions,
tools: [mcpTool]);
Warnung
DefaultAzureCredential ist praktisch für die Entwicklung, erfordert aber sorgfältige Überlegungen in der Produktion. Berücksichtigen Sie in der Produktion die Verwendung bestimmter Anmeldeinformationen (z. B. ManagedIdentityCredential), um Latenzprobleme, unbeabsichtigte Anmeldeinformationen probingen und potenzielle Sicherheitsrisiken aus Fallbackmechanismen zu vermeiden.
Dadurch wird ein beständiger Agent erstellt, der:
- Lebt im Azure AI Foundry-Dienst
- Zugriff auf die angegebenen MCP-Tools
- Kann den Unterhaltungszustand über mehrere Interaktionen hinweg verwalten
5. Agentabruf und -ausführung
Der erstellte Agent wird als AIAgent Instanz abgerufen:
AIAgent agent = await persistentAgentsClient.GetAIAgentAsync(agentMetadata.Value.Id);
6. Toolressourcenkonfiguration
Im Beispiel werden Toolressourcen mit Genehmigungseinstellungen konfiguriert:
var runOptions = new ChatClientAgentRunOptions()
{
ChatOptions = new()
{
RawRepresentationFactory = (_) => new ThreadAndRunOptions()
{
ToolResources = new MCPToolResource(serverLabel: "microsoft_learn")
{
RequireApproval = new MCPApproval("never"),
}.ToToolResources()
}
}
};
Schlüsselkonfiguration:
- MCPToolResource: Verknüpft die MCP-Serverinstanz mit der Agentausführung
-
RequireApproval: Steuerelemente, wenn die Benutzergenehmigung für Toolaufrufe erforderlich ist
-
"never": Tools werden automatisch ohne Genehmigung ausgeführt -
"always": Alle Toolaufrufe erfordern eine Benutzergenehmigung. - Benutzerdefinierte Genehmigungsregeln können auch konfiguriert werden
-
7. Agentausführung
Der Agent wird mit einer Frage aufgerufen und mithilfe der konfigurierten MCP-Tools ausgeführt:
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. Bereinigung
Im Beispiel wird die richtige Ressourcenbereinigung veranschaulicht:
await persistentAgentsClient.Administration.DeleteAgentAsync(agent.Id);
Tipp
Vollständige Runnable-Beispiele finden Sie in den .NET-Beispielen .
Azure AI Foundry bietet eine nahtlose Integration mit MCP-Servern (Model Context Protocol) über das Python Agent Framework. Der Dienst verwaltet das MCP-Serverhosting und die Ausführung, wodurch die Infrastrukturverwaltung eliminiert und gleichzeitig sicheren, kontrollierten Zugriff auf externe Tools bereitgestellt wird.
Umgebungseinrichtung
Konfigurieren Sie Ihre Azure AI Foundry-Projektanmeldeinformationen über Umgebungsvariablen:
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
Grundlegende MCP-Integration
Erstellen Sie einen Azure AI Foundry-Agent mit gehosteten MCP-Tools:
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())
Multitool-MCP-Konfiguration
Verwenden sie mehrere gehostete MCP-Tools mit einem einzigen Agent:
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())
Das Python Agent Framework bietet eine nahtlose Integration mit den gehosteten MCP-Funktionen von Azure AI Foundry, wodurch der sichere und skalierbare Zugriff auf externe Tools ermöglicht wird und gleichzeitig die für Produktionsanwendungen erforderliche Flexibilität und Kontrolle gewährleistet ist.
Vollständiges Beispiel
# 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())