GitHub Copilot

Microsoft Agent Framework, arka uç olarak GitHub Copilot SDK'sını kullanan aracılar oluşturmayı destekler. GitHub Copilot aracıları kabuk komutu yürütme, dosya işlemleri, URL getirme ve Model Bağlam Protokolü (MCP) sunucu tümleştirmesi gibi güçlü kodlama odaklı yapay zeka özelliklerine erişim sağlar.

Important

GitHub Copilot aracıları kimliği doğrulanmış bir GitHub Copilot çalışma zamanı gerektirir. Bazı SDK'lar yüklü bir CLI kullanırken Go SDK'sı varsayılan olarak paketlenmiş çalışma zamanını kullanır. Güvenlik için kapsayıcılı bir ortamda (Docker/Dev Kapsayıcısı) kabuk veya dosya izinlerine sahip aracıların çalıştırılması önerilir.

Getting Started

Projenize gerekli NuGet paketlerini ekleyin.

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

GitHub Copilot Aracısı Oluşturma

İlk adım olarak bir CopilotClient oluşturun ve başlatın. Ardından bir aracı oluşturmak için uzantı yöntemini kullanın AsAIAgent .

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

Araçlar ve Yönergelerle

Aracıyı oluştururken işlev araçları ve özel yönergeler sağlayabilirsiniz:

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

Temsilci Özellikleri

Akış Yanıtları

Oluşturulan yanıtları alın:

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

Oturum Yönetimi

Oturumları kullanarak birden çok etkileşimde konuşma bağlamı sağlama:

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

Varsayılan olarak, aracı kabuk komutlarını yürütemez, dosyaları okuyamaz/yazamaz veya URL'leri getiremez. Bu özellikleri etkinleştirmek için aracılığıyla SessionConfigbir izin işleyicisi sağlayın:

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

Araç Onayı

GitHub Copilot SDK'sı araç çağırma döngüsüne sahip olduğundan, özel işlev araçları için onay standart Agent Framework onayı gidiş dönüş yerine SDK'nın yerel yürütme öncesi kancası aracılığıyla zorlanır. içinde sarmalanmış bir aracı kaydettiğinizde ApprovalRequiredAIFunctionaracı, bu araç için döndüren "ask" bir varsayılan OnPreToolUse kanca yükler ve kararı işleyicinize OnPermissionRequest yönlendirir:

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

aracılığıyla SessionConfig.Hookskendi OnPreToolUse kancanızı sağlarsanız öncelik kazanır ve aracı varsayılan onay kancasını yüklemez. Daha sonra, kaydolduysanız (örneğin, bir "deny" veya "ask" karar döndürerek) onayını ApprovalRequiredAIFunction zorunlu tutmaktan tamamen siz sorumlu olursunuz. Aracı, kancanızın işlemesi gereken onay gerektiren araçları adlandıran bir uyarı kaydeder.

MCP Sunucuları

Genişletilmiş özellikler için yerel (stdio) veya uzak (HTTP) MCP sunucularına bağlanın:

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

İpucu

Çalıştırılabilir örneklerin tamamı için .NET örneklerine bakın.

Tools

Araç Statü Notlar
İşlev Araçları Standart AIFunction örnekler.
Araç Onayı Çerçevenin işlev çağırma destekli sohbet istemcisi tarafından sağlanır; herhangi bir işlev aracı çağrısıyla çalışır.
Kod Yorumlayıcısı Copilot CLI özelliği değildir.
Dosya Arama Copilot CLI özelliği değildir.
Web Araması Barındırılan bir araç olarak kullanıma sunulmaz.
Komut satırı / dosya sistemi / URL alma Copilot CLI çalışma zamanına yerleşiktir ve sağladığınız Permissions işleyicisinin denetimine tabidir.
Barındırılan MCP Araçları SessionConfig.McpServers aracılığıyla yapılandırılan uzak (HTTP) MCP sunucuları. Bkz. MCP Sunucuları.
Yerel MCP Araçları SessionConfig.McpServers aracılığıyla yapılandırılan yerel (stdio) MCP sunucuları. Bkz. MCP Sunucuları.

Ajanı Kullanma

Aracı, standart bir AIAgent'dir ve tüm standart AIAgent işlemlerini destekler.

Aracıları çalıştırma ve aracılarla etkileşim kurma hakkında daha fazla bilgi için bkz. Aracı kullanmaya başlama öğreticileri.

Prerequisites

Microsoft Agent Framework GitHub Copilot paketini yükleyin.

pip install agent-framework-github-copilot

Configuration

Aracı isteğe bağlı olarak aşağıdaki ortam değişkenleri kullanılarak yapılandırılabilir:

Değişken Description
GITHUB_COPILOT_CLI_PATH Copilot CLI yürütülebilir dosyasının yolu
GITHUB_COPILOT_MODEL Kullanılacak model (örn. , gpt-5claude-sonnet-4)
GITHUB_COPILOT_TIMEOUT İstek zaman aşımı süresi (saniye cinsinden)
GITHUB_COPILOT_LOG_LEVEL CLI günlük düzeyi
GITHUB_COPILOT_BASE_DIRECTORY CLI oturum durumu ve yapılandırması dizini (varsayılan olarak ~/.copilot)

Getting Started

Gerekli sınıfları Agent Framework'ten içeri aktarın:

import asyncio
from agent_framework.github import GitHubCopilotAgent, GitHubCopilotOptions

GitHub Copilot Aracısı Oluşturma

Temel Ajan Oluşturma

GitHub Copilot aracısı oluşturmanın en basit yolu:

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)

Açık Yapılandırma ile

aracılığıyla default_optionsaçık yapılandırma sağlayabilirsiniz:

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)

İpucu

default_options(ve çalıştırma optionsbaşına ) Copilot SDK'create_sessionları tarafından kabul edilen herhangi bir parametreyi (örneğinreasoning_effort, , context_tier, enable_citationsprovider (kendi anahtarını getir) veya skill_directories yalnızca burada gösterilen anahtarları değil iletir. Bilinmeyen parametre adları bir TypeErroroluşturur, bu nedenle yazım hataları sessizce yoksaymak yerine yakalanılır.

Kendi anahtarını getir (BYOK)

Model isteklerini GitHub Copilot arka ucu yerine kendi OpenAI, Azure OpenAI, Anthropic veya OpenAI uyumlu uç noktanız üzerinden yönlendirmek için Copilot SDK'sının BYOK desteğini kullanın. üzerinden geçin ProviderConfigGitHubCopilotOptions(provider=...)ve hem sağlayıcı yapılandırmasında hem de oturum düzeyi model seçeneğinde aynı model tanımlayıcısını ayarlayın.

Çalıştırılabilir örnek şu ortam değişkenlerini kullanır:

Değişken Description
BYOK_PROVIDER_TYPE Sağlayıcı türü: openai, azureveya anthropic. Varsayılan değer openai’dır.
BYOK_BASE_URL Sağlayıcı uç noktasının temel URL'si.
BYOK_API_KEY Sağlayıcı uç noktası için statik API anahtarı.
BYOK_MODEL_ID İstenecek model tanımlayıcısı. Varsayılan değer gpt-4o’dır.

Warning

BYOK statik kimlik bilgilerini kullanır ve otomatik belirteç yenilemesi sağlamaz. API anahtarlarını kaynak denetiminden uzak tutun ve ortam değişkenlerinden veya gizli dizi deposundan yükleyin. Kullanım ve faturalama, GitHub yerine sağlayıcınız tarafından izlenir.

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

Temsilci Özellikleri

Bağlam Sağlayıcıları

Python GitHubCopilotAgent da destekler context_providers=[...]. Sağlayıcılar her çağrıdan önce ve sonra çalışır, bu nedenle sağlayıcı tarafından eklenen iletiler ve yönergeler Copilot istemine dahil edilir ve geçmiş sağlayıcıları son yanıtı gözlemleyebilir.

from agent_framework import InMemoryHistoryProvider

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

Yerleşik geçmiş sağlayıcılarını özel bağlam sağlayıcılarıyla birleştirebilirsiniz. Uygulama desenleri için bkz. Bağlam Sağlayıcıları.

İşlev Araçları

Ajanınızı özel işlevlerle donatın.

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)

Akış Yanıtları

Daha iyi bir kullanıcı deneyimi için oluşturulan yanıtları alın:

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

Thread Yönetimi

Birden çok etkileşimde konuşma bağlamını koru.

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

Varsayılan olarak, aracı kabuk komutlarını yürütemez, dosyaları okuyamaz/yazamaz veya URL'leri getiremez. Bu özellikleri etkinleştirmek için bir izin işleyicisi sağlayın:

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)

Tüm izinlerin otomatik olarak onaylanması gereken güvenilir ortamlar için yerleşik PermissionHandler.approve_all kullanın:

from copilot.session import PermissionHandler

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

İzin işleyicileri hem senkron hem de asenkron geri çağrı işlevlerini destekler. Olay döngüsünü engellememek için asenkron işleyicilerde etkileşimli istemler için asyncio.to_thread kullanın.

Araç Onayı

GitHub Copilot SDK'sı araç çağırma döngüsüne sahip olduğundan, özel işlev araçları için onay standart Agent Framework onayı gidiş dönüş yerine SDK'nın yerel yürütme öncesi kancası aracılığıyla zorlanır. ile approval_mode="always_require" bildirilen bir aracı kaydettiğinizde ve kendi on_pre_tool_use kancanızı sağlamadığınızda, aracı bu araç için döndüren "ask" bir varsayılan kanca yükler ve kararı işleyicinize on_permission_request yönlendirir:

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

Kendi on_pre_tool_use kancanızı sağlarsanız öncelik kazanır ve aracı varsayılan onay kancasını yüklemez . Daha sonra herhangi bir approval_mode="always_require" araç için onay uygulamaktan tamamen sorumlu olursunuz (örneğin, bir "deny" veya "ask" karar döndürerek). Aracı, kancanızın işlemesi gereken onay gerektiren araçları adlandıran bir uyarı kaydeder. Varsayılan tümünü reddet izin işleyicisiyle, onaylayan on_permission_requestbir kablo göndermediğiniz sürece bir always_require araç reddedilir.

MCP Sunucuları

Genişletilmiş özellikler için yerel (stdio) veya uzak (HTTP) MCP sunucularına bağlanın:

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 yerleşik OpenTelemetry izleme özelliğine sahiptir. Başlangıçta bir kez configure_otel_providers() çağırarak her çalışma için ölçümleri, günlükleri ve aralıkları etkinleştirin.

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

Telemetri katmanı olmadan temel aracıya ihtiyacınız varsa (örneğin, özel bir katmana sarmak için), RawGitHubCopilotAgent öğesini agent_framework.github içeri aktarın.

OTLP ihracatçıları ve daha zengin örnekler için gözlemlenebilirlik örneklerine bakın.

Tools

Araç Statü Notlar
İşlev Araçları Standart Python çağrılabilir nesneleri veya @ai_function.
Araç Onayı Çerçevenin işlev çağırma destekli sohbet istemcisi tarafından sağlanır; herhangi bir işlev aracı çağrısıyla çalışır.
Kod Yorumlayıcısı Copilot CLI özelliği değildir.
Dosya Arama Copilot CLI özelliği değildir.
Web Araması Barındırılan bir araç olarak kullanıma sunulmaz.
Komut satırı / dosya sistemi / URL alma Copilot CLI çalışma zamanına yerleşiktir ve sağladığınız Permissions işleyicisinin denetimine tabidir.
Barındırılan MCP Araçları default_options["mcp_servers"] aracılığıyla yapılandırılan uzak (HTTP) MCP sunucuları. Bkz. MCP Sunucuları.
Yerel MCP Araçları default_options["mcp_servers"] aracılığıyla yapılandırılan yerel (stdio) MCP sunucuları. Bkz. MCP Sunucuları.

Ajanı Kullanma

Aracı standart bir BaseAgent'dir ve tüm standart aracı işlemleri destekler.

Aracıları çalıştırma ve aracılarla etkileşim kurma hakkında daha fazla bilgi için bkz. Aracı kullanmaya başlama öğreticileri.

Getting Started

Microsoft Agent Framework Go modülünü ve Go için GitHub Copilot SDK'sını yükleyin. Agent Framework Go SDK'sı Go 1.25 veya üzerini gerektirir.

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

GitHub Copilot Aracısı Oluşturma

copilot.Client oluşturup başlatın, ardından bunu copilotprovider.NewAgent öğesine geçirin.

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)

Araçlar ve Yönergelerle

Aracıyı oluştururken işlev araçları ve özel yönergeler sağlayabilirsiniz:

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)

Temsilci Özellikleri

Akış Yanıtları

Oluşturulan yanıtları alın:

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

Oturum Yönetimi

Oturumları kullanarak birden çok etkileşimde konuşma bağlamı sağlama:

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

Varsayılan olarak, aracı kabuk komutlarını yürütemez, dosyaları okuyamaz/yazamaz veya URL'leri getiremez. Bu özellikleri etkinleştirmek için aracılığıyla copilot.SessionConfigbir izin işleyicisi sağlayın:

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 Sunucuları

Genişletilmiş özellikler için yerel (stdio) veya uzak (HTTP) MCP sunucularına bağlanın:

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)

İpucu

Tam bir çalıştırılabilir örnek için Go GitHub Copilot örneğine bakın.

Tools

Araç Statü Notlar
İşlev Araçları tool.Tool işlevleri de dahil olmak üzere, Standart Go functool örnekleri.
Araç Onayı Fonksiyon araçları standart Go araç onayı desteğini kullanabilir; Copilot çalışma zamanı izinleri SessionConfig.OnPermissionRequest tarafından yönetilir.
Kod Yorumlayıcısı Copilot CLI özelliği değildir.
Dosya Arama Copilot CLI özelliği değildir.
Web Araması Barındırılan bir araç olarak kullanıma sunulmaz.
Komut satırı / dosya sistemi / URL alma Copilot CLI çalışma zamanına yerleşiktir ve sağladığınız Permissions işleyicisinin denetimine tabidir.
Barındırılan MCP Araçları copilot.SessionConfig.MCPServers aracılığıyla yapılandırılan uzak (HTTP) MCP sunucuları. Bkz. MCP Sunucuları.
Yerel MCP Araçları copilot.SessionConfig.MCPServers aracılığıyla yapılandırılan yerel (stdio) MCP sunucuları. Bkz. MCP Sunucuları.

Ajanı Kullanma

Aracı standart bir *agent.Agent'dir ve tüm standart aracı işlemleri destekler.

Aracıları çalıştırma ve aracılarla etkileşim kurma hakkında daha fazla bilgi için bkz. Aracı kullanmaya başlama öğreticileri.

Sonraki Adımlar