Condividi tramite


Uso degli strumenti MCP con gli agenti

Model Context Protocol è uno standard aperto che definisce il modo in cui le applicazioni forniscono strumenti e dati contestuali a modelli di linguaggio di grandi dimensioni. Consente l'integrazione coerente e scalabile di strumenti esterni nei flussi di lavoro del modello.

Microsoft Agent Framework supporta l'integrazione con i server MCP (Model Context Protocol), consentendo agli agenti di accedere a strumenti e servizi esterni. Questa guida illustra come connettersi a un server MCP e usare i relativi strumenti all'interno dell'agente.

Considerazioni sull'uso di server MCP di terze parti

L'uso dei server Model Context Protocol è soggetto alle condizioni tra l'utente e il provider di servizi. Quando ci si connette a un servizio non Microsoft, alcuni dati , ad esempio il contenuto della richiesta, vengono passati al servizio non Microsoft oppure l'applicazione potrebbe ricevere dati dal servizio non Microsoft. L'utente è responsabile dell'uso di dati e servizi non Microsoft, oltre a eventuali addebiti associati a tale utilizzo.

I server MCP remoti che si decide di usare con lo strumento MCP descritto in questo articolo sono stati creati da terze parti, non da Microsoft. Microsoft non ha testato o verificato questi server. Microsoft non ha alcuna responsabilità per l'utente o altri utenti in relazione all'uso di qualsiasi server MCP remoto.

È consigliabile esaminare attentamente e tenere traccia dei server MCP aggiunti alle applicazioni basate su Agent Framework. È anche consigliabile affidarsi a server ospitati da provider di servizi attendibili anziché proxy.

Lo strumento MCP consente di passare intestazioni personalizzate, ad esempio chiavi di autenticazione o schemi, necessarie per un server MCP remoto. È consigliabile esaminare tutti i dati condivisi con i server MCP remoti e registrare i dati a scopo di controllo. Essere consapevoli delle procedure non Microsoft per la conservazione e la posizione dei dati.

Importante

È possibile specificare le intestazioni solo includendole in tool_resources a ogni esecuzione. In questo modo, è possibile inserire chiavi API, token di accesso OAuth o altre credenziali direttamente nella richiesta. Le intestazioni passate sono disponibili solo per l'esecuzione corrente e non sono persistenti.

Per altre informazioni sulla sicurezza MCP, vedere:

La versione .NET di Agent Framework può essere usata insieme all'SDK C# MCP ufficiale per consentire all'agente di chiamare gli strumenti MCP.

L'esempio seguente illustra come:

  1. Configurare e server MCP
  2. Recuperare l'elenco degli strumenti disponibili dal server MCP
  3. Convertire gli strumenti MCP in AIFunctionin modo che possano essere aggiunti a un agente
  4. Richiamare gli strumenti da un agente usando la chiamata di funzione

Configurazione di un client MCP

Creare prima di tutto un client MCP che si connette al server MCP desiderato:

// Create an MCPClient for the GitHub server
await using var mcpClient = await McpClientFactory.CreateAsync(new StdioClientTransport(new()
{
    Name = "MCPServer",
    Command = "npx",
    Arguments = ["-y", "--verbose", "@modelcontextprotocol/server-github"],
}));

In questo esempio:

  • Nome: nome descrittivo per la connessione al server MCP
  • Comando: eseguibile per eseguire il server MCP (in questo caso usando npx per eseguire un pacchetto di Node.js)
  • Argomenti: argomenti della riga di comando passati al server MCP

Recupero degli strumenti disponibili

Dopo la connessione, recuperare l'elenco degli strumenti disponibili dal server MCP:

// Retrieve the list of tools available on the GitHub server
var mcpTools = await mcpClient.ListToolsAsync().ConfigureAwait(false);

Il ListToolsAsync() metodo restituisce una raccolta di strumenti esposti dal server MCP. Questi strumenti vengono convertiti automaticamente in oggetti AITool che possono essere usati dall'agente.

Creare un agente con strumenti MCP

Creare l'agente e fornire gli strumenti MCP durante l'inizializzazione:

AIAgent agent = new AzureOpenAIClient(
    new Uri(endpoint),
    new DefaultAzureCredential())
     .GetChatClient(deploymentName)
     .AsAIAgent(
         instructions: "You answer questions related to GitHub repositories only.",
         tools: [.. mcpTools.Cast<AITool>()]);

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.

Punti chiave:

  • Istruzioni: fornire istruzioni chiare che si allineano alle funzionalità degli strumenti MCP
  • Strumenti: eseguire il cast degli strumenti MCP agli AITool oggetti e distribuirli nella matrice di strumenti
  • L'agente avrà automaticamente accesso a tutti gli strumenti forniti dal server MCP

Uso dell'agente

Dopo la configurazione, l'agente può usare automaticamente gli strumenti MCP per soddisfare le richieste degli utenti:

// Invoke the agent and output the text result
Console.WriteLine(await agent.RunAsync("Summarize the last four commits to the microsoft/semantic-kernel repository?"));

L'agente:

  1. Analizzare la richiesta dell'utente
  2. Determinare quali strumenti MCP sono necessari
  3. Chiamare gli strumenti appropriati tramite il server MCP
  4. Sintetizzare i risultati in una risposta coerente

Configurazione dell'ambiente

Assicurarsi di configurare le variabili di ambiente necessarie:

var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ??
    throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";

Gestione risorse

Eliminare sempre correttamente le risorse client MCP:

await using var mcpClient = await McpClientFactory.CreateAsync(...);

L'uso await using garantisce che la connessione client MCP venga chiusa correttamente quando esce dall'ambito.

Server MCP comuni

I server MCP più diffusi includono:

  • @modelcontextprotocol/server-github: accedere a repository e dati GitHub
  • @modelcontextprotocol/server-filesystem: operazioni del file system
  • @modelcontextprotocol/server-sqlite: accesso al database SQLite

Ogni server offre diversi strumenti e funzionalità che estendono le funzionalità dell'agente. Questa integrazione consente agli agenti di accedere facilmente a dati e servizi esterni mantenendo al tempo stesso i vantaggi di sicurezza e standardizzazione del protocollo di contesto del modello.

Il codice sorgente completo e le istruzioni per eseguire questo esempio sono disponibili all'indirizzo https://github.com/microsoft/agent-framework/tree/main/dotnet/samples/GettingStarted/ModelContextProtocol/Agent_MCP_Server.

In questo modo gli agenti possono accedere facilmente a strumenti e servizi esterni.

Tipi di strumenti MCP

Agent Framework supporta tre tipi di connessioni MCP:

MCPStdioTool - Server MCP locali

Usare MCPStdioTool per connettersi ai server MCP eseguiti come processi locali usando input/output standard:

import asyncio
from agent_framework import Agent, MCPStdioTool
from agent_framework.openai import OpenAIChatClient

async def local_mcp_example():
    """Example using a local MCP server via stdio."""
    async with (
        MCPStdioTool(
            name="calculator",
            command="uvx",
            args=["mcp-server-calculator"]
        ) as mcp_server,
        Agent(
            chat_client=OpenAIChatClient(),
            name="MathAgent",
            instructions="You are a helpful math assistant that can solve calculations.",
        ) as agent,
    ):
        result = await agent.run(
            "What is 15 * 23 + 45?",
            tools=mcp_server
        )
        print(result)

if __name__ == "__main__":
    asyncio.run(local_mcp_example())

MCPStreamableHTTPTool - Server MCP HTTP/SSE

Usare MCPStreamableHTTPTool per connettersi ai server MCP tramite HTTP con eventi Server-Sent:

import asyncio
from agent_framework import Agent, MCPStreamableHTTPTool
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential

async def http_mcp_example():
    """Example using an HTTP-based MCP server."""
    async with (
        AzureCliCredential() as credential,
        MCPStreamableHTTPTool(
            name="Microsoft Learn MCP",
            url="https://learn.microsoft.com/api/mcp",
            headers={"Authorization": "Bearer your-token"},
        ) as mcp_server,
        Agent(
            chat_client=AzureAIAgentClient(async_credential=credential),
            name="DocsAgent",
            instructions="You help with Microsoft documentation questions.",
        ) as agent,
    ):
        result = await agent.run(
            "How to create an Azure storage account using az cli?",
            tools=mcp_server
        )
        print(result)

if __name__ == "__main__":
    asyncio.run(http_mcp_example())

MCPWebsocketTool - Server MCP WebSocket

Usare MCPWebsocketTool per connettersi ai server MCP tramite connessioni WebSocket:

import asyncio
from agent_framework import Agent, MCPWebsocketTool
from agent_framework.openai import OpenAIChatClient

async def websocket_mcp_example():
    """Example using a WebSocket-based MCP server."""
    async with (
        MCPWebsocketTool(
            name="realtime-data",
            url="wss://api.example.com/mcp",
        ) as mcp_server,
        Agent(
            chat_client=OpenAIChatClient(),
            name="DataAgent",
            instructions="You provide real-time data insights.",
        ) as agent,
    ):
        result = await agent.run(
            "What is the current market status?",
            tools=mcp_server
        )
        print(result)

if __name__ == "__main__":
    asyncio.run(websocket_mcp_example())

Server MCP comuni che è possibile usare con Python Agent Framework:

  • Calcolatrice: uvx mcp-server-calculator - Calcoli matematici
  • File system: uvx mcp-server-filesystem - Operazioni del file system
  • GitHub: npx @modelcontextprotocol/server-github - Accesso al repository GitHub
  • SQLite: uvx mcp-server-sqlite - Operazioni di database

Ogni server offre diversi strumenti e funzionalità che estendono le funzionalità dell'agente mantenendo al tempo stesso i vantaggi di sicurezza e standardizzazione del protocollo di contesto del modello.

Esempio completo

# Copyright (c) Microsoft. All rights reserved.

import os

from agent_framework import Agent, MCPStreamableHTTPTool
from agent_framework.openai import OpenAIResponsesClient
from httpx import AsyncClient

"""
MCP Authentication Example

This example demonstrates how to authenticate with MCP servers using API key headers.

For more authentication examples including OAuth 2.0 flows, see:
- https://github.com/modelcontextprotocol/python-sdk/tree/main/examples/clients/simple-auth-client
- https://github.com/modelcontextprotocol/python-sdk/tree/main/examples/servers/simple-auth
"""


async def api_key_auth_example() -> None:
    """Example of using API key authentication with MCP server."""
    # Configuration
    mcp_server_url = os.getenv("MCP_SERVER_URL", "your-mcp-server-url")
    api_key = os.getenv("MCP_API_KEY")

    # Create authentication headers
    # Common patterns:
    # - Bearer token: "Authorization": f"Bearer {api_key}"
    # - API key header: "X-API-Key": api_key
    # - Custom header: "Authorization": f"ApiKey {api_key}"
    auth_headers = {
        "Authorization": f"Bearer {api_key}",
    }

    # Create HTTP client with authentication headers
    http_client = AsyncClient(headers=auth_headers)

    # Create MCP tool with the configured HTTP client
    async with (
        MCPStreamableHTTPTool(
            name="MCP tool",
            description="MCP tool description",
            url=mcp_server_url,
            http_client=http_client,  # Pass HTTP client with authentication headers
        ) as mcp_tool,
        Agent(
            client=OpenAIResponsesClient(),
            name="Agent",
            instructions="You are a helpful assistant.",
            tools=mcp_tool,
        ) as agent,
    ):
        query = "What tools are available to you?"
        print(f"User: {query}")
        result = await agent.run(query)
        print(f"Agent: {result.text}")

Esposizione di un agente come server MCP

È possibile esporre un agente come server MCP, consentendo di usarlo come strumento da qualsiasi client compatibile con MCP (ad esempio, agenti GitHub Copilot di VS Code o altri agenti). Il nome e la descrizione dell'agente diventano i metadati del server MCP.

Eseguire il wrapping dell'agente in uno strumento di funzione usando .AsAIFunction(), creare un McpServerToole registrarlo con un server MCP:

using System;
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ModelContextProtocol.Server;

// Create the agent
AIAgent agent = new AzureOpenAIClient(
    new Uri("https://<myresource>.openai.azure.com"),
    new AzureCliCredential())
        .GetChatClient("gpt-4o-mini")
        .AsAIAgent(instructions: "You are good at telling jokes.", name: "Joker");

// Convert the agent to an MCP tool
McpServerTool tool = McpServerTool.Create(agent.AsAIFunction());

// Set up the MCP server over stdio
HostApplicationBuilder builder = Host.CreateEmptyApplicationBuilder(settings: null);
builder.Services
    .AddMcpServer()
    .WithStdioServerTransport()
    .WithTools([tool]);

await builder.Build().RunAsync();

Installare i pacchetti NuGet necessari:

dotnet add package Microsoft.Extensions.Hosting --prerelease
dotnet add package ModelContextProtocol --prerelease

Chiamare .as_mcp_server() su un agente per esporlo come server MCP:

from agent_framework.openai import OpenAIResponsesClient
from typing import Annotated

def get_specials() -> Annotated[str, "Returns the specials from the menu."]:
    return "Special Soup: Clam Chowder, Special Salad: Cobb Salad"

# Create an agent with tools
agent = OpenAIResponsesClient().as_agent(
    name="RestaurantAgent",
    description="Answer questions about the menu.",
    tools=[get_specials],
)

# Expose the agent as an MCP server
server = agent.as_mcp_server()

Configurare il server MCP per l'ascolto su input/output standard:

import anyio
from mcp.server.stdio import stdio_server

async def run():
    async with stdio_server() as (read_stream, write_stream):
        await server.run(read_stream, write_stream, server.create_initialization_options())

if __name__ == "__main__":
    anyio.run(run)

Passaggi successivi