### Quick Start: Go Copilot Client Source: https://github.com/github/copilot-sdk/blob/main/docs/setup/bundled-cli.md Example of setting up and using the CopilotClient in Go. Note that the Go SDK does not bundle the CLI, requiring separate installation or configuration. This snippet demonstrates starting the client, creating a session, and sending a message. ```go package main import ( "context" "fmt" "log" copilot "github.com/github/copilot-sdk/go" ) func main() { ctx := context.Background() client := copilot.NewClient(nil) if err := client.Start(ctx); err != nil { log.Fatal(err) } defer client.Stop() session, _ := client.CreateSession(ctx, &copilot.SessionConfig{Model: "gpt-4.1"}) response, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: "Hello!"}) if d, ok := response.Data.(*copilot.AssistantMessageData); ok { fmt.Println(d.Content) } } ``` -------------------------------- ### Java Copilot SDK Quick Start Example Source: https://github.com/github/copilot-sdk/blob/main/java/README.md A basic Java example demonstrating how to create a CopilotClient, start a session, handle assistant messages and usage events, and send a prompt. ```java import com.github.copilot.CopilotClient; import com.github.copilot.generated.AssistantMessageEvent; import com.github.copilot.generated.SessionUsageInfoEvent; import com.github.copilot.rpc.MessageOptions; import com.github.copilot.rpc.PermissionHandler; import com.github.copilot.rpc.SessionConfig; public class CopilotSDK { public static void main(String[] args) throws Exception { var lastMessage = new String[]{null}; // Create and start client try (var client = new CopilotClient()) { client.start().get(); // Create a session var session = client.createSession( new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL).setModel("claude-sonnet-4.5")).get(); // Handle assistant message events session.on(AssistantMessageEvent.class, msg -> { lastMessage[0] = msg.getData().content(); System.out.println(lastMessage[0]); }); // Handle session usage info events session.on(SessionUsageInfoEvent.class, usage -> { var data = usage.getData(); System.out.println("\n--- Usage Metrics ---"); System.out.println("Current tokens: " + data.currentTokens().intValue()); System.out.println("Token limit: " + data.tokenLimit().intValue()); System.out.println("Messages count: " + data.messagesLength().intValue()); }); // Send a message var completable = session.sendAndWait(new MessageOptions().setPrompt("What is 2+2?")); // and wait for completion completable.get(); } boolean success = lastMessage[0] != null && lastMessage[0].contains("4"); System.exit(success ? 0 : -1); } } ``` -------------------------------- ### Quick Start: Python Copilot Client Source: https://github.com/github/copilot-sdk/blob/main/docs/setup/bundled-cli.md Example of initializing and using the CopilotClient in Python, including starting the client, creating a session with permission handling, sending a message, and stopping the client. Requires the SDK to be installed and runtime downloaded. ```python from copilot import CopilotClient from copilot.session import PermissionHandler client = CopilotClient() await client.start() session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model="gpt-4.1") response = await session.send_and_wait("Hello!") print(response.data.content) await client.stop() ``` -------------------------------- ### Start and Manage Copilot Client Source: https://github.com/github/copilot-sdk/blob/main/rust/README.md Demonstrates how to start a client, create or resume a session, and perform low-level RPC calls. Includes examples for health checks and client shutdown. ```rust use github_copilot_sdk::ClientOptions; // Start a client (spawns CLI process) let client = Client::start(options).await?; // Create a new session let session = client.create_session(config.with_permission_handler(handler)).await?; // Resume an existing session let session = client.resume_session(config.with_permission_handler(handler)).await?; // Low-level RPC let result = client.call("method.name", Some(params)).await?; let response = client.send_request("method.name", Some(params)).await?; // Health check (echoes message back, returns typed PingResponse) let pong = client.ping("hello").await?; // Shutdown client.stop().await?; ``` -------------------------------- ### Quick Start: Node.js/TypeScript Copilot Client Source: https://github.com/github/copilot-sdk/blob/main/docs/setup/bundled-cli.md Example of creating a CopilotClient, starting a session, sending a prompt, and receiving a response in Node.js or TypeScript. Ensure the SDK is installed. ```typescript import { CopilotClient } from "@github/copilot-sdk"; const client = new CopilotClient(); const session = await client.createSession({ model: "gpt-4.1" }); const response = await session.sendAndWait({ prompt: "Hello!" }); console.log(response?.data.content); await client.stop(); ``` -------------------------------- ### Install Go Copilot SDK Source: https://github.com/github/copilot-sdk/blob/main/docs/getting-started.md Install the GitHub Copilot SDK for Go using the go get command. ```bash go get github.com/github/copilot-sdk/go ``` -------------------------------- ### Quick Start: .NET Copilot Client Source: https://github.com/github/copilot-sdk/blob/main/docs/setup/bundled-cli.md Example demonstrating the usage of the CopilotClient in .NET, including creating a session, sending a prompt, and retrieving the response. The .NET SDK includes the CLI, simplifying setup. ```csharp await using var client = new CopilotClient(); await using var session = await client.CreateSessionAsync( new SessionConfig { Model = "gpt-4.1" }); var response = await session.SendAndWaitAsync( new MessageOptions { Prompt = "Hello!" }); Console.WriteLine(response?.Data.Content); ``` -------------------------------- ### Quick Start: Java Copilot Client Source: https://github.com/github/copilot-sdk/blob/main/docs/setup/bundled-cli.md Example for using the CopilotClient in Java. This snippet shows how to configure the CLI path, start the client, create a session, send a message, and print the response. The Java SDK requires manual configuration of the CLI path. ```java import com.github.copilot.CopilotClient; import com.github.copilot.rpc.*; var client = new CopilotClient(new CopilotClientOptions() // Point to the CLI binary installed on the system .setCliPath("/path/to/vendor/copilot") ); client.start().get(); var session = client.createSession(new SessionConfig() .setModel("gpt-4.1") .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) ).get(); var response = session.sendAndWait(new MessageOptions() .setPrompt("Hello!")).get(); System.out.println(response.getData().content()); client.stop().get(); ``` -------------------------------- ### start Source: https://github.com/github/copilot-sdk/blob/main/nodejs/README.md Starts the CLI server and establishes a connection. This is the initial step to enable SDK functionality. ```APIDOC ## start ### Description Starts the CLI server and establishes a connection. ### Method `start(): Promise` ### Parameters None ### Response - **Success Response**: Resolves with `void` upon successful startup. ``` -------------------------------- ### Install Go SDK Source: https://github.com/github/copilot-sdk/blob/main/docs/setup/choosing-a-setup-path.md Install the Go version of the Copilot SDK. This requires a separate CLI installation. ```bash go get github.com/github/copilot-sdk/go ``` -------------------------------- ### Install Copilot SDK Source: https://github.com/github/copilot-sdk/blob/main/nodejs/README.md Install the Copilot SDK using npm. ```bash npm install @github/copilot-sdk ``` -------------------------------- ### Install .NET SDK Source: https://github.com/github/copilot-sdk/blob/main/docs/setup/choosing-a-setup-path.md Install the .NET version of the Copilot SDK using the dotnet CLI. ```bash dotnet add package GitHub.Copilot.SDK ``` -------------------------------- ### Create Cloud Session in Go Source: https://github.com/github/copilot-sdk/blob/main/docs/features/cloud-sessions.md Example of creating a cloud session in Go, including repository details and permission handling. The client must be started before creating a session. ```go package main import ( "context" copilot "github.com/github/copilot-sdk/go" "github.com/github/copilot-sdk/go/rpc" ) func main() { _ = run(context.Background()) } func run(ctx context.Context) error { client := copilot.NewClient(nil) if err := client.Start(ctx); err != nil { return err } session, err := client.CreateSession(ctx, &copilot.SessionConfig{ Cloud: &copilot.CloudSessionOptions{ Repository: &copilot.CloudSessionRepository{ Owner: "github", Name: "copilot-sdk", Branch: "main", }, }, OnPermissionRequest: func(_ copilot.PermissionRequest, _ copilot.PermissionInvocation) (rpc.PermissionDecision, error) { return &rpc.PermissionDecisionApproveOnce{}, nil }, }) _ = session return err } ``` ```go client := copilot.NewClient(nil) if err := client.Start(ctx); err != nil { return err } session, err := client.CreateSession(ctx, &copilot.SessionConfig{ Cloud: &copilot.CloudSessionOptions{ Repository: &copilot.CloudSessionRepository{ Owner: "github", Name: "copilot-sdk", Branch: "main", }, }, OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (rpc.PermissionDecision, error) { return &rpc.PermissionDecisionApproveOnce{}, nil }, }) _ = session ``` -------------------------------- ### Quick Start: Initialize and Use CopilotClient Source: https://github.com/github/copilot-sdk/blob/main/dotnet/README.md Demonstrates creating, starting, and using a CopilotClient session to send a message and receive a response. Handles permission requests and session idle events. ```csharp using GitHub.Copilot; // Create and start client await using var client = new CopilotClient(); await client.StartAsync(); // Create a session (OnPermissionRequest is optional; ApproveAll allows every tool) await using var session = await client.CreateSessionAsync(new SessionConfig { Model = "gpt-5", OnPermissionRequest = PermissionHandler.ApproveAll, }); // Wait for the response using the session.idle event var done = new TaskCompletionSource(); session.On(evt => { if (evt is AssistantMessageEvent msg) { Console.WriteLine(msg.Data.Content); } else if (evt is SessionIdleEvent) { done.SetResult(); } }); // Send a message and wait for completion await session.SendAsync(new MessageOptions { Prompt = "What is 2+2?" }); await done.Task; ``` -------------------------------- ### Install Node.js SDK Source: https://github.com/github/copilot-sdk/blob/main/docs/setup/choosing-a-setup-path.md Install the Node.js version of the Copilot SDK using npm. ```bash npm install @github/copilot-sdk ``` -------------------------------- ### Clone Repository and Setup Git Hooks Source: https://github.com/github/copilot-sdk/blob/main/java/README.md Clone the repository and configure Git hooks for code formatting. Requires Git installed. ```bash git clone https://github.com/github/copilot-sdk.git cd copilot-sdk/java git config core.hooksPath .githooks ``` -------------------------------- ### Quick Start: Initialize Client and Session Source: https://github.com/github/copilot-sdk/blob/main/rust/README.md Demonstrates how to start the Copilot CLI client, create a new session with a permission handler, send a message, and disconnect. Requires Rust 1.94.0 or later. ```rust use std::sync::Arc; use github_copilot_sdk::{Client, ClientOptions, SessionConfig}; use github_copilot_sdk::handler::ApproveAllHandler; # async fn example() -> Result<(), github_copilot_sdk::Error> { let client = Client::start(ClientOptions::default()).await?; let session = client.create_session( SessionConfig::default().with_permission_handler(Arc::new(ApproveAllHandler)), ).await?; let _message_id = session.send("Hello!").await?; session.disconnect().await?; client.stop().await.ok(); # Ok(()) # } ``` -------------------------------- ### Configure Local MCP Server in Go Source: https://github.com/github/copilot-sdk/blob/main/docs/features/mcp.md Configure a local MCP server (stdio) for a Copilot client session in Go. Specify the command, arguments, and allowed tools. The example demonstrates initializing the client, starting it, creating a session, and deferring cleanup. ```go package main import ( "context" "log" copilot "github.com/github/copilot-sdk/go" ) func main() { ctx := context.Background() client := copilot.NewClient(nil) if err := client.Start(ctx); err != nil { log.Fatal(err) } defer client.Stop() session, err := client.CreateSession(ctx, &copilot.SessionConfig{ Model: "gpt-5", MCPServers: map[string]copilot.MCPServerConfig{ "my-local-server": copilot.MCPStdioServerConfig{ Command: "node", Args: []string{"./mcp-server.js"}, Tools: []string{"*"}, }, }, }) if err != nil { log.Fatal(err) } defer session.Disconnect() // Use the session... } ``` -------------------------------- ### Install Python SDK Source: https://github.com/github/copilot-sdk/blob/main/docs/setup/choosing-a-setup-path.md Install the Python version of the Copilot SDK using pip. ```bash pip install github-copilot-sdk ``` -------------------------------- ### StartAsync Source: https://github.com/github/copilot-sdk/blob/main/dotnet/README.md Starts the CLI server and establishes a connection. This is the initial step to begin interacting with the Copilot service. ```APIDOC ## StartAsync ### Description Starts the CLI server and establishes a connection. ### Method `StartAsync()` ### Returns `Task` ``` -------------------------------- ### Install Copilot Python SDK Source: https://github.com/github/copilot-sdk/blob/main/python/README.md Install the SDK using pip. Use the extra argument for OpenTelemetry support. ```bash pip install github-copilot-sdk ``` ```bash pip install "github-copilot-sdk[telemetry]" ``` -------------------------------- ### Run JBang Example Source: https://github.com/github/copilot-sdk/blob/main/java/README.md Execute the JBang example directly from the repository to test the SDK. ```bash jbang https://github.com/github/copilot-sdk/blob/main/java/jbang-example.java ``` -------------------------------- ### Install Python Packages Source: https://github.com/github/copilot-sdk/blob/main/docs/setup/azure-managed-identity.md Install the GitHub Copilot SDK and Azure Identity packages for Python. ```bash pip install github-copilot-sdk azure-identity ``` -------------------------------- ### Quick Start: Copilot Client Session Source: https://github.com/github/copilot-sdk/blob/main/nodejs/README.md Demonstrates creating, starting, and managing a Copilot client session with typed event handlers. Ensure to disconnect the session and stop the client when finished. ```typescript import { CopilotClient, approveAll } from "@github/copilot-sdk"; // Create and start client const client = new CopilotClient(); await client.start(); // Create a session (onPermissionRequest is optional; approveAll allows every tool) const session = await client.createSession({ model: "gpt-5", onPermissionRequest: approveAll, }); // Wait for the response using typed event handlers const done = new Promise((resolve) => { session.on("assistant.message", (event) => { console.log(event.data.content); }); session.on("session.idle", () => { resolve(); }); }); // Send a message and wait for completion await session.send({ prompt: "What is 2+2?" }); await done; // Clean up await session.disconnect(); await client.stop(); ``` -------------------------------- ### Install Go SDK Dependencies Source: https://github.com/github/copilot-sdk/blob/main/CONTRIBUTING.md Download Go module dependencies for the Go SDK. ```bash cd go && go mod download ``` -------------------------------- ### Create and Use Copilot Client (Java) Source: https://github.com/github/copilot-sdk/blob/main/docs/setup/github-oauth.md Provides an example of creating a Copilot client for a user and managing a session to send messages. ```java import com.github.copilot.CopilotClient; import com.github.copilot.rpc.*; CopilotClient createClientForUser(String userToken) throws Exception { var client = new CopilotClient(new CopilotClientOptions() .setGitHubToken(userToken) .setUseLoggedInUser(false) ); client.start().get(); return client; } // Usage — use try-with-resources to ensure cleanup var userId = "user1"; try (var client = createClientForUser("gho_user_access_token")) { var session = client.createSession(new SessionConfig() .setSessionId(String.format("user-%s-session", userId)) .setModel("gpt-4.1") .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) ).get(); var response = session.sendAndWait(new MessageOptions() .setPrompt("Hello!")).get(); } ``` -------------------------------- ### onSessionStart Source: https://github.com/github/copilot-sdk/blob/main/nodejs/docs/agent-author.md Fires when a session starts, either from a fresh startup or a resume. Allows injecting initial context. ```APIDOC ## onSessionStart ### Description Fires when a session starts, either from a fresh startup or a resume. Allows injecting initial context. ### Input `{ source: "startup" | "resume" | "new", initialPrompt?: string, timestamp, workingDirectory }` ### Output (all fields optional) - **additionalContext** (`string`) - Injected as initial context ``` -------------------------------- ### Add .NET Packages Source: https://github.com/github/copilot-sdk/blob/main/docs/setup/azure-managed-identity.md Install the GitHub Copilot SDK and Azure Core packages for .NET. ```bash dotnet add package GitHub.Copilot.SDK dotnet add package Azure.Core ``` -------------------------------- ### Install .NET SDK Dependencies Source: https://github.com/github/copilot-sdk/blob/main/CONTRIBUTING.md Restore .NET dependencies for the .NET SDK. ```bash cd dotnet && dotnet restore ``` -------------------------------- ### Go: Initialize Copilot Client and Create Session Source: https://github.com/github/copilot-sdk/blob/main/docs/setup/backend-services.md This Go snippet demonstrates how to set up the Copilot client, start it, and create a session. It includes necessary context management and error handling. ```go package main import ( "context" "fmt" "time" copilot "github.com/github/copilot-sdk/go" ) func main() { ctx := context.Background() userID := "user1" message := "Hello" client := copilot.NewClient(&copilot.ClientOptions{ Connection: copilot.URIConnection{URL: "localhost:4321"}, }) client.Start(ctx) defer client.Stop() session, _ := client.CreateSession(ctx, &copilot.SessionConfig{ SessionID: fmt.Sprintf("user-%s-%d", userID, time.Now().Unix()), Model: "gpt-4.1", }) response, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: message}) _ = response } ``` ```go client := copilot.NewClient(&copilot.ClientOptions{ Connection: copilot.URIConnection{URL: "localhost:4321"}, }) client.Start(ctx) defer client.Stop() session, _ := client.CreateSession(ctx, &copilot.SessionConfig{ SessionID: fmt.Sprintf("user-%s-%d", userID, time.Now().Unix()), Model: "gpt-4.1", }) response, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: message}) ``` -------------------------------- ### Quick Start Go Program Source: https://github.com/github/copilot-sdk/blob/main/go/README.md A basic Go program demonstrating how to initialize the Copilot client, create a session, handle events, send a message, and wait for completion. The OnPermissionRequest handler is optional; ApproveAll automatically approves tool usage. ```go package main import ( "context" "fmt" "log" copilot "github.com/github/copilot-sdk/go" ) func main() { // Create client client := copilot.NewClient(&copilot.ClientOptions{ LogLevel: "error", }) // Start the client if err := client.Start(context.Background()); err != nil { log.Fatal(err) } defer client.Stop() // Create a session (OnPermissionRequest is optional; ApproveAll allows every tool) session, err := client.CreateSession(context.Background(), &copilot.SessionConfig{ Model: "gpt-5", OnPermissionRequest: copilot.PermissionHandler.ApproveAll, }) if err != nil { log.Fatal(err) } defer session.Disconnect() // Set up event handler done := make(chan bool) session.On(func(event copilot.SessionEvent) { switch d := event.Data.(type) { case *copilot.AssistantMessageData: fmt.Println(d.Content) case *copilot.SessionIdleData: close(done) } }) // Send a message _, err = session.Send(context.Background(), copilot.MessageOptions{ Prompt: "What is 2+2?", }) if err != nil { log.Fatal(err) } // Wait for completion <-done } ``` -------------------------------- ### Initialize Go Project for Copilot SDK Source: https://github.com/github/copilot-sdk/blob/main/docs/getting-started.md Create a new directory and initialize a Go module. This is the initial setup for Go projects using the Copilot SDK. ```bash mkdir copilot-demo && cd copilot-demo go mod init copilot-demo ``` -------------------------------- ### Check and Install Missing Shared Libraries on Linux Source: https://github.com/github/copilot-sdk/blob/main/docs/troubleshooting/mcp-debugging.md Shows how to use `ldd` to check for missing shared libraries required by an MCP server executable on Linux and provides example commands for installing them using `apt` or `yum`. ```bash # Check dependencies ldd /path/to/mcp-server # Install missing libraries apt install libfoo # Debian/Ubuntu yum install libfoo # RHEL/CentOS ``` -------------------------------- ### Configuring Session Filesystem Provider and Client Source: https://github.com/github/copilot-sdk/blob/main/rust/README.md Shows how to configure client options with session filesystem settings and create a client. It also demonstrates creating a session with a custom permission handler and session filesystem provider. ```rust use std::sync::Arc; use github_copilot_sdk::session_fs::{SessionFsConfig, SessionFsConventions}; let mut options = ClientOptions::default(); options.session_fs = Some(SessionFsConfig::new( "/workspace", "/workspace/.copilot", SessionFsConventions::Posix, )); let client = Client::start(options).await?; let session = client .create_session( SessionConfig::default() .with_permission_handler(Arc::new(ApproveAllHandler)) .with_session_fs_provider(Arc::new(MyProvider::new())), ) .await?; ``` -------------------------------- ### Send First Message in Node.js/TypeScript Source: https://github.com/github/copilot-sdk/blob/main/docs/getting-started.md Use this snippet to send a simple prompt to the Copilot API and get a response. Ensure you have the '@github/copilot-sdk' package installed. ```typescript import { CopilotClient } from "@github/copilot-sdk"; const client = new CopilotClient(); const session = await client.createSession({ model: "gpt-4.1" }); const response = await session.sendAndWait({ prompt: "What is 2 + 2?" }); console.log(response?.data.content); await client.stop(); process.exit(0); ``` ```bash npx tsx index.ts ``` -------------------------------- ### Subscribe to Sub-agent Events in Python Source: https://github.com/github/copilot-sdk/blob/main/docs/features/custom-agents.md Utilize session.on() with a handler function to process sub-agent events. This example demonstrates logging for started, completed, failed, and selected sub-agents. ```python def handle_event(event): if event.type == "subagent.started": print(f"▶ Sub-agent started: {event.data.agent_display_name}") print(f" Description: {event.data.agent_description}") elif event.type == "subagent.completed": print(f"✅ Sub-agent completed: {event.data.agent_display_name}") elif event.type == "subagent.failed": print(f"❌ Sub-agent failed: {event.data.agent_display_name}") print(f" Error: {event.data.error}") elif event.type == "subagent.selected": tools = event.data.tools or "all" print(f"🎯 Agent selected: {event.data.agent_display_name} (tools: {tools})") unsubscribe = session.on(handle_event) response = await session.send_and_wait("Research how authentication works in this codebase") ``` -------------------------------- ### Java: Initialize CopilotClient with Default Credentials Source: https://github.com/github/copilot-sdk/blob/main/docs/auth/authenticate.md Initialize the CopilotClient in Java. This client automatically uses the logged-in user's credentials and requires starting the client and getting the result. ```java import com.github.copilot.CopilotClient; // Default: uses logged-in user credentials var client = new CopilotClient(); client.start().get(); ``` -------------------------------- ### Desktop Notifications for Session Events (Python) Source: https://github.com/github/copilot-sdk/blob/main/docs/features/hooks.md Utilize the `subprocess` module to execute `notify-send` for desktop notifications on session end or errors in Python. This example assumes a Linux environment with `notify-send` installed. ```python import subprocess from copilot import PermissionDecisionApproveOnce async def on_session_end(input_data, invocation): sid = invocation["session_id"][:8] reason = input_data["reason"] subprocess.Popen([ "notify-send", "Copilot Session Complete", f"Session {sid} finished ({reason}).", ]) return None async def on_error_occurred(input_data, invocation): subprocess.Popen([ "notify-send", "Copilot Error", input_data["error"][:200], ]) return None session = await client.create_session( on_permission_request=lambda req, inv: PermissionDecisionApproveOnce(), hooks={ "on_session_end": on_session_end, "on_error_occurred": on_error_occurred, }, ) ``` -------------------------------- ### Subscribe to Sub-agent Events in Go Source: https://github.com/github/copilot-sdk/blob/main/docs/features/custom-agents.md Implement event handling for sub-agents using session.On() in Go. This snippet shows how to process started, completed, failed, and selected events, including necessary client setup. ```go package main import ( "context" "fmt" copilot "github.com/github/copilot-sdk/go" "github.com/github/copilot-sdk/go/rpc" ) func main() { ctx := context.Background() client := copilot.NewClient(nil) client.Start(ctx) session, _ := client.CreateSession(ctx, &copilot.SessionConfig{ Model: "gpt-4.1", OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (rpc.PermissionDecision, error) { return &rpc.PermissionDecisionApproveOnce{}, nil }, }) session.On(func(event copilot.SessionEvent) { switch d := event.Data.(type) { case *copilot.SubagentStartedData: fmt.Printf("▶ Sub-agent started: %s\n", d.AgentDisplayName) fmt.Printf(" Description: %s\n", d.AgentDescription) fmt.Printf(" Tool call ID: %s\n", d.ToolCallId) case *copilot.SubagentCompletedData: fmt.Printf("✅ Sub-agent completed: %s\n", d.AgentDisplayName) case *copilot.SubagentFailedData: fmt.Printf("❌ Sub-agent failed: %s — %v\n", d.AgentDisplayName, d.Error) case *copilot.SubagentSelectedData: fmt.Printf("🎯 Agent selected: %s\n", d.AgentDisplayName) } }) _, err := session.SendAndWait(ctx, copilot.MessageOptions{ Prompt: "Research how authentication works in this codebase", }) _ = err } ``` ```go session.On(func(event copilot.SessionEvent) { switch d := event.Data.(type) { case *copilot.SubagentStartedData: fmt.Printf("▶ Sub-agent started: %s\n", d.AgentDisplayName) fmt.Printf(" Description: %s\n", d.AgentDescription) fmt.Printf(" Tool call ID: %s\n", d.ToolCallId) case *copilot.SubagentCompletedData: fmt.Printf("✅ Sub-agent completed: %s\n", d.AgentDisplayName) case *copilot.SubagentFailedData: fmt.Printf("❌ Sub-agent failed: %s — %v\n", d.AgentDisplayName, d.Error) case *copilot.SubagentSelectedData: fmt.Printf("🎯 Agent selected: %s\n", d.AgentDisplayName) } }) _, err := session.SendAndWait(ctx, copilot.MessageOptions{ Prompt: "Research how authentication works in this codebase", }) ``` -------------------------------- ### Start Fleet Mode in Node.js/TypeScript Source: https://github.com/github/copilot-sdk/blob/main/docs/features/fleet-mode.md Initiates fleet mode within a session using the `session.rpc.fleet.start` method. The prompt guides the parallel execution of sub-agents. Ensure the SDK and Copilot CLI runtime are pinned if your application depends on this experimental binding. ```typescript const result = await session.rpc.fleet.start({ prompt: "Refactor each SDK package independently, then summarize the changes.", }); if (result.started) { console.log("Fleet mode started"); } ``` -------------------------------- ### Create and Use Copilot Client (Go) Source: https://github.com/github/copilot-sdk/blob/main/docs/setup/github-oauth.md Shows how to initialize a Copilot client using a user token and manage a session for sending messages. ```go package main import ( "context" "fmt" copilot "github.com/github/copilot-sdk/go" ) func createClientForUser(userToken string) *copilot.Client { return copilot.NewClient(&copilot.ClientOptions{ GitHubToken: userToken, UseLoggedInUser: copilot.Bool(false), }) } func main() { ctx := context.Background() userID := "user1" client := createClientForUser("gho_user_access_token") client.Start(ctx) defer client.Stop() session, _ := client.CreateSession(ctx, &copilot.SessionConfig{ SessionID: fmt.Sprintf("user-%s-session", userID), Model: "gpt-4.1", }) response, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: "Hello!"}) _ = response } ``` ```go func createClientForUser(userToken string) *copilot.Client { return copilot.NewClient(&copilot.ClientOptions{ GitHubToken: userToken, UseLoggedInUser: copilot.Bool(false), }) } // Usage client := createClientForUser("gho_user_access_token") client.Start(ctx) defer client.Stop() session, _ := client.CreateSession(ctx, &copilot.SessionConfig{ SessionID: fmt.Sprintf("user-%s-session", userID), Model: "gpt-4.1", }) response, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: "Hello!"}) ``` -------------------------------- ### Implement SessionHooks for Lifecycle Events Source: https://github.com/github/copilot-sdk/blob/main/rust/README.md Implement the `SessionHooks` trait to intercept CLI behavior at lifecycle points such as tool use, prompt submission, and session start/end. This example shows how to deny a specific tool use and add context to session start. ```rust use std::sync::Arc; use github_copilot_sdk::hooks::*; use async_trait::async_trait; struct MyHooks; #[async_trait] impl SessionHooks for MyHooks { async fn on_hook(&self, event: HookEvent) -> HookOutput { match event { HookEvent::PreToolUse { input, ctx } => { if input.tool_name == "dangerous_tool" { HookOutput::PreToolUse(PreToolUseOutput { permission_decision: Some("deny".to_string()), permission_decision_reason: Some("blocked by policy".to_string()), ..Default::default() }) } else { HookOutput::None // pass through } } HookEvent::SessionStart { input, .. } => { HookOutput::SessionStart(SessionStartOutput { additional_context: Some("Extra system context".to_string()), ..Default::default() }) } _ => HookOutput::None, } } } let session = client .create_session( config .with_permission_handler(handler) .with_hooks(Arc::new(MyHooks)), ) .await?; ``` -------------------------------- ### Create Cloud Session in .NET Source: https://github.com/github/copilot-sdk/blob/main/docs/features/cloud-sessions.md This .NET example shows how to initiate a cloud session with repository details. The CopilotClient is managed using `await using` for proper disposal. ```csharp await using var client = new CopilotClient(); var session = await client.CreateSessionAsync(new SessionConfig { Cloud = new CloudSessionOptions { Repository = new CloudSessionRepository { Owner = "github", Name = "copilot-sdk", Branch = "main", }, }, OnPermissionRequest = (req, inv) => Task.FromResult(PermissionDecision.ApproveOnce()), }); ``` -------------------------------- ### Track Session Metrics in Python Source: https://github.com/github/copilot-sdk/blob/main/docs/features/hooks.md Implement session hooks in Python to monitor session duration, tool invocations, and prompts. This example initializes metrics on session start, increments counters for user prompts and tool calls, and logs session details when the session ends. ```python from copilot import PermissionDecisionApproveOnce session_metrics = {} async def on_session_start(input_data, invocation): session_metrics[invocation["session_id"]] = { "start": input_data["timestamp"], "tool_calls": 0, "prompts": 0, } return None async def on_user_prompt_submitted(input_data, invocation): session_metrics[invocation["session_id"]]["prompts"] += 1 return None async def on_pre_tool_use(input_data, invocation): session_metrics[invocation["session_id"]]["tool_calls"] += 1 return {"permissionDecision": "allow"} async def on_session_end(input_data, invocation): m = session_metrics.pop(invocation["session_id"]) duration = (input_data["timestamp"] - m["start"]).total_seconds() sid = invocation["session_id"][:8] print( f"Session {sid}: {duration:.1f}s, {m['prompts']} prompts, " f"{m['tool_calls']} tool calls, ended: {input_data['reason']}" ) return None session = await client.create_session( on_permission_request=lambda req, inv: PermissionDecisionApproveOnce(), hooks={ "on_session_start": on_session_start, "on_user_prompt_submitted": on_user_prompt_submitted, "on_pre_tool_use": on_pre_tool_use, "on_session_end": on_session_end, }, ) ``` -------------------------------- ### Track Session Metrics in Node.js/TypeScript Source: https://github.com/github/copilot-sdk/blob/main/docs/features/hooks.md Use session hooks to track metrics like session duration, tool invocations, and prompts. This example demonstrates initializing metrics on session start, incrementing counters for prompts and tool calls, and logging session details upon termination. ```typescript const metrics = new Map< string, { start: Date; toolCalls: number; prompts: number } >(); const session = await client.createSession({ hooks: { onSessionStart: async (input, invocation) => { metrics.set(invocation.sessionId, { start: input.timestamp, toolCalls: 0, prompts: 0, }); return null; }, onUserPromptSubmitted: async (_input, invocation) => { metrics.get(invocation.sessionId)!.prompts++; return null; }, onPreToolUse: async (_input, invocation) => { metrics.get(invocation.sessionId)!.toolCalls++; return { permissionDecision: "allow" }; }, onSessionEnd: async (input, invocation) => { const m = metrics.get(invocation.sessionId)! const durationSec = (input.timestamp.getTime() - m.start.getTime()) / 1000; console.log( `Session ${invocation.sessionId.slice(0, 8)}: ` + `${durationSec.toFixed(1)}s, ${m.prompts} prompts, ` + `${m.toolCalls} tool calls, ended: ${input.reason}`, ); metrics.delete(invocation.sessionId); return null; }, }, onPermissionRequest: async () => ({ kind: "approve-once" }), }); ``` -------------------------------- ### Initialize Copilot Client and Create Session (Java) Source: https://github.com/github/copilot-sdk/blob/main/docs/getting-started.md Demonstrates initializing the Copilot client, creating a session with streaming enabled, and setting up event handlers for assistant messages and session idle events. This is useful for real-time interaction with the Copilot model. ```java import com.github.copilot.CopilotClient; import com.github.copilot.rpc.*; public class HelloCopilot { public static void main(String[] args) throws Exception { try (var client = new CopilotClient()) { client.start().get(); var session = client.createSession( new SessionConfig() .setModel("gpt-4.1") .setStreaming(true) .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) ).get(); // Listen for response chunks session.on(AssistantMessageDeltaEvent.class, delta -> { System.out.print(delta.getData().deltaContent()); }); session.on(SessionIdleEvent.class, idle -> { System.out.println(); // New line when done }); session.sendAndWait( new MessageOptions().setPrompt("Tell me a short joke") ).get(); client.stop().get(); } } } ``` -------------------------------- ### Install Bundled CLI Manually Source: https://github.com/github/copilot-sdk/blob/main/rust/README.md Use `install_bundled_cli` to get the path to the bundled CLI binary when a `Client` is not being used or when `ClientOptions::program` is always set to `CliProgram::Path`. This function lazily extracts the binary on its first call and is idempotent. It returns `None` if `bundled-cli` is disabled or the target is unsupported, and does not fall back to the build-time extracted dev-cache path. ```rust use github_copilot_sdk::{HAS_BUNDLED_CLI, install_bundled_cli}; if HAS_BUNDLED_CLI { if let Some(path) = install_bundled_cli() { // lazily extracts on first call; idempotent thereafter println!("bundled CLI at {}", path.display()); } } ``` -------------------------------- ### Run Manual Tool Resume Sample Source: https://github.com/github/copilot-sdk/blob/main/go/README.md Execute the manual permission/tool-result resume sample from the 'go/samples' directory. ```bash go run ./manual_tool_resume ``` -------------------------------- ### Create and Use Filesystem MCP Server Session Source: https://github.com/github/copilot-sdk/blob/main/docs/features/mcp.md This snippet demonstrates how to create a Copilot SDK session with the local filesystem MCP server. It shows how to initialize the client, configure the server with a command and arguments, and send a prompt to list files. ```typescript import { CopilotClient } from "@github/copilot-sdk"; async function main() { const client = new CopilotClient(); // Create session with filesystem MCP server const session = await client.createSession({ mcpServers: { filesystem: { type: "local", command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"], tools: ["*"], }, }, }); console.log("Session created:", session.sessionId); // The model can now use filesystem tools const result = await session.sendAndWait({ prompt: "List the files in the allowed directory", }); console.log("Response:", result?.data?.content); await session.disconnect(); await client.stop(); } main(); ``` -------------------------------- ### Install Node.js SDK Dependencies Source: https://github.com/github/copilot-sdk/blob/main/CONTRIBUTING.md Install Node.js dependencies for the Node.js SDK. ```bash cd nodejs && npm ci ``` -------------------------------- ### Quick Start with CopilotClient (Async Context Manager) Source: https://github.com/github/copilot-sdk/blob/main/python/README.md Demonstrates using CopilotClient within an async context manager for automatic resource management. Handles session events and sends a message. ```python import asyncio from copilot import CopilotClient from copilot.session_events import AssistantMessageData, SessionIdleData from copilot.session import PermissionHandler async def main(): # Client automatically starts on enter and cleans up on exit async with CopilotClient() as client: # Create a session with automatic cleanup async with await client.create_session( on_permission_request=PermissionHandler.approve_all, model="gpt-5", ) as session: # Wait for response using session.idle event done = asyncio.Event() def on_event(event): match event.data: case AssistantMessageData() as data: print(data.content) case SessionIdleData(): done.set() session.on(on_event) # Send a message and wait for completion await session.send("What is 2+2?") await done.wait() asyncio.run(main()) ``` -------------------------------- ### Create and Use Copilot Client (Python) Source: https://github.com/github/copilot-sdk/blob/main/docs/setup/github-oauth.md Demonstrates how to create a Copilot client for a user and initiate a session for sending messages. ```python client = create_client_for_user("gho_user_access_token") await client.start() session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model="gpt-4.1", session_id=f"user-{user_id}-session") response = await session.send_and_wait("Hello!") ``` -------------------------------- ### Run Manual Tool Resume Sample Source: https://github.com/github/copilot-sdk/blob/main/dotnet/README.md Execute the manual permission/tool-result resume sample from the repository root. ```bash dotnet run --file dotnet/samples/ManualToolResume.cs ``` -------------------------------- ### Go: Immediate Steering Message Source: https://github.com/github/copilot-sdk/blob/main/docs/features/steering-and-queueing.md Demonstrates sending an immediate steering message in Go. This example initializes the Copilot client, creates a session, sends an initial prompt, and then uses 'immediate' mode to steer the agent's ongoing response. ```go package main import ( "context" "log" copilot "github.com/github/copilot-sdk/go" "github.com/github/copilot-sdk/go/rpc" ) func main() { ctx := context.Background() client := copilot.NewClient(nil) if err := client.Start(ctx); err != nil { log.Fatal(err) } defer client.Stop() session, err := client.CreateSession(ctx, &copilot.SessionConfig{ Model: "gpt-4.1", OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (rpc.PermissionDecision, error) { return &rpc.PermissionDecisionApproveOnce{}, nil }, }) if err != nil { log.Fatal(err) } // Start a long-running task _, err = session.Send(ctx, copilot.MessageOptions{ Prompt: "Refactor the authentication module to use sessions", }) if err != nil { log.Fatal(err) } // While the agent is working, steer it _, err = session.Send(ctx, copilot.MessageOptions{ Prompt: "Actually, use JWT tokens instead of sessions", Mode: "immediate", }) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Install TypeScript Packages Source: https://github.com/github/copilot-sdk/blob/main/docs/setup/azure-managed-identity.md Install the GitHub Copilot SDK and Azure Identity packages for TypeScript. ```bash npm install @github/copilot-sdk @azure/identity ``` -------------------------------- ### Configure .NET Exe and DLL Tools Source: https://github.com/github/copilot-sdk/blob/main/docs/troubleshooting/mcp-debugging.md Provides correct configuration examples for running .NET executable and DLL tools via MCP, including setting the command, arguments, and working directory. ```csharp // Correct configuration for .NET exe ["my-dotnet-server"] = new McpStdioServerConfig { Command = @"C:\Tools\MyServer\MyServer.exe", // Full path with .exe Args = new List(), WorkingDirectory = @"C:\Tools\MyServer", // Set working directory Tools = new List { "*" }, } // For dotnet tool (DLL) ["my-dotnet-tool"] = new McpStdioServerConfig { Command = "dotnet", Args = new List { @"C:\Tools\MyTool\MyTool.dll" }, WorkingDirectory = @"C:\Tools\MyTool", Tools = new List { "*" }, } ``` -------------------------------- ### Run Interactive Chat Sample Source: https://github.com/github/copilot-sdk/blob/main/go/README.md Navigate to the samples directory and run the interactive chat sample using 'go run chat.go'. ```bash cd go/samples go run chat.go ``` -------------------------------- ### Install Python SDK Dependencies Source: https://github.com/github/copilot-sdk/blob/main/CONTRIBUTING.md Install Python dependencies using uv for the Python SDK. ```bash cd python && uv pip install -e ".[dev]" ``` -------------------------------- ### Run Interactive Chat Sample Source: https://github.com/github/copilot-sdk/blob/main/python/README.md Navigate to the samples directory and run the chat sample script. ```bash cd python/samples python chat.py ``` -------------------------------- ### Send First Message in Go Source: https://github.com/github/copilot-sdk/blob/main/docs/getting-started.md A Go example demonstrating how to use the Copilot SDK to send a prompt. It includes context management and error handling for client operations. ```go package main import ( "context" "fmt" "log" "os" copilot "github.com/github/copilot-sdk/go" ) func main() { ctx := context.Background() client := copilot.NewClient(nil) if err := client.Start(ctx); err != nil { log.Fatal(err) } defer client.Stop() session, err := client.CreateSession(ctx, &copilot.SessionConfig{Model: "gpt-4.1"}) if err != nil { log.Fatal(err) } response, err := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: "What is 2 + 2?"}) if err != nil { log.Fatal(err) } if d, ok := response.Data.(*copilot.AssistantMessageData); ok { fmt.Println(d.Content) } os.Exit(0) } ``` ```bash go run main.go ``` -------------------------------- ### Verify Copilot CLI Installation Source: https://github.com/github/copilot-sdk/blob/main/docs/troubleshooting/debugging.md Run this command to check if the Copilot CLI is installed and accessible in your PATH. ```bash copilot --version ``` -------------------------------- ### Create and Use Copilot Client (.NET) Source: https://github.com/github/copilot-sdk/blob/main/docs/setup/github-oauth.md Illustrates setting up a Copilot client with a user token and managing a session for message exchange. ```csharp using GitHub.Copilot; CopilotClient CreateClientForUser(string userToken) => new CopilotClient(new CopilotClientOptions { GitHubToken = userToken, UseLoggedInUser = false, }); var userId = "user1"; await using var client = CreateClientForUser("gho_user_access_token"); await using var session = await client.CreateSessionAsync(new SessionConfig { SessionId = $"user-{userId}-session", Model = "gpt-4.1", }); var response = await session.SendAndWaitAsync( new MessageOptions { Prompt = "Hello!" }); ``` ```csharp CopilotClient CreateClientForUser(string userToken) => new CopilotClient(new CopilotClientOptions { GitHubToken = userToken, UseLoggedInUser = false, }); // Usage await using var client = CreateClientForUser("gho_user_access_token"); await using var session = await client.CreateSessionAsync(new SessionConfig { SessionId = $"user-{userId}-session", Model = "gpt-4.1", }); var response = await session.SendAndWaitAsync( new MessageOptions { Prompt = "Hello!" }); ``` -------------------------------- ### Initialize Copilot Client (.NET) Source: https://github.com/github/copilot-sdk/blob/main/docs/setup/multi-tenancy.md Sets up the Copilot client using `CopilotClientMode.Empty` for multi-tenancy. The `BaseDirectory` should be tenant-specific. Configures a 900-second session idle timeout. ```csharp var client = new CopilotClient(new CopilotClientOptions { Mode = CopilotClientMode.Empty, BaseDirectory = $"/var/lib/my-app/copilot/{runtimeInstanceId}", SessionIdleTimeoutSeconds = 900, Connection = RuntimeConnection.ForUri(runtimeUrl), }); await using var session = await client.CreateSessionAsync(new SessionConfig { SessionId = $"user-{user.Id}-{requestId}", Model = "gpt-4.1", AvailableTools = ["custom:lookupOrder", "custom:createTicket"], GitHubToken = user.GitHubToken, }); ``` -------------------------------- ### Install Test Harness Dependencies Source: https://github.com/github/copilot-sdk/blob/main/CONTRIBUTING.md Before running tests in any language, install the shared Node.js test harness dependencies. ```bash cd test/harness && npm ci ```