alpha

Gives a coding agent guidance for building Go apps with the Copilot SDK: client setup, sessions, tools, events and options, with code examples.
applyTo: "**.go, go.mod"
description: "This file provides guidance on building Go applications using the Microsoft Copilot SDK."
name: "Microsoft Copilot SDK Go Instructions"
The Microsoft Copilot SDK is transitioning from the GitHub Copilot SDK in phases. No immediate changes are required; package names and examples below use the currently published identifiers. See the [official transition announcement](https://github.blog/changelog/2026-10-28-github-copilot-sdk-is-becoming-microsoft-copilot-sdk/).
Always install via Go modules:
go get github.com/github/copilot-sdk/go
import "github.com/github/copilot-sdk/go"
client := copilot.NewClient(nil)
if err := client.Start(); err != nil {
log.Fatal(err)
}
defer client.Stop()
When creating a CopilotClient, use ClientOptions:
CLIPath - Path to CLI executable (default: "copilot" from PATH)CLIUrl - URL of existing CLI server (e.g., "localhost:8080"). When provided, client won't spawn a processPort - Server port (default: 0 for random)UseStdio - Use stdio transport instead of TCP (default: true)LogLevel - Log level (default: "info")AutoStart - Auto-start server (default: true, use pointer: boolPtr(true))AutoRestart - Auto-restart on crash (default: true, use pointer: boolPtr(true))Cwd - Working directory for the CLI processEnv - Environment variables for the CLI process ([]string)For explicit control:
autoStart := false
client := copilot.NewClient(&copilot.ClientOptions{AutoStart: &autoStart})
if err := client.Start(); err != nil {
log.Fatal(err)
}
// Use client...
client.Stop()
Use ForceStop() when Stop() takes too long.
Use SessionConfig for configuration:
session, err := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
Streaming: true,
Tools: []copilot.Tool{...},
SystemMessage: &copilot.SystemMessageConfig{ ... },
AvailableTools: []string{"tool1", "tool2"},
ExcludedTools: []string{"tool3"},
Provider: &copilot.ProviderConfig{ ... },
})
if err != nil {
log.Fatal(err)
}
SessionID - Custom session IDModel - Model name ("gpt-5", "claude-sonnet-4.5", etc.)Tools - Custom tools exposed to the CLI ([]Tool)SystemMessage - System message customization (*SystemMessageConfig)AvailableTools - Allowlist of tool names ([]string)ExcludedTools - Blocklist of tool names ([]string)Provider - Custom API provider configuration (BYOK) (*ProviderConfig)Streaming - Enable streaming response chunks (bool)MCPServers - MCP server configurationsCustomAgents - Custom agent configurationsConfigDir - Config directory overrideSkillDirectories - Skill directories ([]string)DisabledSkills - Disabled skills ([]string)session, err := client.ResumeSession("session-id", &copilot.ResumeSessionConfig{OnPermissionRequest: copilot.PermissionHandler.ApproveAll})
// Or with options:
session, err := client.ResumeSessionWithOptions("session-id", &copilot.ResumeSessionConfig{ ... })
session.SessionID - Get session identifier (string)session.Send(copilot.MessageOptions{Prompt: "...", Attachments: []copilot.Attachment{...}}) - Send message, returns (messageID string, error)session.SendAndWait(options, timeout) - Send and wait for idle, returns (*SessionEvent, error)session.Abort() - Abort current processing, returns errorsession.GetMessages() - Get all events/messages, returns ([]SessionEvent, error)session.Destroy() - Clean up session, returns errorALWAYS use channels or done signals to wait for session events:
done := make(chan struct{})
unsubscribe := session.On(func(evt copilot.SessionEvent) {
switch evt.Type {
case copilot.AssistantMessage:
fmt.Println(*evt.Data.Content)
case copilot.SessionIdle:
close(done)
}
})
defer unsubscribe()
session.Send(copilot.MessageOptions{Prompt: "..."})
<-done
The On() method returns a function that unsubscribes:
unsubscribe := session.On(func(evt copilot.SessionEvent) {
// handler
})
// Later...
unsubscribe()
Use type switches for event handling:
session.On(func(evt copilot.SessionEvent) {
switch evt.Type {
case copilot.UserMessage:
// Handle user message
case copilot.AssistantMessage:
if evt.Data.Content != nil {
fmt.Println(*evt.Data.Content)
}
case copilot.ToolExecutionStart:
// Tool execution started
case copilot.ToolExecutionComplete:
// Tool execution completed
case copilot.SessionStart:
// Session started
case copilot.SessionIdle:
// Session is idle (processing complete)
case copilot.SessionError:
if evt.Data.Message != nil {
fmt.Println("Error:", *evt.Data.Message)
}
}
})
Set Streaming: true in SessionConfig:
session, err := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
Streaming: true,
})
Handle both delta events (incremental) and final events:
done := make(chan struct{})
session.On(func(evt copilot.SessionEvent) {
switch evt.Type {
case copilot.AssistantMessageDelta:
// Incremental text chunk
if evt.Data.DeltaContent != nil {
fmt.Print(*evt.Data.DeltaContent)
}
case copilot.AssistantReasoningDelta:
// Incremental reasoning chunk (model-dependent)
if evt.Data.DeltaContent != nil {
fmt.Print(*evt.Data.DeltaContent)
}
case copilot.AssistantMessage:
// Final complete message
fmt.Println("\n--- Final ---")
if evt.Data.Content != nil {
fmt.Println(*evt.Data.Content)
}
case copilot.AssistantReasoning:
// Final reasoning content
fmt.Println("--- Reasoning ---")
if evt.Data.Content != nil {
fmt.Println(*evt.Data.Content)
}
case copilot.SessionIdle:
close(done)
}
})
session.Send(copilot.MessageOptions{Prompt: "Tell me a story"})
<-done
Note: Final events (AssistantMessage, AssistantReasoning) are ALWAYS sent regardless of streaming setting.
session, err := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
Tools: []copilot.Tool{
{
Name: "lookup_issue",
Description: "Fetch issue details from tracker",
Parameters: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"id": map[string]interface{}{
"type": "string",
"description": "Issue ID",
},
},
"required": []string{"id"},
},
Handler: func(inv copilot.ToolInvocation) (copilot.ToolResult, error) {
args := inv.Arguments.(map[string]interface{})
issueID := args["id"].(string)
issue, err := fetchIssue(issueID)
if err != nil {
return copilot.ToolResult{}, err
}
return copilot.ToolResult{
TextResultForLLM: fmt.Sprintf("Issue: %v", issue),
ResultType: "success",
ToolTelemetry: map[string]interface{}{},
}, nil
},
},
},
})
ToolResult struct with fields:TextResultForLLM (string) - Result text for the LLMResultType (string) - "success" or "failure"Error (string, optional) - Internal error message (not shown to LLM)ToolTelemetry (map[string]interface{}) - Telemetry dataWhen Copilot invokes a tool, the client automatically:
session, err := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
SystemMessage: &copilot.SystemMessageConfig{
Mode: "append",
Content: `
<workflow_rules>
- Always check for security vulnerabilities
- Suggest performance improvements when applicable
</workflow_rules>
`,
},
})
session, err := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
SystemMessage: &copilot.SystemMessageConfig{
Mode: "replace",
Content: "You are a helpful assistant.",
},
})
Attach files to messages using Attachment:
messageID, err := session.Send(copilot.MessageOptions{
Prompt: "Analyze this file",
Attachments: []copilot.Attachment{
{
Type: "file",
Path: "/path/to/file.go",
DisplayName: "My File",
},
},
})
Use the Mode field in MessageOptions:
"enqueue" - Queue message for processing"immediate" - Process message immediatelysession.Send(copilot.MessageOptions{
Prompt: "...",
Mode: "enqueue",
})
Sessions are independent and can run concurrently:
session1, _ := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
})
session2, _ := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "claude-sonnet-4.5",
})
session1.Send(copilot.MessageOptions{Prompt: "Hello from session 1"})
session2.Send(copilot.MessageOptions{Prompt: "Hello from session 2"})
Use custom API providers by configuring ProviderConfig:
session, err := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Provider: &copilot.ProviderConfig{
Type: "openai",
BaseURL: "https://api.openai.com/v1",
APIKey: "your-api-key",
},
})
state := client.GetState()
// Returns: "disconnected", "connecting", "connected", or "error"
session, err := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
})
if err != nil {
log.Fatalf("Failed to create session: %v", err)
}
_, err = session.Send(copilot.MessageOptions{Prompt: "Hello"})
if err != nil {
log.Printf("Failed to send: %v", err)
}
Monitor SessionError type for runtime errors:
session.On(func(evt copilot.SessionEvent) {
if evt.Type == copilot.SessionError {
if evt.Data.Message != nil {
fmt.Fprintf(os.Stderr, "Session Error: %s\n", *evt.Data.Message)
}
}
})
Use Ping to verify server connectivity:
resp, err := client.Ping("test message")
if err != nil {
log.Printf("Server unreachable: %v", err)
} else {
log.Printf("Server responded at %d", resp.Timestamp)
}
ALWAYS use defer for cleanup:
client := copilot.NewClient(nil)
if err := client.Start(); err != nil {
log.Fatal(err)
}
defer client.Stop()
session, err := client.CreateSession(&copilot.SessionConfig{OnPermissionRequest: copilot.PermissionHandler.ApproveAll})
if err != nil {
log.Fatal(err)
}
defer session.Destroy()
If not using defer:
client := copilot.NewClient(nil)
err := client.Start()
if err != nil {
log.Fatal(err)
}
session, err := client.CreateSession(&copilot.SessionConfig{OnPermissionRequest: copilot.PermissionHandler.ApproveAll})
if err != nil {
client.Stop()
log.Fatal(err)
}
// Use session...
session.Destroy()
errors := client.Stop()
for _, err := range errors {
log.Printf("Cleanup error: %v", err)
}
defer for cleanup of clients and sessionsclient := copilot.NewClient(nil)
if err := client.Start(); err != nil {
log.Fatal(err)
}
defer client.Stop()
session, err := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
})
if err != nil {
log.Fatal(err)
}
defer session.Destroy()
done := make(chan struct{})
session.On(func(evt copilot.SessionEvent) {
if evt.Type == copilot.AssistantMessage && evt.Data.Content != nil {
fmt.Println(*evt.Data.Content)
} else if evt.Type == copilot.SessionIdle {
close(done)
}
})
session.Send(copilot.MessageOptions{Prompt: "What is 2+2?"})
<-done
session, _ := client.CreateSession(&copilot.SessionConfig{OnPermissionRequest: copilot.PermissionHandler.ApproveAll})
defer session.Destroy()
sendAndWait := func(prompt string) error {
done := make(chan struct{})
var eventErr error
unsubscribe := session.On(func(evt copilot.SessionEvent) {
switch evt.Type {
case copilot.AssistantMessage:
if evt.Data.Content != nil {
fmt.Println(*evt.Data.Content)
}
case copilot.SessionIdle:
close(done)
case copilot.SessionError:
if evt.Data.Message != nil {
eventErr = fmt.Errorf(*evt.Data.Message)
}
}
})
defer unsubscribe()
if _, err := session.Send(copilot.MessageOptions{Prompt: prompt}); err != nil {
return err
}
<-done
return eventErr
}
sendAndWait("What is the capital of France?")
sendAndWait("What is its population?")
// Use built-in SendAndWait for simpler synchronous interaction
response, err := session.SendAndWait(copilot.MessageOptions{
Prompt: "What is 2+2?",
}, 0) // 0 uses default 60s timeout
if err != nil {
log.Printf("Error: %v", err)
}
if response != nil && response.Data.Content != nil {
fmt.Println(*response.Data.Content)
}
type UserInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Role string `json:"role"`
}
session, _ := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Tools: []copilot.Tool{
{
Name: "get_user",
Description: "Retrieve user information",
Parameters: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"user_id": map[string]interface{}{
"type": "string",
"description": "User ID",
},
},
"required": []string{"user_id"},
},
Handler: func(inv copilot.ToolInvocation) (copilot.ToolResult, error) {
args := inv.Arguments.(map[string]interface{})
userID := args["user_id"].(string)
user := UserInfo{
ID: userID,
Name: "John Doe",
Email: "john@example.com",
Role: "Developer",
}
jsonBytes, _ := json.Marshal(user)
return copilot.ToolResult{
TextResultForLLM: string(jsonBytes),
ResultType: "success",
ToolTelemetry: map[string]interface{}{},
}, nil
},
},
},
})
© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com


Sea turtle carrying floating film studio island
Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.
image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost
Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.
video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

Cozy Pixel Art Farm Island Village
Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.
image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape
Loading reviews…
Loading comments…