GitHub Copilot SDK

Agents for Every App

Embed Copilot's agentic workflows in your application

TypeScript Python Go .NET Java
QR code to examples repo

Examples & slides

github.com/jeffreygroneberg/ghcp_sdk

๐Ÿ“– github.com/github/copilot-sdk

What is the GitHub Copilot SDK?

A programmable SDK that brings Copilot's agent runtime into your application โ€” no orchestration to build.

๐Ÿ—๏ธ Production-Tested

Same runtime behind Copilot CLI, battle-tested at scale

๐ŸŒ Multi-Language

TypeScript, Python, Go, .NET, and Java SDKs available

๐Ÿ”ง Extensible

Custom tools, agents, MCP servers, hooks, and skills

๐Ÿ“– README.md

Architecture

Your Application
โ†’
SDK Client
TS / Python / Go / .NET / Java
โ†’
Copilot CLI
JSON-RPC (stdio / TCP)
โ†’
Model Provider
GitHub ยท OpenAI ยท Azure ยท Anthropic ยท Local

โšก Auto-managed or external CLI

๐Ÿ’พ Session persistence

๐Ÿ‘ฅ Multi-client support (v3)

๐Ÿ“ก 40+ streaming event types

๐Ÿ“ˆ Horizontal scaling

๐Ÿ” OpenTelemetry tracing

๐Ÿ“– README.md โ€” Architecture

Available SDKs

LanguageInstall Command
Node.js / TypeScriptnpm install @github/copilot-sdk
Pythonpip install github-copilot-sdk
Gogo get github.com/github/copilot-sdk/go
.NETdotnet add package GitHub.Copilot.SDK
Javacom.github:copilot-sdk-java (Maven/Gradle)

Community SDKs also available: Rust, Clojure, C++

๐Ÿ“– README.md โ€” Available SDKs

Key Features

๐Ÿ”ง Custom Tools

Define functions Copilot can invoke

๐Ÿค– Custom Agents

Specialized AI personas with scoped tools

๐Ÿ”Œ MCP Servers

External tool integration via standard protocol

๐Ÿ“š Skills

Reusable prompt modules from directories

๐Ÿช Hooks

Intercept sessions for security and auditing

๐Ÿ“ก Streaming

40+ real-time event types

๐Ÿ”‘ BYOK

Bring your own model provider API keys

๐Ÿ“Š Observability

Built-in OpenTelemetry instrumentation

๐Ÿ“– docs/features/index.md

What Can You Build?

Real problems your teams face today โ€” solved with the SDK

๐Ÿ” Automated Code Review

Problem: Manual reviews miss security issues and take days

โ†’ Deploy a security auditor agent that reviews every PR in seconds using OWASP-focused prompts and read-only tools

๐Ÿš€ CI/CD Pipeline Intelligence

Problem: Pipelines fail silently; debugging takes hours

โ†’ Run agents in your pipeline that analyze failures, suggest fixes, and auto-generate test coverage

๐Ÿ—„๏ธ Database Query Assistants

Problem: Non-technical teams can't self-serve data queries

โ†’ Connect MCP servers to your database โ€” users ask in natural language, agent writes and explains SQL

๐Ÿ“ Documentation Generation

Problem: Docs are always outdated, nobody wants to write them

โ†’ Agents analyze your codebase and produce up-to-date, comprehensive documentation on every release

๐Ÿ“– docs/features/index.md

More Use Cases

๐Ÿ’ก AI-Powered SaaS Products

Problem: Building AI features requires custom orchestration and model plumbing

โ†’ Embed Copilot's agent runtime in your product with per-user OAuth, session isolation, and streaming โ€” ship AI features in days, not months

๐Ÿค Multi-Agent Workflows

Problem: Complex tasks need multiple specialized AI roles working together

โ†’ Use Microsoft Agent Framework to orchestrate Copilot alongside Azure OpenAI and Anthropic in sequential or parallel pipelines

โš™๏ธ DevOps Automation

Problem: Incident response and infrastructure changes require deep expertise

โ†’ Agents that diagnose production issues, manage infrastructure, and automate deployments with guardrailed shell access

๐Ÿ—๏ธ Internal Developer Platforms

Problem: Internal tools lack intelligence and require constant maintenance

โ†’ Embed Copilot in your developer portal, CLI tools, and dashboards โ€” let third-party teams build on your AI-powered platform

๐Ÿ“– docs/features/index.md

Built-in Tools

First-party tools available to every session โ€” all enabled by default

๐Ÿ“– File System โ€” Reading

  • read_file โ€” Read file contents
  • view โ€” View file or directory
  • glob โ€” Find files by name pattern
  • grep โ€” Search contents (ripgrep)
  • list_dir โ€” List directory contents

โœ๏ธ File System โ€” Writing

  • edit โ€” Targeted edits to existing files
  • create โ€” Create new files
  • write_file โ€” Write / overwrite files

โšก Shell, Web & Agent

  • bash / shell โ€” Execute commands
  • web_fetch โ€” Fetch content from URLs
  • task โ€” Delegate to sub-agents
  • ask_user โ€” Ask the user a question
  • store_memory โ€” Persist facts

Plus: MCP server tools (e.g. GitHub MCP) and your custom tools via @define_tool

๐Ÿ“– README.md โ€” Default tools ยท docs/features/hooks.md

Controlling Tool Access

Three ways to restrict what the agent can do

1. Session Config

Whitelist or blacklist at creation

session = await client.create_session(
  available_tools=[
    "grep", "glob", "view"
  ],
  # OR
  excluded_tools=[
    "bash", "shell"
  ],
)

2. onPreToolUse Hook

Dynamic per-call decisions

ALLOWED = [
  "read_file", "glob",
  "grep", "view"
]

async def on_pre_tool_use(inp, inv):
  if inp["toolName"] not in ALLOWED:
    return {
      "permissionDecision": "deny"
    }
  return {
    "permissionDecision": "allow"
  }

3. Override Built-ins

Replace with your own (v0.1.30+)

@define_tool(
  description="Custom grep",
  overrides_built_in_tool=True,
)
async def grep(params):
  # Your custom implementation
  return custom_search(
    params.query
  )

๐Ÿ“– docs/features/hooks.md ยท CHANGELOG v0.1.30

Custom Tools

Define custom functions that Copilot can invoke during conversations

You define a tool with a name, description, JSON Schema parameters, and a handler function. The agent automatically decides when to call it based on the user's prompt.

๐Ÿ”ง Define

Name, description, and typed parameters via JSON Schema

โšก Handle

Your async function runs when the agent calls the tool

๐Ÿ”— Register

Pass tools array to createSession()

๐Ÿ“– docs/getting-started.md โ€” Custom Tools

Custom Tools โ€” Code

const getWeather = defineTool("get_weather", {
  description: "Get the current weather for a city",
  parameters: {
    type: "object",
    properties: {
      city: { type: "string", description: "The city name" },
    },
    required: ["city"],
  },
  handler: async (args) => {
    const data = await fetchWeatherAPI(args.city);
    return { city: args.city, temp: data.temp, condition: data.condition };
  },
});

const session = await client.createSession({
  model: "gpt-4.1",
  tools: [getWeather],
});

๐Ÿ“– docs/getting-started.md โ€” Custom Tools

Custom Agents & Sub-Agent Orchestration

Define specialized AI personas with their own prompts, tool restrictions, and MCP servers

๐Ÿ” Research Agent

Tools: grep, glob, view

Analyze code, answer questions. Read-only.

โœ๏ธ Editor Agent

Tools: view, edit, bash

Make minimal, surgical code changes.

๐Ÿ›ก๏ธ Security Auditor

Tools: grep, glob, view

Focus on OWASP Top 10 vulnerabilities.

Automatic Delegation โ€” The runtime auto-selects the right agent based on user intent when infer: true is set.

๐Ÿ“– docs/features/custom-agents.md

MCP Server Integration

Model Context Protocol โ€” open standard for connecting AI to external tools

Local / Stdio

Runs as a subprocess, communicates via stdin/stdout

Local tools, file access, scripts

Remote / HTTP

Accessed via HTTP endpoint, supports SSE

Shared services, cloud tools

Connect to any MCP server from the community directory โ€” GitHub, SQLite, Puppeteer, filesystem, and more. The tools array controls which tools are exposed.

๐Ÿ“– docs/features/mcp.md

MCP Server Integration โ€” Code

const session = await client.createSession({
  mcpServers: {
    github: {
      type: "http",
      url: "https://api.githubcopilot.com/mcp/",
    },
    filesystem: {
      type: "local",
      command: "npx",
      args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
      tools: ["*"],
    },
  },
});

๐Ÿ“– docs/features/mcp.md

Hooks โ€” Session Lifecycle Control

onSessionStart

Add context, audit logging

onUserPromptSubmitted

Modify or filter user input

onPreToolUse

Approve, deny, or modify tool calls

onPostToolUse

Transform results, redact secrets

onErrorOccurred

Custom error handling, retry logic

onSessionEnd

Cleanup, finalize audit trail

Use for: permissions, auditing, prompt enrichment, secret redaction, error recovery

๐Ÿ“– docs/features/hooks.md

Authentication Deep Dive

Four methods โ€” choose based on your deployment scenario

Auth Flow

๐Ÿ‘ค CLI Login ๐Ÿ”‘ OAuth App โš™๏ธ Env Var ๐Ÿ—๏ธ BYOK
โ–ผ
SDK Client โ†’ Copilot CLI
โ–ผ
โ˜๏ธ Copilot API (subscription) or โ˜๏ธ BYOK Provider (no sub)
MethodUse CaseSubscription
๐Ÿ‘ค Signed-in UserDesktop, local devRequired
๐Ÿ”‘ OAuth AppWeb apps, SaaSRequired
โš™๏ธ Env VariablesCI/CD, automationRequired
๐Ÿ—๏ธ BYOKOwn API keysNot Required

Token support: gho_ โœ… ยท ghu_ โœ… ยท github_pat_ โœ… ยท ghp_ โŒ
OAuth Apps + GitHub Apps both supported for multi-user scenarios

๐Ÿ“– docs/auth/index.md

OAuth GitHub App Integration

Build multi-user apps โ€” each user authenticates with their GitHub account

OAuth Flow

1. User clicks "Sign in with GitHub"
2. Redirect โ†’ GitHub OAuth โ†’ user approves
3. Exchange code โ†’ gho_xxx token
4. Pass token โ†’ SDK via githubToken
5. Requests made as that user (their subscription)

Enterprise: Works with org memberships, EMU, and SAML SSO automatically.

Code Example

const client = new CopilotClient({
  githubToken: userAccessToken,
  useLoggedInUser: false,
});

const session = await client.createSession({
  sessionId: `user-${userId}`,
  model: "gpt-4.1",
  onPermissionRequest: approveAll,
});

๐Ÿ“– docs/setup/github-oauth.md ยท docs/auth/index.md

BYOK โ€” Bring Your Own Key

Use your own model provider API keys โ€” no Copilot subscription required

OpenAI

Direct API access

Azure AI Foundry

Enterprise deployments

Anthropic

Claude models

Ollama

Local models

Foundry Local

On-device AI

Other

vLLM, LiteLLM, etc.

๐Ÿ“– docs/auth/byok.md

BYOK โ€” Code

const session = await client.createSession({
  model: "gpt-5.2-codex",
  provider: {
    type: "openai",
    baseUrl: "https://your-resource.openai.azure.com/openai/v1/",
    wireApi: "responses",
    apiKey: process.env.FOUNDRY_API_KEY,
  },
});

The wireApi setting controls the API format โ€” use "responses" for newer GPT-5 series models and "completions" for older ones.

๐Ÿ“– docs/auth/byok.md

How the SDK Talks to the CLI

All SDKs communicate via JSON-RPC โ€” the SDK manages the CLI process lifecycle automatically

Mode 1: stdio (Auto-Managed)

SDK spawns CLI as a child process

  • Zero config โ€” just new CopilotClient()
  • CLI dies with your app
  • Best for: local dev, desktop apps

Mode 2: TCP (External Server)

CLI runs as a headless server on a port

  • copilot --headless --port 4321
  • Independent lifecycle, multi-client
  • Best for: APIs, backends, scaling

๐Ÿ“– docs/setup/local-cli.md ยท backend-services.md

Ship It โ€” Bundled Deployment

Package the Copilot CLI binary alongside your application โ€” users don't need to install anything separately.

Supported Platforms

  • Desktop apps (Electron, Tauri)
  • Docker containers
  • Distributable CLI tools

Multi-Platform Binaries

  • copilot-darwin-arm64
  • copilot-linux-x64
  • copilot-win-x64.exe

๐Ÿ“– docs/setup/bundled-cli.md

Deployment Patterns

๐Ÿ’ป Local CLI

SDK spawns CLI as child process. Simplest path for personal projects and development.

๐Ÿ“ฆ Bundled CLI

Ship the CLI binary with your app. Standalone apps with zero external dependencies.

๐Ÿ–ฅ๏ธ Backend Services

CLI as headless server over TCP. Web backends, APIs, and microservices.

๐Ÿ“ˆ Scaling

Horizontal scaling with session isolation. Serve thousands of users reliably.

๐Ÿ“– docs/setup/index.md

Microsoft Agent Framework Integration

Compose Copilot alongside Azure OpenAI, Anthropic, and others in orchestrated workflows

Sequential Workflow

Copilot Agent
Code Review
โ†’
Azure Agent
Documentation
โ†’
Combined
Final Output

Concurrent Workflow

Security Reviewer
Perf Reviewer
โ†’
Aggregated Result
Unified successor to Semantic Kernel & AutoGen .NET and Python A2A protocol support Full streaming

๐Ÿ“– docs/integrations/microsoft-agent-framework.md

Demo 1: Simple Chat โ€” TypeScript

What this does: Create a client, open a session, send a prompt, and get a response โ€” the "Hello World" of the SDK. Just 6 lines of meaningful code.

import { CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient();
const session = await client.createSession({
  model: "gpt-4.1",
  onPermissionRequest: async () =>
    ({ kind: "approved" }),
});

const response = await session.sendAndWait({
  prompt: "Explain how async/await works"
});

console.log(response?.data.content);
await client.stop();

๐Ÿ“– docs/getting-started.md

Demo 1: Simple Chat โ€” Python

What this does: Same "Hello World" in Python โ€” identical concept, idiomatic API. The v0.2.0 SDK uses keyword arguments and positional prompts.

from copilot import CopilotClient
from copilot 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(
  "Explain how async/await works"
)

print(response.data.content)
await client.stop()

๐Ÿ“– python/README.md

Demo 2: Custom Tool โ€” Ticket Lookup

What this does: Define a tool that queries your internal ticket system. The agent automatically calls it when a user asks about a ticket โ€” no routing code needed. This pattern works for any internal system: CRMs, dashboards, HR tools.

const lookupTicket = defineTool("lookup_ticket", {
  description: "Look up a support ticket by ID",
  parameters: {
    type: "object",
    properties: {
      ticketId: { type: "string", description: "Ticket ID (e.g. TICK-1234)" },
    },
    required: ["ticketId"],
  },
  handler: async (args) => {
    const ticket = await db.tickets.findById(args.ticketId);
    return {
      id: ticket.id, status: ticket.status,
      title: ticket.title, assignee: ticket.assignee,
    };
  },
});

๐Ÿ“– docs/getting-started.md โ€” Custom Tools

Demo 2: Ticket Lookup โ€” Usage

What this does: Register the tool, send a natural language question. The agent recognizes it needs the ticket tool, calls it automatically, and formulates a human-readable answer from the structured data.

const session = await client.createSession({
  model: "gpt-4.1",
  tools: [lookupTicket],
  onPermissionRequest: async () => ({ kind: "approved" }),
});

await session.sendAndWait({
  prompt: "What's the status of TICK-4521?"
});
// Copilot automatically calls lookup_ticket("TICK-4521")

This pattern works for any internal system: CRMs, monitoring dashboards, inventory systems, HR tools โ€” anything with an API or database.

๐Ÿ“– docs/getting-started.md โ€” Custom Tools

Demo 3: Backend API Service

What this does: Run Copilot as a production backend โ€” the CLI runs as a headless server, your Express API connects over TCP, each user gets their own session with per-user OAuth. This is the pattern for SaaS products and internal tools at scale.

import express from "express";
import { CopilotClient } from "@github/copilot-sdk";

const app = express();
app.use(express.json());

// Connect to headless CLI server
const client = new CopilotClient({ cliUrl: "localhost:4321" });

app.post("/api/chat", async (req, res) => {
  const { sessionId, message, userToken } = req.body;

  const session = await client.createSession({
    sessionId: `user-${sessionId}`,
    model: "gpt-4.1",
    githubToken: userToken,  // Per-user OAuth token
  });

  const response = await session.sendAndWait({ prompt: message });
  res.json({ sessionId, content: response?.data.content });
});

app.listen(3000);

๐Ÿ“– docs/setup/backend-services.md

Get Started Today

1๏ธโƒฃ Install Copilot CLI

Follow the Copilot CLI installation guide

2๏ธโƒฃ Install Your SDK

npm, pip, go get, dotnet add, or Maven/Gradle

3๏ธโƒฃ Create Your First Session

client.createSession({ model: "gpt-4.1" })

ResourceLink
SDK Repositorygithub.com/github/copilot-sdk
Documentationdocs/ in the repository
Cookbook & Recipesgithub.com/github/awesome-copilot
Java SDKgithub.com/github/copilot-sdk-java
GitHub MCP Servergithub.com/github/github-mcp-server

๐Ÿ“– github.com/github/copilot-sdk

Demo 4: Real-Time Streaming

Stream AI responses token by token for interactive, real-time user experiences

const session = await client.createSession({
  model: "gpt-4.1",
  streaming: true,
  onPermissionRequest: async () => ({ kind: "approved" }),
});

// Subscribe to real-time streaming events
session.on("assistant.message_delta", (event) => {
  process.stdout.write(event.data.delta ?? "");
});

session.on("assistant.message", (event) => {
  console.log("\n--- Full response complete ---");
});

await session.sendAndWait({
  prompt: "Write a quicksort implementation in TypeScript"
});

๐Ÿ“– docs/features/streaming-events.md

Demo 5: Security Audit with Hooks

Combine custom agents with hooks for enterprise-grade auditing

const READ_ONLY_TOOLS = ["read_file", "glob", "grep", "view"];

const session = await client.createSession({
  model: "gpt-4.1",
  customAgents: [{
    name: "security-auditor",
    prompt: "You are a security expert. Focus on OWASP Top 10.",
    tools: READ_ONLY_TOOLS,
  }],
  agent: "security-auditor",
});

๐Ÿ“– docs/hooks/pre-tool-use.md

Demo 5: Security Hooks

hooks: {
  onPreToolUse: async (input) => {
    // Enforce read-only: deny any write operations
    if (!READ_ONLY_TOOLS.includes(input.toolName)) {
      return { permissionDecision: "deny",
        permissionDecisionReason: `"${input.toolName}" blocked` };
    }
    return { permissionDecision: "allow" };
  },
  onPostToolUse: async (input) => {
    // Redact any secrets found in tool output
    if (typeof input.toolResult === "string") {
      const redacted = input.toolResult.replace(
        /api[_-]?key\s*[:=]\s*["']?[\w\-\.]+["']?/gi, "[REDACTED]");
      if (redacted !== input.toolResult)
        return { modifiedResult: redacted };
    }
    return null;
  },
}

๐Ÿ“– docs/hooks/pre-tool-use.md

๐Ÿš€ What's New in v0.2.0

A major release with new capabilities, API refinements, and breaking changes

โœจ New Features

  • System prompt customization โ€” surgically edit 10 prompt sections (identity, tone, safety, โ€ฆ) with replace/append/prepend/transform actions
  • Blob attachments โ€” send images and binary data inline without writing to disk
  • skipPermission on tools โ€” bypass confirmation for low-risk read-only tools
  • OpenTelemetry โ€” full distributed tracing across all 4 SDKs
  • New RPC methods โ€” skills, MCP, extensions, shell, and plugin management

โš ๏ธ Breaking Changes

  • Python API overhaul โ€” keyword args replace TypedDicts
  • autoRestart removed โ€” deprecated across all SDKs
  • Go Start() context โ€” cancelling context no longer kills CLI process; use Stop()
  • Go LogOptions.Ephemeral โ€” changed from bool to *bool
  • Python internal modules โ€” copilot.jsonrpc โ†’ copilot._jsonrpc

๐Ÿ“– releases/tag/v0.2.0

v0.2.0: System Prompt Customization

Surgically edit individual sections of the Copilot system prompt

identity โ†’ tone โ†’ tool_efficiency โ†’ environment_context โ†’ code_change_rules
guidelines โ†’ safety โ†’ tool_instructions โ†’ custom_instructions โ†’ last_instructions

Actions per section

replaceReplace entire section content
appendAdd content after the section
prependAdd content before the section
removeRemove the section entirely
transformCallback โ€” receives text, returns modified

Example

await client.createSession({
  systemMessage: {
    mode: "customize",
    sections: {
      identity: {
        action: (current) =>
          current.replace("Copilot",
            "Acme Assistant"),
      },
      tone: {
        action: "replace",
        content: "Be concise.",
      },
    },
  },
});

๐Ÿ“– releases/tag/v0.2.0 ยท PR #816