Delen via


MCP-hulpprogramma's gebruiken met Foundry Agents

U kunt de mogelijkheden van uw Azure AI Foundry-agent uitbreiden door deze te verbinden met hulpprogramma's die worden gehost op externe Model Context Protocol (MCP) servers (breng uw eigen MCP-server-eindpunt mee).

Het hulpprogramma Model Context Protocol gebruiken

In deze sectie wordt uitgelegd hoe u een AI-agent maakt met behulp van Azure Foundry (Azure AI) met een gehoste MCP-serverintegratie (Model Context Protocol). De agent kan GEBRUIKMAKEN van MCP-hulpprogramma's die worden beheerd en uitgevoerd door de Azure Foundry-service, waardoor beveiligde en gecontroleerde toegang tot externe resources mogelijk is.

Belangrijke functies

  • Gehoste MCP-server: De MCP-server wordt gehost en beheerd door Azure AI Foundry, waardoor de serverinfrastructuur niet meer hoeft te worden beheerd
  • Permanente agents: agents worden gemaakt en opgeslagen aan de serverzijde, waardoor stateful gesprekken mogelijk zijn
  • Werkstroom voor goedkeuring van hulpprogramma's: configureerbare goedkeuringsmechanismen voor MCP-hulpprogramma-aanroepen

Hoe het werkt

1. Omgeving instellen

Voor het voorbeeld zijn twee omgevingsvariabelen vereist:

  • AZURE_FOUNDRY_PROJECT_ENDPOINT: De eindpunt-URL van uw Azure AI Foundry-project
  • AZURE_FOUNDRY_PROJECT_MODEL_ID: De naam van de modelimplementatie (standaard '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. Agentconfiguratie

De agent is geconfigureerd met specifieke instructies en metagegevens:

const string AgentName = "MicrosoftLearnAgent";
const string AgentInstructions = "You answer questions by searching the Microsoft Learn content only.";

Hiermee maakt u een agent die speciaal is bedoeld voor het beantwoorden van vragen met behulp van microsoft Learn-documentatie.

3. MCP Tool Definition

In het voorbeeld wordt een MCP-hulpprogrammadefinitie gemaakt die verwijst naar een gehoste MCP-server:

var mcpTool = new MCPToolDefinition(
    serverLabel: "microsoft_learn",
    serverUrl: "https://learn.microsoft.com/api/mcp");
mcpTool.AllowedTools.Add("microsoft_docs_search");

Belangrijkste onderdelen:

  • serverLabel: een unieke id voor het MCP-serverexemplaren
  • serverUrl: de URL van de gehoste MCP-server
  • AllowedTools: Hiermee geeft u op welke hulpprogramma's van de MCP-server de agent kan gebruiken

4. Permanente agent maken

De agent wordt aan de serverzijde gemaakt met behulp van de Azure AI Foundry Persistent Agents SDK:

var persistentAgentsClient = new PersistentAgentsClient(endpoint, new DefaultAzureCredential());

var agentMetadata = await persistentAgentsClient.Administration.CreateAgentAsync(
    model: model,
    name: AgentName,
    instructions: AgentInstructions,
    tools: [mcpTool]);

Waarschuwing

DefaultAzureCredential is handig voor ontwikkeling, maar vereist zorgvuldige overwegingen in de productieomgeving. Overweeg in productie een specifieke referentie te gebruiken (bijvoorbeeld ManagedIdentityCredential) om latentieproblemen, onbedoelde referentieprobing en potentiële beveiligingsrisico's van terugvalmechanismen te voorkomen.

Hiermee maakt u een permanente agent die:

  • Woont in de Azure AI Foundry-service
  • Heeft toegang tot de opgegeven MCP-hulpprogramma's
  • Kan de gespreksstatus behouden voor meerdere interacties

5. Agent ophalen en uitvoeren

De gemaakte agent wordt opgehaald als een AIAgent exemplaar:

AIAgent agent = await persistentAgentsClient.GetAIAgentAsync(agentMetadata.Value.Id);

6. Resourceconfiguratie hulpprogramma

In het voorbeeld worden hulpprogrammabronnen geconfigureerd met goedkeuringsinstellingen:

var runOptions = new ChatClientAgentRunOptions()
{
    ChatOptions = new()
    {
        RawRepresentationFactory = (_) => new ThreadAndRunOptions()
        {
            ToolResources = new MCPToolResource(serverLabel: "microsoft_learn")
            {
                RequireApproval = new MCPApproval("never"),
            }.ToToolResources()
        }
    }
};

Sleutelconfiguratie:

  • MCPToolResource: koppelt het MCP-serverexemplaren aan de agentuitvoering
  • RequireApproval: Bepaalt wanneer goedkeuring van de gebruiker nodig is voor aanroepen van hulpprogramma's
    • "never": Hulpprogramma's worden automatisch uitgevoerd zonder goedkeuring
    • "always": Voor alle aanroepen van hulpprogramma's is goedkeuring van de gebruiker vereist
    • Aangepaste goedkeuringsregels kunnen ook worden geconfigureerd

7. Agentuitvoering

De agent wordt aangeroepen met een vraag en wordt uitgevoerd met behulp van de geconfigureerde MCP-hulpprogramma's:

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. Opschonen

Het voorbeeld demonstreert het juiste opschonen van resources:

await persistentAgentsClient.Administration.DeleteAgentAsync(agent.Id);

Aanbeveling

Zie de .NET-voorbeelden voor volledige runnable voorbeelden.

Azure AI Foundry biedt naadloze integratie met MCP-servers (Model Context Protocol) via het Python Agent Framework. De service beheert de MCP-serverhosting en -uitvoering, waardoor infrastructuurbeheer wordt geëlimineerd terwijl beveiligde, gecontroleerde toegang tot externe hulpprogramma's wordt geboden.

Omgeving instellen

Configureer uw Azure AI Foundry-projectreferenties via omgevingsvariabelen:

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

Eenvoudige MCP-integratie

Maak een Azure AI Foundry-agent met gehoste MCP-hulpprogramma's:

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-configuratie met meerdere hulpprogramma's

Gebruik meerdere gehoste MCP-hulpprogramma's met één 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())

Het Python Agent Framework biedt naadloze integratie met de gehoste MCP-mogelijkheden van Azure AI Foundry, waardoor veilige en schaalbare toegang tot externe hulpprogramma's mogelijk is, terwijl de flexibiliteit en controle die nodig is voor productietoepassingen behouden blijft.

Volledig voorbeeld

# 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())

Volgende stappen