GitHub Copilot

Microsoft Agent Framework mendukung pembuatan agen yang menggunakan GitHub Copilot SDK sebagai backend mereka. Agen GitHub Copilot menyediakan akses ke kemampuan AI berorientasi pengkodian yang kuat, termasuk eksekusi perintah shell, operasi file, pengambilan URL, dan integrasi server Protokol Konteks Model (MCP).

Important

agen GitHub Copilot memerlukan runtime GitHub Copilot yang diautentikasi. Beberapa SDK menggunakan CLI yang diinstal, sementara Go SDK menggunakan runtime yang dibundel secara default. Untuk keamanan, disarankan untuk menjalankan agen dengan izin shell atau file di lingkungan kontainer (Docker/Dev Container).

Getting Started

Tambahkan paket NuGet yang diperlukan ke proyek Anda.

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

Membuat Agen GitHub Copilot

Sebagai langkah pertama, buat CopilotClient dan mulai. Kemudian gunakan AsAIAgent metode ekstensi untuk membuat agen.

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

Dengan Alat dan Instruksi

Anda dapat memberikan alat fungsi dan instruksi kustom saat membuat agen:

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

Fitur Agen

Respons yang Mengalir

Dapatkan respons saat dihasilkan:

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

Manajemen Sesi

Pertahankan konteks percakapan di beberapa interaksi menggunakan sesi:

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

Secara default, agen tidak dapat menjalankan perintah shell, membaca/menulis file, atau mengambil URL. Untuk mengaktifkan kemampuan ini, berikan penangan izin melalui 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"));

Persetujuan Alat

Karena SDK GitHub Copilot memiliki perulangan panggilan alat, persetujuan untuk alat fungsi kustom diberlakukan melalui kait pra-eksekusi asli SDK daripada persetujuan Kerangka Kerja Agen standar pulang pergi. Ketika Anda mendaftarkan alat yang dibungkus dalam ApprovalRequiredAIFunction, agen menginstal kait default OnPreToolUse yang kembali "ask" untuk alat tersebut dan merutekan keputusan ke handler Anda OnPermissionRequest :

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

Warning

Jika Anda memberikan kait Anda sendiri OnPreToolUse melalui SessionConfig.Hooks, itu diutamakan dan agen tidak menginstal kait persetujuan defaultnya. Anda kemudian bertanggung jawab penuh untuk memberlakukan persetujuan untuk setiap yang ApprovalRequiredAIFunction Anda daftarkan (misalnya, dengan mengembalikan keputusan "deny" atau "ask" ). Agen mencatat peringatan penamaan alat yang diperlukan persetujuan yang harus ditangani oleh kait Anda.

Server MCP

Sambungkan ke server MCP lokal (stdio) atau jarak jauh (HTTP) untuk kemampuan yang diperluas:

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

Tip

Lihat sampel .NET untuk contoh lengkap yang dapat dijalankan.

Tools

Alat Status Notes
Peralatan Fungsional Instans standar AIFunction .
Persetujuan Alat Disediakan oleh klien chat pemanggil fungsi milik framework; kompatibel dengan panggilan alat/fungsi apa pun.
Penerjemah Kode Bukan kemampuan Copilot CLI.
Pencarian File Bukan kemampuan Copilot CLI.
Pencarian Web Tidak diekspos sebagai alat yang dihosting.
Shell / sistem berkas / pengambilan URL Terintegrasi ke dalam runtime CLI Copilot dan dikendalikan oleh handler Permissions yang Anda sediakan.
Alat MCP yang Dihosting Server MCP jarak jauh (HTTP) dikonfigurasi melalui SessionConfig.McpServers. Lihat Server MCP.
Alat MCP Lokal Server MCP lokal (stdio) dikonfigurasi melalui SessionConfig.McpServers. Lihat Server MCP.

Menggunakan Agen

Agen adalah standar AIAgent dan mendukung semua operasi standar AIAgent .

Untuk informasi selengkapnya tentang cara menjalankan dan berinteraksi dengan agen, lihat tutorial Memulai Agen.

Prasyarat

Instal paket Microsoft Agent Framework GitHub Copilot.

pip install agent-framework-github-copilot

Configuration

Agen dapat dikonfigurasi secara opsional menggunakan variabel lingkungan berikut:

Variabel Description
GITHUB_COPILOT_CLI_PATH Jalur ke Copilot CLI yang dapat dieksekusi
GITHUB_COPILOT_MODEL Model yang akan digunakan (misalnya, gpt-5, claude-sonnet-4)
GITHUB_COPILOT_TIMEOUT Meminta batas waktu dalam detik
GITHUB_COPILOT_LOG_LEVEL Tingkat log CLI
GITHUB_COPILOT_BASE_DIRECTORY Direktori untuk status sesi CLI dan konfigurasi (default ke ~/.copilot)

Getting Started

Impor kelas yang diperlukan dari Agent Framework:

import asyncio
from agent_framework.github import GitHubCopilotAgent, GitHubCopilotOptions

Membuat Agen GitHub Copilot

Pembuatan Agen Dasar

Cara paling sederhana untuk membuat agen 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)

Dengan Konfigurasi Eksplisit

Anda dapat menyediakan konfigurasi eksplisit melalui 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)

Tip

default_options(dan per-eksekusi options) meneruskan parameter apa pun yang diterima oleh SDK create_session Copilot — misalnya reasoning_effort, , context_tier, enable_citationsprovider (bring-your-own-key), atau skill_directories — bukan hanya kunci yang ditampilkan di sini. Nama parameter yang tidak diketahui menaikkan TypeError, sehingga kesalahan ketik ditangkap daripada diabaikan secara diam-diam.

Bawa Kunci Anda Sendiri (BYOK)

Gunakan dukungan BYOK SDK Copilot untuk merutekan permintaan model melalui titik akhir OpenAI, Azure OpenAI, Anthropic, atau yang kompatibel dengan OpenAI Anda sendiri, bukan backend GitHub Copilot. Teruskan ProviderConfigGitHubCopilotOptions(provider=...), dan atur pengidentifikasi model yang sama di konfigurasi penyedia dan opsi tingkat model sesi.

Sampel yang dapat dijalankan menggunakan variabel lingkungan ini:

Variabel Description
BYOK_PROVIDER_TYPE Jenis penyedia: openai, azure, atau anthropic. Secara default menjadi openai.
BYOK_BASE_URL URL dasar untuk titik akhir penyedia.
BYOK_API_KEY Kunci API statis untuk titik akhir penyedia.
BYOK_MODEL_ID Pengidentifikasi model untuk diminta. Secara default menjadi gpt-4o.

Warning

BYOK menggunakan kredensial statis dan tidak menyediakan refresh token otomatis. Jauhkan kunci API dari kontrol sumber dan muat dari variabel lingkungan atau penyimpanan rahasia. Penggunaan dan penagihan dilacak oleh penyedia Anda daripada 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")

Fitur Agen

Penyedia Konteks

Python GitHubCopilotAgent juga mendukung context_providers=[...]. Penyedia berjalan sebelum dan sesudah setiap pemanggilan dilakukan, sehingga pesan dan instruksi yang ditambahkan oleh penyedia disertakan dalam prompt Copilot, dan penyedia riwayat dapat mengamati respons akhir.

from agent_framework import InMemoryHistoryProvider

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

Anda dapat menggabungkan penyedia riwayat bawaan dengan penyedia konteks kustom. Untuk pola implementasi, lihat Penyedia Konteks.

Perangkat Fungsional

Lengkapi agen Anda dengan fungsi kustom:

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)

Respons yang Mengalir

Dapatkan respons saat dihasilkan untuk pengalaman pengguna yang lebih baik:

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

Manajemen Utas

Pertahankan konteks percakapan di beberapa interaksi:

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

Secara default, agen tidak dapat menjalankan perintah shell, membaca/menulis file, atau mengambil URL. Untuk mengaktifkan kemampuan ini, berikan pengelola izin:

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)

Untuk lingkungan tepercaya di mana semua izin harus disetujui secara otomatis, gunakan bawaan PermissionHandler.approve_all:

from copilot.session import PermissionHandler

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

Penangan izin mendukung panggilan balik sinkronisasi dan asinkron. Gunakan asyncio.to_thread untuk perintah interaktif dalam handler asinkron untuk menghindari pemblokiran perulangan peristiwa.

Persetujuan Alat

Karena SDK GitHub Copilot memiliki perulangan panggilan alat, persetujuan untuk alat fungsi kustom diberlakukan melalui kait pra-eksekusi asli SDK daripada persetujuan Kerangka Kerja Agen standar pulang pergi. Ketika Anda mendaftarkan alat yang dideklarasikan dengan approval_mode="always_require" dan tidak menyediakan kait Anda sendiri on_pre_tool_use , agen menginstal kait default yang kembali "ask" untuk alat itu dan merutekan keputusan ke handler Anda on_permission_request :

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

Warning

Jika Anda memberikan kait Anda sendiri on_pre_tool_use , itu diutamakan dan agen tidak menginstal kait persetujuan defaultnya. Anda kemudian bertanggung jawab penuh untuk memberlakukan persetujuan untuk alat apa pun approval_mode="always_require" (misalnya, dengan mengembalikan keputusan "deny" atau "ask" ). Agen mencatat peringatan penamaan alat yang diperlukan persetujuan yang harus ditangani oleh kait Anda. Dengan penangan izin tolak-semua default, alat always_require ditolak kecuali Anda mengirim kawat on_permission_requestyang menyetujui .

Server MCP

Sambungkan ke server MCP lokal (stdio) atau jarak jauh (HTTP) untuk kemampuan yang diperluas:

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 memiliki pelacakan OpenTelemetry bawaan. Panggil configure_otel_providers() sekali saat startup untuk mengaktifkan rentang, metrik, dan log untuk setiap proses:

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

Jika Anda memerlukan agen yang mendasar tanpa lapisan telemetri (misalnya untuk membungkusnya dalam yang kustom), impor RawGitHubCopilotAgent dari agent_framework.github.

Untuk eksportir OTLP dan contoh yang lebih kaya, lihat contoh observabilitas.

Tools

Alat Status Notes
Peralatan Fungsional Panggilan Python standar atau @ai_function.
Persetujuan Alat Disediakan oleh klien chat pemanggil fungsi milik framework; kompatibel dengan panggilan alat/fungsi apa pun.
Penerjemah Kode Bukan kemampuan Copilot CLI.
Pencarian File Bukan kemampuan Copilot CLI.
Pencarian Web Tidak diekspos sebagai alat yang dihosting.
Shell / sistem berkas / pengambilan URL Terintegrasi ke dalam runtime CLI Copilot dan dikendalikan oleh handler Permissions yang Anda sediakan.
Alat MCP yang Dihosting Server MCP jarak jauh (HTTP) dikonfigurasi melalui default_options["mcp_servers"]. Lihat Server MCP.
Alat MCP Lokal Server MCP lokal (stdio) dikonfigurasi melalui default_options["mcp_servers"]. Lihat Server MCP.

Menggunakan Agen

Agen ini adalah BaseAgent standar dan mendukung semua operasi agen standar.

Untuk informasi selengkapnya tentang cara menjalankan dan berinteraksi dengan agen, lihat tutorial Memulai Agen.

Getting Started

Instal modul Microsoft Agent Framework Go dan SDK GitHub Copilot untuk Go. Agent Framework Go SDK memerlukan Go 1.25 atau yang lebih baru.

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

Membuat Agen GitHub Copilot

Buat dan mulai copilot.Client, lalu teruskan ke 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)

Dengan Alat dan Instruksi

Anda dapat memberikan alat fungsi dan instruksi kustom saat membuat agen:

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)

Fitur Agen

Respons yang Mengalir

Dapatkan respons saat dihasilkan:

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

Manajemen Sesi

Pertahankan konteks percakapan di beberapa interaksi menggunakan sesi:

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

Secara default, agen tidak dapat menjalankan perintah shell, membaca/menulis file, atau mengambil URL. Untuk mengaktifkan kemampuan ini, berikan penangan izin melalui 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

Sambungkan ke server MCP lokal (stdio) atau jarak jauh (HTTP) untuk kemampuan yang diperluas:

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)

Tip

Lihat sampel Go GitHub Copilot untuk contoh lengkap yang dapat dijalankan.

Tools

Alat Status Notes
Peralatan Fungsional Instans Standard Go tool.Tool , termasuk functool fungsi.
Persetujuan Alat alat fungsi dapat menggunakan dukungan persetujuan standar untuk alat Go; izin runtime Copilot ditangani oleh SessionConfig.OnPermissionRequest.
Penerjemah Kode Bukan kemampuan Copilot CLI.
Pencarian File Bukan kemampuan Copilot CLI.
Pencarian Web Tidak diekspos sebagai alat yang dihosting.
Shell / sistem berkas / pengambilan URL Terintegrasi ke dalam runtime CLI Copilot dan dikendalikan oleh handler Permissions yang Anda sediakan.
Alat MCP yang Dihosting Server MCP jarak jauh (HTTP) dikonfigurasi melalui copilot.SessionConfig.MCPServers. Lihat Server MCP.
Alat MCP Lokal Server MCP lokal (stdio) dikonfigurasi melalui copilot.SessionConfig.MCPServers. Lihat Server MCP.

Menggunakan Agen

Agen ini adalah *agent.Agent standar dan mendukung semua operasi agen standar.

Untuk informasi selengkapnya tentang cara menjalankan dan berinteraksi dengan agen, lihat tutorial Memulai Agen.

Langkah berikutnya