GitHub Copilot-Agenten

Microsoft Agent Framework unterstützt das Erstellen von Agents, die das GitHub Copilot SDK als Back-End verwenden. GitHub Copilot-Agents bieten Zugriff auf leistungsstarke codierungsorientierte KI-Funktionen, einschließlich Shell-Befehlsausführung, Dateivorgänge, URL-Abruf und MCP-Serverintegration (Model Context Protocol).

Von Bedeutung

GitHub Copilot Agents benötigen eine authentifizierte GitHub Copilot Laufzeit. Einige SDKs verwenden eine installierte CLI, während das Go SDK standardmäßig die gebündelte Laufzeit verwendet. Zur Sicherheit wird empfohlen, Agents mit Shell- oder Dateiberechtigungen in einer containerisierten Umgebung (Docker/Dev Container) auszuführen.

Erste Schritte

Fügen Sie dem Projekt die erforderlichen NuGet-Pakete hinzu.

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

Einen GitHub Copilot-Agent erstellen

Erstellen Sie als ersten Schritt eine CopilotClient und starten Sie sie. Verwenden Sie dann die AsAIAgent Erweiterungsmethode, um einen Agent zu erstellen.

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

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

AIAgent agent = copilotClient.AsAIAgent();

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

Mit Tools und Anweisungen

Sie können Beim Erstellen des Agents Funktionstools und benutzerdefinierte Anweisungen bereitstellen:

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?"));

Agentfeatures

Streaming-Antworten

Erhalten Sie Antworten, während sie generiert werden:

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

AIAgent agent = copilotClient.AsAIAgent();

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

Console.WriteLine();

Sitzungsverwaltung

Den Gesprächskontext über mehrere Interaktionen hinweg mithilfe von Sitzungen beibehalten.

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"

Erlaubnisse

Standardmäßig kann der Agent keine Shellbefehle ausführen, Dateien lesen/schreiben oder URLs abrufen. Um diese Funktionen zu aktivieren, richten Sie einen Berechtigungshandler über SessionConfig ein:

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"));

MCP-Server

Stellen Sie eine Verbindung mit lokalen (Stdio) oder REMOTE-MCP-Servern (HTTP) für erweiterte Funktionen her:

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

SessionConfig sessionConfig = new()
{
    OnPermissionRequest = PromptPermission,
    McpServers = new Dictionary<string, object>
    {
        // Local stdio server
        ["filesystem"] = new McpLocalServerConfig
        {
            Type = "stdio",
            Command = "npx",
            Args = ["-y", "@modelcontextprotocol/server-filesystem", "."],
            Tools = ["*"],
        },
        // Remote HTTP server
        ["microsoft-learn"] = new McpRemoteServerConfig
        {
            Type = "http",
            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"));

Tipp

Vollständige Runnable-Beispiele finden Sie in den .NET-Beispielen .

Tools

Werkzeug Status Hinweise
Funktionswerkzeuge Standardinstanzen AIFunction.
Toolgenehmigung Bereitgestellt durch den Chatclient des Frameworks zum Aufrufen von Funktionen; funktioniert mit jedem Funktions- oder Tool-Aufruf.
Codedolmetscher Keine Copilot CLI-Funktion.
Dateisuche Keine Copilot CLI-Funktion.
Websuche Nicht als gehostetes Tool verfügbar gemacht.
Shell/Dateisystem/URL-Abruf In die Copilot CLI-Laufzeit integriert und durch den von Ihnen bereitgestellten Permissions-Handler abgesichert.
Gehostete MCP-Tools Remote-(HTTP-)MCP-Server, konfiguriert über SessionConfig.McpServers. Siehe MCP-Server.
Lokale MCP-Tools Lokale (stdio)-MCP-Server, die über SessionConfig.McpServers konfiguriert sind. Siehe MCP-Server.

Den Agent verwenden

Der Agent ist ein AIAgent Standard und unterstützt alle AIAgent Standardoperationen.

Weitere Informationen zum Ausführen und Interagieren mit Agenten finden Sie in den Agenten-Einführungstutorials.

Voraussetzungen

Installieren Sie das GitHub Copilot-Paket von Microsoft Agent Framework.

pip install agent-framework-github-copilot --pre

Konfiguration

Der Agent kann optional mithilfe der folgenden Umgebungsvariablen konfiguriert werden:

Variable Description
GITHUB_COPILOT_CLI_PATH Pfad zur ausführbaren Datei der Copilot CLI
GITHUB_COPILOT_MODEL Zu verwendende Modell (z. B. gpt-5, claude-sonnet-4)
GITHUB_COPILOT_TIMEOUT Anforderungstimeout in Sekunden
GITHUB_COPILOT_LOG_LEVEL CLI-Protokollebene
GITHUB_COPILOT_BASE_DIRECTORY Verzeichnis für CLI-Sitzungszustand und Konfiguration (Standardeinstellung ~/.copilot)

Erste Schritte

Importieren Sie die erforderlichen Klassen aus dem Agent-Framework:

import asyncio
from agent_framework.github import GitHubCopilotAgent, GitHubCopilotOptions

Einen GitHub Copilot-Agent erstellen

Grundlegende Agent-Erstellung

Die einfachste Möglichkeit zum Erstellen eines GitHub Copilot-Agents:

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)

Mit expliziter Konfiguration

Sie können eine explizite Konfiguration über default_options bereitstellen.

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)

Agentfeatures

Kontextanbieter

Python GitHubCopilotAgent unterstützt context_providers=[...]auch . Anbieter werden vor und nach jedem Aufruf ausgeführt, sodass vom Anbieter hinzugefügte Nachrichten und Anweisungen in der Copilot-Eingabeaufforderung enthalten sind und Verlaufsanbieter die endgültige Antwort beobachten können.

from agent_framework import InMemoryHistoryProvider

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

Sie können integrierte Verlaufsanbieter mit benutzerdefinierten Kontextanbietern kombinieren. Implementierungsmuster finden Sie unter Kontextanbieter.

Funktionstools

Rüsten Sie Ihren Agent mit benutzerdefinierten Funktionen aus:

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)

Streaming-Antworten

Erhalten Sie Antworten, wenn sie generiert werden, um eine bessere Benutzererfahrung zu erzielen:

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

Threadverwaltung

Den Gesprächskontext über mehrere Interaktionen hinweg beibehalten.

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"

Erlaubnisse

Standardmäßig kann der Agent keine Shellbefehle ausführen, Dateien lesen/schreiben oder URLs abrufen. Um diese Funktionen zu aktivieren, geben Sie einen Berechtigungshandler an:

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)

Verwenden Sie für vertrauenswürdige Umgebungen, in denen alle Berechtigungen automatisch genehmigt werden sollen, die integrierte PermissionHandler.approve_all:

from copilot.session import PermissionHandler

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

Berechtigungs-Handler unterstützen sowohl synchrone als auch asynchrone Callbacks. Verwenden Sie asyncio.to_thread für interaktive Abfragen in asynchronen Handlern, um ein Blockieren der Ereignisschleife zu vermeiden.

MCP-Server

Stellen Sie eine Verbindung mit lokalen (Stdio) oder REMOTE-MCP-Servern (HTTP) für erweiterte Funktionen her:

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)

Observierbarkeit

GitHubCopilotAgent verfügt über integriertes OpenTelemetry-Tracing. Rufen Sie einmal beim Start auf configure_otel_providers() , um Spannen, Metriken und Protokolle für jede Ausführung zu aktivieren:

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!")

Wenn Sie den zugrunde liegenden Agent ohne die Telemetrieebene benötigen (z. B. um ihn in eine benutzerdefinierte Lösung einzubinden), importieren Sie RawGitHubCopilotAgent von agent_framework.github.

Für OTLP-Exporteure und umfangreichere Beispiele finden Sie die Observability-Beispiele.

Tools

Werkzeug Status Hinweise
Funktionswerkzeuge Normale Python-aufrufbare Objekte oder @ai_function.
Toolgenehmigung Bereitgestellt durch den Chatclient des Frameworks zum Aufrufen von Funktionen; funktioniert mit jedem Funktions- oder Tool-Aufruf.
Codedolmetscher Keine Copilot CLI-Funktion.
Dateisuche Keine Copilot CLI-Funktion.
Websuche Nicht als gehostetes Tool verfügbar gemacht.
Shell/Dateisystem/URL-Abruf In die Copilot CLI-Laufzeit integriert und durch den von Ihnen bereitgestellten Permissions-Handler gesteuert.
Gehostete MCP-Tools Remote-(HTTP-)MCP-Server, konfiguriert über default_options["mcp_servers"]. Siehe MCP-Server.
Lokale MCP-Tools Lokale (stdio)-MCP-Server, die über default_options["mcp_servers"] konfiguriert sind. Siehe MCP-Server.

Den Agent verwenden

Der Agent ist ein Standard BaseAgent und unterstützt alle Standard-Agent-Vorgänge.

Weitere Informationen zum Ausführen und Interagieren mit Agenten finden Sie in den Agenten-Einführungstutorials.

Erste Schritte

Installieren Sie das Microsoft Agent Framework Go-Modul und das GitHub Copilot SDK für Go. Das Agent Framework Go SDK erfordert Go 1.25 oder höher.

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

Einen GitHub Copilot-Agent erstellen

Erstellen und starten Sie ein copilot.Client, und übergeben Sie es an 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)

Mit Tools und Anweisungen

Sie können Beim Erstellen des Agents Funktionstools und benutzerdefinierte Anweisungen bereitstellen:

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)

Agentfeatures

Streaming-Antworten

Erhalten Sie Antworten, während sie generiert werden:

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

Sitzungsverwaltung

Den Gesprächskontext über mehrere Interaktionen hinweg mithilfe von Sitzungen beibehalten.

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)

Erlaubnisse

Standardmäßig kann der Agent keine Shellbefehle ausführen, Dateien lesen/schreiben oder URLs abrufen. Um diese Funktionen zu aktivieren, richten Sie einen Berechtigungshandler über copilot.SessionConfig ein:

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)

MCP-Server

Stellen Sie eine Verbindung mit lokalen (Stdio) oder REMOTE-MCP-Servern (HTTP) für erweiterte Funktionen her:

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)

Tipp

Ein vollständiges Runnable-Beispiel finden Sie im Beispiel "Go GitHub Copilot".

Tools

Werkzeug Status Hinweise
Funktionswerkzeuge Standard-Go-Instanzentool.Tool, einschließlich functool-Funktionen.
Toolgenehmigung Funktions-Tools können die Standardunterstützung für die Genehmigung von Go-Tools verwenden; Copilot-Laufzeitberechtigungen werden von SessionConfig.OnPermissionRequest verwaltet.
Codedolmetscher Keine Copilot CLI-Funktion.
Dateisuche Keine Copilot CLI-Funktion.
Websuche Nicht als gehostetes Tool verfügbar gemacht.
Shell/Dateisystem/URL-Abruf In die Copilot CLI-Laufzeit integriert und durch den von Ihnen bereitgestellten Permissions-Handler gesteuert.
Gehostete MCP-Tools Remote-(HTTP-)MCP-Server, konfiguriert über copilot.SessionConfig.MCPServers. Siehe MCP-Server.
Lokale MCP-Tools Lokale (stdio)-MCP-Server, die über copilot.SessionConfig.MCPServers konfiguriert sind. Siehe MCP-Server.

Den Agent verwenden

Der Agent ist ein Standard *agent.Agent und unterstützt alle Standard-Agent-Vorgänge.

Weitere Informationen zum Ausführen und Interagieren mit Agenten finden Sie in den Agenten-Einführungstutorials.

Nächste Schritte