GitHub Copilot

Microsoft Agent Framework supporta la creazione di agenti che usano GitHub Copilot SDK come back-end. Gli agenti di GitHub Copilot forniscono l'accesso a potenti funzionalità di intelligenza artificiale orientate alla codifica, tra cui l'esecuzione dei comandi della shell, le operazioni di file, il recupero di URL e l'integrazione del server MCP (Model Context Protocol).

Importante

gli agenti GitHub Copilot richiedono un runtime di GitHub Copilot autenticato. Alcuni SDK usano una CLI installata, mentre l'SDK Go usa per impostazione predefinita il runtime integrato. Per motivi di sicurezza, è consigliabile eseguire agenti con autorizzazioni shell o file in un ambiente in contenitori (contenitore Docker/Dev).

Getting Started

Aggiungere i pacchetti NuGet necessari al progetto.

dotnet add package Microsoft.Agents.AI.GitHub.Copilot

Creare un agente Copilot di GitHub

Come primo passaggio, creare un CopilotClient e avviarlo. Usare quindi il AsAIAgent metodo di estensione per creare un agente.

using GitHub.Copilot;
using Microsoft.Agents.AI;

await using CopilotClient copilotClient = new();
await copilotClient.StartAsync();

AIAgent agent = copilotClient.AsAIAgent(sessionConfig: null);

Console.WriteLine(await agent.RunAsync("What is Microsoft Agent Framework?"));

Con strumenti e istruzioni

È possibile fornire strumenti per le funzioni e istruzioni personalizzate durante la creazione dell'agente:

using GitHub.Copilot;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

AIFunction weatherTool = AIFunctionFactory.Create((string location) =>
{
    return $"The weather in {location} is sunny with a high of 25C.";
}, "GetWeather", "Get the weather for a given location.");

await using CopilotClient copilotClient = new();
await copilotClient.StartAsync();

AIAgent agent = copilotClient.AsAIAgent(
    tools: [weatherTool],
    instructions: "You are a helpful weather agent.");

Console.WriteLine(await agent.RunAsync("What's the weather like in Seattle?"));

Funzionalità dell'agente

Risposte in streaming

Ottenere risposte man mano che vengono generate:

await using CopilotClient copilotClient = new();
await copilotClient.StartAsync();

AIAgent agent = copilotClient.AsAIAgent(sessionConfig: null);

await foreach (AgentResponseUpdate update in agent.RunStreamingAsync("Tell me a short story."))
{
    Console.Write(update);
}

Console.WriteLine();

Gestione delle sessioni

Mantenere il contesto della conversazione tra più interazioni usando sessioni:

await using CopilotClient copilotClient = new();
await copilotClient.StartAsync();

await using GitHubCopilotAgent agent = new(
    copilotClient,
    instructions: "You are a helpful assistant. Keep your answers short.");

AgentSession session = await agent.CreateSessionAsync();

// First turn
await agent.RunAsync("My name is Alice.", session);

// Second turn - agent remembers the context
AgentResponse response = await agent.RunAsync("What is my name?", session);
Console.WriteLine(response); // Should mention "Alice"

Permissions

Per impostazione predefinita, l'agente non può eseguire comandi della shell, file di lettura/scrittura o recuperare GLI URL. Per abilitare queste funzionalità, fornire un gestore di autorizzazioni tramite SessionConfig:

static Task<PermissionDecision> PromptPermission(
    PermissionRequest request, PermissionInvocation invocation)
{
    Console.WriteLine($"\n[Permission Request: {request.Kind}]");
    Console.Write("Approve? (y/n): ");

    string? input = Console.ReadLine()?.Trim().ToUpperInvariant();
    PermissionDecision decision = input is "Y" or "YES"
        ? PermissionDecision.ApproveOnce()
        : PermissionDecision.Reject();

    return Task.FromResult(decision);
}

await using CopilotClient copilotClient = new();
await copilotClient.StartAsync();

SessionConfig sessionConfig = new()
{
    OnPermissionRequest = PromptPermission,
};

AIAgent agent = copilotClient.AsAIAgent(sessionConfig);

Console.WriteLine(await agent.RunAsync("List all files in the current directory"));

Approvazione degli strumenti

Poiché GitHub Copilot SDK è proprietario del ciclo di chiamata degli strumenti, l'approvazione per gli strumenti di funzione personalizzati viene applicata tramite l'hook di pre-esecuzione nativo dell'SDK anziché il round trip di approvazione standard di Agent Framework. Quando si registra uno strumento sottoposto a wrapping in ApprovalRequiredAIFunction, l'agente installa un hook predefinito OnPreToolUse che restituisce "ask" per tale strumento e indirizza la decisione al OnPermissionRequest gestore:

using GitHub.Copilot;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

AIFunction deleteFile = AIFunctionFactory.Create(
    (string path) => $"Deleted {path}.",
    "DeleteFile",
    "Deletes a file.");

await using CopilotClient copilotClient = new();
await copilotClient.StartAsync();

SessionConfig sessionConfig = new()
{
    // Wrapping the tool marks it approval-required; the agent turns this into an "ask" at OnPreToolUse.
    Tools = [new ApprovalRequiredAIFunction(deleteFile)],

    // OnPermissionRequest decides the "asked" tools (and Copilot's built-in shell/file/URL prompts).
    OnPermissionRequest = PromptPermission,
};

AIAgent agent = copilotClient.AsAIAgent(sessionConfig);

Console.WriteLine(await agent.RunAsync("Delete the file temp.txt"));

Avvertimento

Se si fornisce il proprio OnPreToolUse hook tramite SessionConfig.Hooks, ha la precedenza e l'agente non installa il relativo hook di approvazione predefinito. L'utente è quindi completamente responsabile dell'applicazione dell'approvazione per qualsiasi ApprovalRequiredAIFunction registrazione(ad esempio, restituendo una "deny" decisione o "ask" ). L'agente registra un avviso che assegna un nome a qualsiasi strumento necessario per l'approvazione che deve essere gestito dall'hook.

Server MCP

Connettersi ai server MCP locali (stdio) o remoti (HTTP) per le funzionalità estese:

await using CopilotClient copilotClient = new();
await copilotClient.StartAsync();

SessionConfig sessionConfig = new()
{
    OnPermissionRequest = PromptPermission,
    McpServers = new Dictionary<string, McpServerConfig>
    {
        // Local stdio server
        ["filesystem"] = new McpStdioServerConfig
        {
            Command = "npx",
            Args = ["-y", "@modelcontextprotocol/server-filesystem", "."],
            Tools = ["*"],
        },
        // Remote HTTP server
        ["microsoft-learn"] = new McpHttpServerConfig
        {
            Url = "https://learn.microsoft.com/api/mcp",
            Tools = ["*"],
        },
    },
};

AIAgent agent = copilotClient.AsAIAgent(sessionConfig);

Console.WriteLine(await agent.RunAsync("Search Microsoft Learn for 'Azure Functions' and summarize the top result"));

Tools

Strumento Condizione Note
Strumenti per le funzioni Istanze standard AIFunction.
Approvazione degli strumenti Fornito dal client di chat del framework per l'invocazione di funzioni; funziona con qualsiasi chiamata a uno strumento funzione.
Interprete di codice Non è una funzionalità di Copilot CLI.
Ricerca file Non è una funzionalità di Copilot CLI.
Ricerca Web Non disponibile come strumento ospitato.
Shell / file system / recupero degli URL Integrato nel runtime della CLI di Copilot e controllato dal gestore Permissions fornito.
Strumenti MCP ospitati Server MCP remoti (HTTP) configurati tramite SessionConfig.McpServers. Vedere Server MCP.
Strumenti MCP locali Server MCP locali (stdio) configurati tramite SessionConfig.McpServers. Vedere Server MCP.

Uso dell'agente

L'agente è uno standard AIAgent e supporta tutte le operazioni standard AIAgent .

Per altre informazioni su come eseguire e interagire con gli agenti, vedere le esercitazioni introduttive su Agent.

Prerequisiti

Installare il pacchetto GitHub Copilot di Microsoft Agent Framework.

pip install agent-framework-github-copilot

Configuration

L'agente può essere configurato facoltativamente usando le variabili di ambiente seguenti:

Variabile Description
GITHUB_COPILOT_CLI_PATH Percorso dell'eseguibile di Copilot CLI
GITHUB_COPILOT_MODEL Modello da usare (ad esempio, gpt-5, claude-sonnet-4)
GITHUB_COPILOT_TIMEOUT Timeout della richiesta in secondi
GITHUB_COPILOT_LOG_LEVEL Livello di log CLI
GITHUB_COPILOT_BASE_DIRECTORY Directory per lo stato della sessione CLI e la configurazione (il valore predefinito è ~/.copilot)

Getting Started

Importare le classi necessarie da Agent Framework:

import asyncio
from agent_framework.github import GitHubCopilotAgent, GitHubCopilotOptions

Creare un agente Copilot di GitHub

Creazione dell'agente di base

Il modo più semplice per creare un agente Di GitHub Copilot:

async def basic_example():
    agent = GitHubCopilotAgent(
        instructions="You are a helpful assistant.",
    )

    async with agent:
        result = await agent.run("What is Microsoft Agent Framework?")
        print(result)

Con configurazione esplicita

È possibile fornire una configurazione esplicita tramite default_options:

async def explicit_config_example():
    agent = GitHubCopilotAgent(
        instructions="You are a helpful assistant.",
        default_options={
            "model": "gpt-5",
            "timeout": 120,
        },
    )

    async with agent:
        result = await agent.run("What can you do?")
        print(result)

Suggerimento

default_options(e per esecuzione options) inoltra qualsiasi parametro accettato dall'SDK di create_session Copilot, ad esempio reasoning_effort, context_tier, enable_citationsprovider (bring-your-own-key) o skill_directories non solo dalle chiavi mostrate qui. I nomi dei parametri sconosciuti generano un TypeErroroggetto , pertanto gli errori di digitazione vengono rilevati anziché ignorati automaticamente.

Bring Your Own Key (BYOK)

Usare il supporto BYOK di Copilot SDK per instradare le richieste del modello tramite openAI, Azure OpenAI, Anthropic o endpoint compatibile con OpenAI anziché il back-end GitHub Copilot. Passare un oggetto ProviderConfig through GitHubCopilotOptions(provider=...)e impostare lo stesso identificatore del modello sia nella configurazione del provider che nell'opzione a livello model di sessione.

L'esempio eseguibile usa queste variabili di ambiente:

Variabile Description
BYOK_PROVIDER_TYPE Tipo di provider: openai, azureo anthropic. Di default è openai.
BYOK_BASE_URL URL di base per l'endpoint del provider.
BYOK_API_KEY Chiave API statica per l'endpoint del provider.
BYOK_MODEL_ID Identificatore del modello da richiedere. Di default è gpt-4o.

Avvertimento

BYOK usa credenziali statiche e non fornisce l'aggiornamento automatico del token. Mantenere le chiavi API fuori dal controllo del codice sorgente e caricarle dalle variabili di ambiente o da un archivio segreto. L'utilizzo e la fatturazione vengono monitorati dal provider anziché GitHub.

import asyncio
import os
from typing import Literal, cast

from agent_framework.github import GitHubCopilotAgent, GitHubCopilotOptions
from copilot.session import ProviderConfig


async def main() -> None:
    print("=== GitHub Copilot Agent with BYOK (Bring Your Own Key) ===\n")

    model_id = os.environ.get("BYOK_MODEL_ID", "gpt-4o")
    provider_type = cast(Literal["openai", "azure", "anthropic"], os.environ.get("BYOK_PROVIDER_TYPE", "openai"))

    # ProviderConfig routes the session through a custom endpoint instead of the GitHub
    # Copilot backend. `wire_api="completions"` is the broadly compatible choice; use
    # "responses" for providers that support the OpenAI Responses API.
    provider: ProviderConfig = {
        "type": provider_type,
        "base_url": os.environ["BYOK_BASE_URL"],
        "api_key": os.environ["BYOK_API_KEY"],
        "wire_api": "completions",
        "model_id": model_id,
    }

    # BYOK requires the model to also be set at the session level.
    agent: GitHubCopilotAgent[GitHubCopilotOptions] = GitHubCopilotAgent(
        instructions="You are a helpful assistant.",
        default_options=GitHubCopilotOptions(model=model_id, provider=provider),
    )

    async with agent:
        query = "What are the benefits of using your own API keys with an agent framework?"
        print(f"User: {query}")
        result = await agent.run(query)
        print(f"\nAgent: {result}\n")

Funzionalità dell'agente

Provider di contesto

Python GitHubCopilotAgent supporta anche context_providers=[...]. I provider vengono eseguiti prima e dopo ogni invocazione, quindi i messaggi e le istruzioni aggiunti dai provider vengono inclusi nel prompt di Copilot e i provider di cronologia possono osservare la risposta finale.

from agent_framework import InMemoryHistoryProvider

agent = GitHubCopilotAgent(
    instructions="You are a helpful coding assistant.",
    context_providers=[InMemoryHistoryProvider()],
)

È possibile combinare provider di cronologia predefiniti con provider di contesto personalizzati. Per i modelli di implementazione, vedere Provider di contesto.

Strumenti per le funzioni

Equipaggiare l'agente con funzioni personalizzate:

from typing import Annotated
from pydantic import Field

def get_weather(
    location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
    """Get the weather for a given location."""
    return f"The weather in {location} is sunny with a high of 25C."

async def tools_example():
    agent = GitHubCopilotAgent(
        instructions="You are a helpful weather agent.",
        tools=[get_weather],
    )

    async with agent:
        result = await agent.run("What's the weather like in Seattle?")
        print(result)

Risposte in streaming

Ottenere risposte man mano che vengono generate per un'esperienza utente migliore:

async def streaming_example():
    agent = GitHubCopilotAgent(
        instructions="You are a helpful assistant.",
    )

    async with agent:
        print("Agent: ", end="", flush=True)
        async for chunk in agent.run("Tell me a short story.", stream=True):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()

Gestione dei thread

Mantenere il contesto della conversazione tra più interazioni:

async def thread_example():
    agent = GitHubCopilotAgent(
        instructions="You are a helpful assistant.",
    )

    async with agent:
        session = agent.create_session()

        # First interaction
        result1 = await agent.run("My name is Alice.", session=session)
        print(f"Agent: {result1}")

        # Second interaction - agent remembers the context
        result2 = await agent.run("What's my name?", session=session)
        print(f"Agent: {result2}")  # Should remember "Alice"

Permissions

Per impostazione predefinita, l'agente non può eseguire comandi della shell, file di lettura/scrittura o recuperare GLI URL. Per abilitare queste funzionalità, fornire un gestore di autorizzazioni:

import asyncio

from copilot.generated.rpc import PermissionDecisionDeniedInteractivelyByUser
from copilot.session import PermissionHandler, PermissionRequestResult
from copilot.session_events import PermissionRequest


async def prompt_permission(
    request: PermissionRequest, context: dict[str, str]
) -> PermissionRequestResult:
    print(f"\n[Permission Request: {request.kind}]")
    response = (await asyncio.to_thread(input, "Approve? (y/n): ")).strip().lower()
    if response in ("y", "yes"):
        return PermissionHandler.approve_all(request, context)
    return PermissionDecisionDeniedInteractivelyByUser()

async def permissions_example():
    agent = GitHubCopilotAgent(
        instructions="You are a helpful assistant that can execute shell commands.",
        default_options={
            "on_permission_request": prompt_permission,
        },
    )

    async with agent:
        result = await agent.run("List the Python files in the current directory")
        print(result)

Per gli ambienti attendibili in cui tutte le autorizzazioni devono essere approvate automaticamente, utilizzare l'elemento predefinito PermissionHandler.approve_all:

from copilot.session import PermissionHandler

agent = GitHubCopilotAgent(
    default_options={
        "on_permission_request": PermissionHandler.approve_all,
    },
)

I gestori di autorizzazioni supportano sia i callback sincroni che i callback asincroni. Usare asyncio.to_thread per le richieste interattive nei gestori asincroni per evitare di bloccare il ciclo di eventi.

Approvazione degli strumenti

Poiché GitHub Copilot SDK è proprietario del ciclo di chiamata degli strumenti, l'approvazione per gli strumenti di funzione personalizzati viene applicata tramite l'hook di pre-esecuzione nativo dell'SDK anziché il round trip di approvazione standard di Agent Framework. Quando si registra uno strumento dichiarato con approval_mode="always_require" e non si fornisce il proprio on_pre_tool_use hook, l'agente installa un hook predefinito che restituisce "ask" per tale strumento e indirizza la decisione al on_permission_request gestore:

from agent_framework import tool
from agent_framework.github import GitHubCopilotAgent, GitHubCopilotOptions
from copilot.session import PermissionHandler


@tool(approval_mode="always_require")
def delete_file(path: str) -> str:
    """Delete a file."""
    return f"Deleted {path}."


agent = GitHubCopilotAgent(
    tools=[delete_file],
    # The "ask" decision is routed here; approve or deny the call.
    default_options=GitHubCopilotOptions(on_permission_request=PermissionHandler.approve_all),
)

Avvertimento

Se si fornisce un hook personalizzato on_pre_tool_use , ha la precedenza e l'agente non installa il relativo hook di approvazione predefinito. Si è quindi completamente responsabili dell'applicazione dell'approvazione per qualsiasi approval_mode="always_require" strumento (ad esempio, restituendo una "deny" decisione o "ask" ). L'agente registra un avviso che assegna un nome a qualsiasi strumento necessario per l'approvazione che deve essere gestito dall'hook. Con il gestore di autorizzazioni deny-all predefinito, viene negato uno always_require strumento a meno che non si collega un oggetto approvazione on_permission_request.

Server MCP

Connettersi ai server MCP locali (stdio) o remoti (HTTP) per le funzionalità estese:

from copilot.session import MCPServerConfig, PermissionHandler

async def mcp_example():
    mcp_servers: dict[str, MCPServerConfig] = {
        # Local stdio server
        "filesystem": {
            "type": "stdio",
            "command": "npx",
            "args": ["-y", "@modelcontextprotocol/server-filesystem", "."],
            "tools": ["*"],
        },
        # Remote HTTP server
        "microsoft-learn": {
            "type": "http",
            "url": "https://learn.microsoft.com/api/mcp",
            "tools": ["*"],
        },
    }

    agent = GitHubCopilotAgent(
        instructions="You are a helpful assistant with access to the filesystem and Microsoft Learn.",
        default_options={
            "on_permission_request": PermissionHandler.approve_all,
            "mcp_servers": mcp_servers,
        },
    )

    async with agent:
        result = await agent.run("Search Microsoft Learn for 'Azure Functions' and summarize the top result")
        print(result)

Observability

GitHubCopilotAgent include la traccia OpenTelemetry predefinita. Chiamare configure_otel_providers() una sola volta all'avvio per abilitare intervalli, metriche e log per ogni esecuzione:

from agent_framework.observability import configure_otel_providers
from agent_framework.github import GitHubCopilotAgent

configure_otel_providers(enable_console_exporters=True)

async with GitHubCopilotAgent() as agent:
    response = await agent.run("Hello!")

Se è necessario l'agente sottostante, senza il livello di telemetria, ad esempio per incorporarlo in un'entità personalizzata, importare RawGitHubCopilotAgent da agent_framework.github.

Per gli esportatori OTLP ed esempi più avanzati, vedere gli esempi di osservabilità.

Tools

Strumento Condizione Note
Strumenti per le funzioni Oggetti richiamabili Python standard o @ai_function.
Approvazione degli strumenti Fornito dal client di chat del framework per l'invocazione di funzioni; funziona con qualsiasi chiamata a uno strumento funzione.
Interprete di codice Non è una funzionalità di Copilot CLI.
Ricerca file Non è una funzionalità di Copilot CLI.
Ricerca Web Non disponibile come strumento ospitato.
Shell / file system / recupero degli URL Integrato nel runtime della CLI di Copilot e controllato dal gestore Permissions fornito.
Strumenti MCP ospitati Server MCP remoti (HTTP) configurati tramite default_options["mcp_servers"]. Vedere Server MCP.
Strumenti MCP locali Server MCP locali (stdio) configurati tramite default_options["mcp_servers"]. Vedere Server MCP.

Uso dell'agente

L'agente è uno standard BaseAgent e supporta tutte le operazioni dell'agente standard.

Per altre informazioni su come eseguire e interagire con gli agenti, vedere le esercitazioni introduttive su Agent.

Getting Started

Installare il modulo Microsoft Agent Framework Go e GitHub Copilot SDK per Go. Agent Framework Go SDK richiede Go 1.25 o versione successiva.

go get github.com/microsoft/agent-framework-go github.com/github/copilot-sdk/go

Creare un agente Copilot di GitHub

Crea e avvia un copilot.Client, quindi passalo a copilotprovider.NewAgent.

import (
    "context"
    "fmt"

    copilot "github.com/github/copilot-sdk/go"
    "github.com/microsoft/agent-framework-go/provider/copilotprovider"
)

ctx := context.Background()

copilotClient := copilot.NewClient(nil)
if err := copilotClient.Start(ctx); err != nil {
    panic(err)
}
defer func() { _ = copilotClient.Stop() }()

copilotAgent := copilotprovider.NewAgent(
    copilotClient,
    copilotprovider.AgentConfig{
        Instructions: "You are a helpful assistant.",
    },
)

response, err := copilotAgent.RunText(ctx, "What is Microsoft Agent Framework?").Collect()
if err != nil {
    panic(err)
}
fmt.Println(response)

Con strumenti e istruzioni

È possibile fornire strumenti per le funzioni e istruzioni personalizzate durante la creazione dell'agente:

import (
    "context"
    "fmt"

    copilot "github.com/github/copilot-sdk/go"
    "github.com/microsoft/agent-framework-go/agent"
    "github.com/microsoft/agent-framework-go/provider/copilotprovider"
    "github.com/microsoft/agent-framework-go/tool"
    "github.com/microsoft/agent-framework-go/tool/functool"
)

weatherTool := functool.MustNew(
    functool.Config{
        Name:        "GetWeather",
        Description: "Get the weather for a given location.",
    },
    func(_ context.Context, location string) (string, error) {
        return fmt.Sprintf("The weather in %s is sunny with a high of 25C.", location), nil
    },
)

copilotAgent := copilotprovider.NewAgent(
    copilotClient,
    copilotprovider.AgentConfig{
        Instructions: "You are a helpful weather agent.",
        Config: agent.Config{
            Tools: []tool.Tool{weatherTool},
        },
    },
)

response, err := copilotAgent.RunText(ctx, "What's the weather like in Seattle?").Collect()
if err != nil {
    panic(err)
}
fmt.Println(response)

Funzionalità dell'agente

Risposte in streaming

Ottenere risposte man mano che vengono generate:

for update, err := range copilotAgent.RunText(ctx, "Tell me a short story.", agent.Stream(true)) {
    if err != nil {
        panic(err)
    }
    fmt.Print(update)
}

fmt.Println()

Gestione delle sessioni

Mantenere il contesto della conversazione tra più interazioni usando sessioni:

session, err := copilotAgent.CreateSession(ctx)
if err != nil {
    panic(err)
}

// First turn
response, err := copilotAgent.RunText(ctx, "My name is Alice.", agent.WithSession(session)).Collect()
if err != nil {
    panic(err)
}
fmt.Println(response)

// Second turn - the agent remembers the context
response, err = copilotAgent.RunText(ctx, "What is my name?", agent.WithSession(session)).Collect()
if err != nil {
    panic(err)
}
fmt.Println(response)

Permissions

Per impostazione predefinita, l'agente non può eseguire comandi della shell, file di lettura/scrittura o recuperare GLI URL. Per abilitare queste funzionalità, fornire un gestore di autorizzazioni tramite copilot.SessionConfig:

import (
    "bufio"
    "fmt"
    "os"
    "strings"

    copilot "github.com/github/copilot-sdk/go"
    "github.com/github/copilot-sdk/go/rpc"
    "github.com/microsoft/agent-framework-go/provider/copilotprovider"
)

func promptPermission(request copilot.PermissionRequest, _ copilot.PermissionInvocation) (rpc.PermissionDecision, error) {
    fmt.Printf("\n[Permission Request: %s]\n", request.Kind())
    fmt.Print("Approve? (y/n): ")

    input, _ := bufio.NewReader(os.Stdin).ReadString('\n')
    input = strings.TrimSpace(strings.ToUpper(input))
    if input == "Y" || input == "YES" {
        return &rpc.PermissionDecisionApproveOnce{}, nil
    }
    return &rpc.PermissionDecisionReject{}, nil
}

copilotAgent := copilotprovider.NewAgent(
    copilotClient,
    copilotprovider.AgentConfig{
        SessionConfig: &copilot.SessionConfig{
            OnPermissionRequest: promptPermission,
        },
    },
)

response, err := copilotAgent.RunText(ctx, "List all files in the current directory").Collect()
if err != nil {
    panic(err)
}
fmt.Println(response)

Server MCP

Connettersi ai server MCP locali (stdio) o remoti (HTTP) per le funzionalità estese:

import (
    copilot "github.com/github/copilot-sdk/go"
    "github.com/microsoft/agent-framework-go/provider/copilotprovider"
)

mcpServers := map[string]copilot.MCPServerConfig{
    // Local stdio server
    "filesystem": copilot.MCPStdioServerConfig{
        Command: "npx",
        Args:    []string{"-y", "@modelcontextprotocol/server-filesystem", "."},
        Tools:   []string{"*"},
    },
    // Remote HTTP server
    "microsoft-learn": copilot.MCPHTTPServerConfig{
        URL:   "https://learn.microsoft.com/api/mcp",
        Tools: []string{"*"},
    },
}

copilotAgent := copilotprovider.NewAgent(
    copilotClient,
    copilotprovider.AgentConfig{
        Instructions: "You are a helpful assistant with access to the filesystem and Microsoft Learn.",
        SessionConfig: &copilot.SessionConfig{
            OnPermissionRequest: promptPermission,
            MCPServers:          mcpServers,
        },
    },
)

response, err := copilotAgent.RunText(ctx, "Search Microsoft Learn for 'Azure Functions' and summarize the top result").Collect()
if err != nil {
    panic(err)
}
fmt.Println(response)

Suggerimento

Per un esempio eseguibile completo, vedere l'esempio go GitHub Copilot.

Tools

Strumento Condizione Note
Strumenti per le funzioni Istanze Go standard tool.Tool, incluse le funzioni functool.
Approvazione degli strumenti I tool di funzione possono usare il supporto standard per l’approvazione dei tool Go; le autorizzazioni di runtime di Copilot sono gestite da SessionConfig.OnPermissionRequest.
Interprete di codice Non è una funzionalità di Copilot CLI.
Ricerca file Non è una funzionalità di Copilot CLI.
Ricerca Web Non disponibile come strumento ospitato.
Shell / file system / recupero degli URL Integrato nel runtime della CLI di Copilot e controllato dal gestore Permissions fornito.
Strumenti MCP ospitati Server MCP remoti (HTTP) configurati tramite copilot.SessionConfig.MCPServers. Vedere Server MCP.
Strumenti MCP locali Server MCP locali (stdio) configurati tramite copilot.SessionConfig.MCPServers. Vedere Server MCP.

Uso dell'agente

L'agente è uno standard *agent.Agent e supporta tutte le operazioni dell'agente standard.

Per altre informazioni su come eseguire e interagire con gli agenti, vedere le esercitazioni introduttive su Agent.

Passaggi successivi