Condividi tramite


Uso degli strumenti MCP con gli agenti Foundry

È possibile estendere le funzionalità dell'agente Azure AI Foundry connettendolo agli strumenti ospitati su server remoti Model Context Protocol (MCP) (fornire il proprio endpoint per server MCP).

Come usare lo strumento Model Context Protocol

Questa sezione illustra come creare un agente di intelligenza artificiale usando Azure Foundry (Azure AI) con un'integrazione del server MCP (Model Context Protocol) ospitata. L'agente può usare gli strumenti MCP gestiti ed eseguiti dal servizio Azure Foundry, consentendo l'accesso sicuro e controllato alle risorse esterne.

Funzionalità principali

  • Server MCP ospitato: il server MCP è ospitato e gestito da Azure AI Foundry, eliminando la necessità di gestire l'infrastruttura server
  • Agenti permanenti: gli agenti vengono creati e archiviati sul lato server, consentendo conversazioni con stato
  • Flusso di lavoro di approvazione degli strumenti: meccanismi di approvazione configurabili per le chiamate allo strumento MCP

Funzionamento

1. Installazione dell'ambiente

L'esempio richiede due variabili di ambiente:

  • AZURE_FOUNDRY_PROJECT_ENDPOINT: URL dell'endpoint del progetto Azure AI Foundry
  • AZURE_FOUNDRY_PROJECT_MODEL_ID: il nome della distribuzione del modello (per impostazione predefinita è "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. Configurazione agente

L'agente è configurato con istruzioni e metadati specifici:

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

Viene creato un agente specializzato per rispondere alle domande usando la documentazione di Microsoft Learn.

3. Definizione dello strumento MCP

L'esempio crea una definizione di strumento MCP che punta a un server MCP ospitato:

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

Componenti chiave:

  • serverLabel: identificatore univoco per l'istanza del server MCP
  • serverUrl: URL del server MCP ospitato
  • AllowedTools: specifica gli strumenti del server MCP che l'agente può usare

4. Creazione dell'agente persistente

L'agente viene creato sul lato server usando 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]);

Avviso

DefaultAzureCredential è utile per lo sviluppo, ma richiede un'attenta considerazione nell'ambiente di produzione. Nell'ambiente di produzione prendere in considerazione l'uso di credenziali specifiche ,ad esempio ManagedIdentityCredential, per evitare problemi di latenza, probe di credenziali indesiderate e potenziali rischi per la sicurezza dai meccanismi di fallback.

Verrà creato un agente permanente che:

  • Si trova nel servizio Azure AI Foundry
  • Ha accesso agli strumenti MCP specificati
  • Può mantenere lo stato della conversazione tra più interazioni

5. Recupero ed esecuzione dell'agente

L'agente creato viene recuperato come AIAgent istanza:

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

6. Configurazione delle risorse dello strumento

L'esempio configura le risorse dello strumento con le impostazioni di approvazione:

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

Configurazione chiave:

  • MCPToolResource: collega l'istanza del server MCP all'esecuzione dell'agente
  • RequireApproval: controlla quando è necessaria l'approvazione dell'utente per le chiamate allo strumento
    • "never": gli strumenti vengono eseguiti automaticamente senza approvazione
    • "always": tutte le chiamate agli strumenti richiedono l'approvazione dell'utente
    • È anche possibile configurare regole di approvazione personalizzate

7. Esecuzione dell'agente

L'agente viene richiamato con una domanda ed eseguito usando gli strumenti MCP configurati:

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

L'esempio illustra la pulizia corretta delle risorse:

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

Azure AI Foundry offre una perfetta integrazione con i server MCP (Model Context Protocol) tramite Python Agent Framework. Il servizio gestisce l'hosting e l'esecuzione del server MCP, eliminando la gestione dell'infrastruttura fornendo al tempo stesso l'accesso sicuro e controllato agli strumenti esterni.

Configurazione dell'ambiente

Configurare le credenziali del progetto Azure AI Foundry tramite le variabili di ambiente:

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

Integrazione MCP di base

Creare un agente di Azure AI Foundry con strumenti MCP ospitati:

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

Configurazione mcp multi-strumento

Usare più strumenti MCP ospitati con un singolo agente:

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 Agent Framework offre una perfetta integrazione con le funzionalità MCP ospitate di Azure AI Foundry, consentendo l'accesso sicuro e scalabile agli strumenti esterni, mantenendo al tempo stesso la flessibilità e il controllo necessari per le applicazioni di produzione.

Esempio completo

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

Passaggi successivi