# How to Add the GitHub Copilot SDK to Your Go Project: Complete Integration Guide

> Integrate the GitHub Copilot SDK into your Go project with our guide. Learn to install, initialize, start the runtime, and create sessions for AI code generation.

- Repository: [GitHub/copilot-sdk](https://github.com/github/copilot-sdk)
- Tags: how-to-guide
- Published: 2026-07-18

---

**Install the GitHub Copilot SDK for Go using `go get github.com/github/copilot-sdk/go`, then initialize a `Client` with `copilot.NewClient()`, start the runtime with `client.Start()`, and create sessions using `client.CreateSession()` to exchange messages with the Copilot AI via JSON-RPC.**

The GitHub Copilot SDK for Go is a lightweight library that enables your applications to communicate with the Copilot CLI or a remote runtime. According to the github/copilot-sdk repository, the SDK abstracts process lifecycle management, session negotiation, and permission handling through type-safe APIs defined in [`go/client.go`](https://github.com/github/copilot-sdk/blob/main/go/client.go) and [`go/session.go`](https://github.com/github/copilot-sdk/blob/main/go/session.go). This guide covers installation, client initialization, session management, and advanced configuration for production deployments.

## Installing the GitHub Copilot SDK

To add the SDK to your Go project, fetch the module from GitHub:

```bash
go get github.com/github/copilot-sdk/go

```

This command updates your `go.mod` file and makes the `copilot` package available for import. The SDK requires Go 1.21 or later to support the context and generics features used in the JSON-RPC implementation.

## Initializing the Client and Runtime

The **Client** struct defined in [`go/client.go`](https://github.com/github/copilot-sdk/blob/main/go/client.go) serves as the primary entry point for all SDK operations, handling transport negotiation and process management.

### Creating the Client

Call `copilot.NewClient(opts)` to instantiate a client. The constructor, located at lines 13-63 in [`go/client.go`](https://github.com/github/copilot-sdk/blob/main/go/client.go), validates transport options and resolves the connection method (`stdio`, `inprocess`, or custom TCP/URI):

```go
import copilot "github.com/github/copilot-sdk/go"

// Create client with default options (uses bundled CLI over stdio)
client := copilot.NewClient(nil)

// Or customize with explicit options
client := copilot.NewClient(&copilot.ClientOptions{
    Connection: copilot.StdioConnection{},
})

```

The `Client` stores runtime connection options, environment variables, and authentication settings. When `opts` is `nil`, the SDK uses sensible defaults targeting the bundled CLI binary.

### Starting the Runtime

Invoke `client.Start(ctx)` to spawn the Copilot CLI process and open the JSON-RPC channel. This method, implemented at lines 24-56 in [`go/client.go`](https://github.com/github/copilot-sdk/blob/main/go/client.go), handles process launch, connection establishment, and protocol version negotiation:

```go
if err := client.Start(context.Background()); err != nil {
    log.Fatalf("failed to start Copilot runtime: %v", err)
}
defer client.Stop()

```

The SDK maintains the process handle and manages graceful shutdown when `client.Stop()` is called or the program exits.

## Creating Sessions and Exchanging Messages

Sessions represent isolated conversations with the AI model, supporting tool registration and permission callbacks.

### Session Creation

Use `client.CreateSession(ctx, config)` (lines 95-140 in [`go/client.go`](https://github.com/github/copilot-sdk/blob/main/go/client.go)) to initialize a new conversation. The SDK builds a `session.create` RPC request, registers custom tools, and stores the resulting `Session` in the client's internal session map:

```go
sess, err := client.CreateSession(context.Background(), &copilot.SessionConfig{
    Model:               "gpt-4",
    OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
})
if err != nil {
    log.Fatalf("session creation failed: %v", err)
}
defer sess.Disconnect()

```

The `SessionConfig` struct allows you to specify the model name, tool definitions, telemetry settings, and permission handlers that govern tool execution approval.

### Sending Messages and Handling Events

The **Session** type in [`go/session.go`](https://github.com/github/copilot-sdk/blob/main/go/session.go) manages event routing and streaming responses. Send prompts using `session.Send()` and subscribe to events with `sess.On()` to receive assistant messages, tool calls, and status updates:

```go
done := make(chan bool)

sess.On(func(ev copilot.SessionEvent) {
    switch d := ev.Data.(type) {
    case *copilot.AssistantMessageData:
        fmt.Println("Assistant:", d.Content)
    case *copilot.ToolCallData:
        fmt.Printf("Tool called: %s\n", d.Name)
    case *copilot.SessionIdleData:
        close(done)
    }
})

_, err = sess.Send(context.Background(), copilot.MessageOptions{
    Prompt: "Refactor this function to use channels.",
})
if err != nil {
    log.Fatalf("send failed: %v", err)
}

<-done

```

The event-driven architecture allows your application to stream tokens as they are generated or handle multi-turn tool invocations asynchronously.

## Registering Custom Tools

Expose Go functions to the LLM using `copilot.DefineTool()`, which automatically generates JSON Schema from your struct definitions:

```go
type WeatherParams struct {
    City string `json:"city" jsonschema:"The name of the city"`
}

var getWeather = copilot.DefineTool(
    "get_weather",
    "Fetch the current weather for a city",
    func(p WeatherParams, inv copilot.ToolInvocation) (any, error) {
        // Implementation calling your weather API
        return fmt.Sprintf("%s is sunny, 25°C.", p.City), nil
    },
)

// Register when creating session
sess, _ := client.CreateSession(context.Background(), &copilot.SessionConfig{
    Model:               "gpt-4",
    Tools:               []copilot.Tool{getWeather},
    OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
})

```

The SDK validates arguments against the generated schema before invoking your handler, ensuring type safety across the JSON-RPC boundary.

## Advanced Configuration Options

### In-Process Transport

For scenarios requiring reduced overhead, compile with the `copilot_inprocess` build tag and configure `copilot.InProcessConnection{}`. This loads the native runtime via FFI instead of spawning a child process, as supported by the connection logic in [`go/client.go`](https://github.com/github/copilot-sdk/blob/main/go/client.go):

```bash
go build -tags copilot_inprocess

```

```go
client := copilot.NewClient(&copilot.ClientOptions{
    Connection: copilot.InProcessConnection{},
})

```

### Embedding the Copilot CLI

To distribute standalone binaries, use the **bundler** tool located at `go/cmd/bundler` to embed the Copilot CLI into your build:

```bash
go get -tool github.com/github/copilot-sdk/go/cmd/bundler
go tool bundler  # Caches CLI binary for embedding

```

At runtime, the SDK extracts and caches the binary using logic in [`go/internal/embeddedcli/embeddedcli.go`](https://github.com/github/copilot-sdk/blob/main/go/internal/embeddedcli/embeddedcli.go), transparently handling platform-specific paths and permissions.

### Telemetry Integration

Provide a `TelemetryConfig` in `ClientOptions` to enable OpenTelemetry export, allowing you to monitor RPC latency, session duration, and token throughput in your observability stack.

## Summary

- **Install** the SDK using `go get github.com/github/copilot-sdk/go` to add JSON-RPC Copilot capabilities to your project.
- **Initialize** the client with `copilot.NewClient()` and start the runtime via `client.Start()` as implemented in [`go/client.go`](https://github.com/github/copilot-sdk/blob/main/go/client.go) lines 13-63.
- **Create sessions** using `client.CreateSession()` to manage conversation state, model selection, and tool registration.
- **Exchange messages** through `session.Send()` and handle streaming events via callbacks defined in [`go/session.go`](https://github.com/github/copilot-sdk/blob/main/go/session.go).
- **Deploy flexibly** by embedding the CLI with the bundler tool or using in-process mode via the `copilot_inprocess` build tag.

## Frequently Asked Questions

### What Go version is required for the GitHub Copilot SDK?

The SDK requires **Go 1.21 or later** to support the context handling and generic types used in the JSON-RPC implementation. Ensure your `go.mod` file specifies a compatible version before running `go get`.

### Can I use the SDK without spawning a separate CLI process?

Yes. According to the source code in [`go/client.go`](https://github.com/github/copilot-sdk/blob/main/go/client.go), compile with the `-tags copilot_inprocess` flag and set `Connection: copilot.InProcessConnection{}` in your `ClientOptions`. This loads the Copilot runtime via FFI, eliminating subprocess overhead while maintaining the same `Client` and `Session` APIs.

### How does the SDK handle authentication with GitHub Copilot?

The `Client` struct manages authentication through environment variables and connection options validated during `NewClient()` initialization. The SDK passes credentials to the underlying Copilot CLI process or runtime via the transport layer defined in [`go/internal/jsonrpc2/jsonrpc2.go`](https://github.com/github/copilot-sdk/blob/main/go/internal/jsonrpc2/jsonrpc2.go), keeping tokens out of your application code.

### Where is the JSON-RPC communication implemented?

The low-level **JSON-RPC 2.0** client resides in [`go/internal/jsonrpc2/jsonrpc2.go`](https://github.com/github/copilot-sdk/blob/main/go/internal/jsonrpc2/jsonrpc2.go), handling message serialization and request/response correlation. The public APIs in [`go/client.go`](https://github.com/github/copilot-sdk/blob/main/go/client.go) and [`go/session.go`](https://github.com/github/copilot-sdk/blob/main/go/session.go) wrap this implementation, providing type-safe methods like `CreateSession()` and `Send()` while abstracting the wire protocol.