AI

How to Build AI Agents with GitHub Copilot SDK (2026)

How to Build AI Agents with GitHub Copilot SDK (2026)

Image: GitHub

TL;DR — GitHub Copilot SDK reached GA on June 2, 2026 [^github-changelog]. It lets you embed Copilot’s agentic engine into your own apps across 6 languages (TypeScript, Python, Go, .NET, Rust, Java) with MCP support, BYOK for any LLM, and OpenTelemetry tracing. This guide walks through building a working agent from scratch — no orchestration layer needed.

What you’ll build: A TypeScript console app that spins up a Copilot-powered coding agent, registers custom tools, connects to an MCP server, and streams the session — all in ~50 lines of code.


What You Need

Requirement Details Where to Get
GitHub account Copilot Free tier works; Copilot Pro/Enterprise for higher limits github.com
Node.js ≥18.x (LTS recommended) nodejs.org
npm Bundled with Node.js
GitHub token Classic PAT with copilot scope or OAuth App GitHub Settings → Developer settings
Skill level Intermediate TypeScript/JavaScript

Optional for BYOK: OpenAI API key, Anthropic API key, or Azure Foundry endpoint — lets you use Copilot SDK without a Copilot subscription.


Step-by-Step Instructions

Step 1: Initialize the project

Goal: Create a minimal TypeScript project with Copilot SDK installed.

Instructions:
1. Create project folder and initialize:
bash
mkdir copilot-agent-demo && cd copilot-agent-demo
npm init -y

2. Install dependencies:
bash
npm install @github/copilot-sdk
npm install -D typescript tsx @types/node

3. Configure tsconfig.json:
json
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"esModuleInterop": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"]
}

⚠️ Common Mistake: Forgetting "module": "NodeNext" — the SDK uses ESM; CommonJS config will fail at runtime.
Fix: Use the exact tsconfig.json above.


Step 2: Create a basic agent session

Goal: Spin up a Copilot agent session and send a prompt.

Instructions:
1. Create src/basic-agent.ts:
“`typescript
import { createCopilotClient, GitHubAuth } from “@github/copilot-sdk”;

async function main() {
// Authenticate with GitHub token (or use OAuth flow)
const auth = new GitHubAuth({
token: process.env.GITHUB_TOKEN!, // classic PAT with copilot scope
});

 // Create client
 const client = createCopilotClient({ auth });

 // Start a session
 const session = await client.startSession({
   repo: "owner/repo", // optional: repo context for RAG
 });

 // Send a prompt to the agent
 const stream = session.stream({
   prompt: "Create a simple Express.js health check endpoint",
 });

 // Stream and print responses
 for await (const chunk of stream) {
   if (chunk.type === "text") process.stdout.write(chunk.text);
   if (chunk.type === "tool_call") {
     console.log(`\n🔧 Tool: ${chunk.name}`, chunk.input);
   }
   if (chunk.type === "tool_result") {
     console.log(`   ↳ Result:`, chunk.output);
   }
 }

 console.log("\n✅ Session complete");

}

main().catch(console.error);
“`

  1. Run it:
    bash
    GITHUB_TOKEN=ghp_xxx npx tsx src/basic-agent.ts

⚠️ Common Mistake: Token lacks copilot scope — SDK returns 403.
Fix: Create a classic PAT at github.com/settings/tokens with copilot scope checked.


Step 3: Register custom tools

Goal: Give the agent your own functions (e.g., database query, API call).

Instructions:
1. Create src/with-custom-tools.ts:
“`typescript
import { createCopilotClient, GitHubAuth, Tool } from “@github/copilot-sdk”;

// Define a custom tool
const getWeather: Tool = {
name: “getWeather”,
description: “Get current weather for a city”,
parameters: {
type: “object”,
properties: {
city: { type: “string”, description: “City name” },
},
required: [“city”],
},
async execute({ city }) {
// In real use: call weather API
return { city, temp: “22°C”, condition: “sunny” };
},
};

async function main() {
const auth = new GitHubAuth({ token: process.env.GITHUB_TOKEN! });
const client = createCopilotClient({ auth });

 const session = await client.startSession({
   tools: [getWeather], // register custom tool
 });

 const stream = session.stream({
   prompt: "What's the weather in Tokyo?",
 });

 for await (const chunk of stream) {
   if (chunk.type === "text") process.stdout.write(chunk.text);
   if (chunk.type === "tool_call") console.log(`\n🔧 ${chunk.name}`, chunk.input);
 }

}

main().catch(console.error);
“`

  1. Run it:
    bash
    GITHUB_TOKEN=ghp_xxx npx tsx src/with-custom-tools.ts

Step 4: Connect to an MCP server

Goal: Extend the agent with external capabilities via Model Context Protocol.

Instructions:
1. Create src/with-mcp.ts:
“`typescript
import { createCopilotClient, GitHubAuth, MCPServer } from “@github/copilot-sdk”;

async function main() {
const auth = new GitHubAuth({ token: process.env.GITHUB_TOKEN! });
const client = createCopilotClient({ auth });

 // Connect to a remote MCP server (e.g., GitHub's research-tracker-mcp)
 const mcpServer: MCPServer = {
   name: "research-tracker",
   transport: "stdio",
   command: "npx",
   args: ["-y", "@github/mcp-research-tracker"],
 };

 const session = await client.startSession({
   mcpServers: [mcpServer],
 });

 const stream = session.stream({
   prompt: "Find recent papers on transformer architecture improvements",
 });

 for await (const chunk of stream) {
   if (chunk.type === "text") process.stdout.write(chunk.text);
   if (chunk.type === "tool_call") console.log(`\n🔧 ${chunk.name}`, chunk.input);
 }

}

main().catch(console.error);
“`

  1. Run it:
    bash
    GITHUB_TOKEN=ghp_xxx npx tsx src/with-mcp.ts

⚠️ Common Mistake: MCP server binary not in PATH or npx fails.
Fix: Use absolute path to npx or ensure Node.js is in PATH. Test MCP server manually first: npx -y @github/mcp-research-tracker.


Step 5: Enable BYOK (Bring Your Own Key)

Goal: Use Copilot SDK with your own LLM provider (OpenAI, Anthropic, Azure).

Instructions:
1. Create src/with-byok.ts:
“`typescript
import { createCopilotClient, BYOKAuth } from “@github/copilot-sdk”;

async function main() {
// Use OpenAI key instead of GitHub Copilot subscription
const auth = new BYOKAuth({
provider: “openai”,
apiKey: process.env.OPENAI_API_KEY!,
model: “gpt-4o”, // or gpt-4o-mini, o1, etc.
});

 const client = createCopilotClient({ auth });
 const session = await client.startSession();

 const stream = session.stream({
   prompt: "Explain the difference between async/await and Promise.then in 3 sentences",
 });

 for await (const chunk of stream) {
   if (chunk.type === "text") process.stdout.write(chunk.text);
 }

}

main().catch(console.error);
“`

  1. Run it:
    bash
    OPENAI_API_KEY=sk-xxx npx tsx src/with-byok.ts

Step 6: Add OpenTelemetry tracing

Goal: Observe agent sessions in production with distributed tracing.

Instructions:
1. Install OTel deps:
bash
npm install @opentelemetry/api @opentelemetry/sdk-node @opentelemetry/auto-instrumentations-node

  1. Create src/with-tracing.ts:
    “`typescript
    import { createCopilotClient, GitHubAuth } from “@github/copilot-sdk”;
    import { NodeSDK } from “@opentelemetry/sdk-node”;
    import { getNodeAutoInstrumentations } from “@opentelemetry/auto-instrumentations-node”;
    import { ConsoleSpanExporter } from “@opentelemetry/sdk-trace-node”;

// Initialize OTel
const sdk = new NodeSDK({
traceExporter: new ConsoleSpanExporter(),
instrumentations: [getNodeAutoInstrumentations()],
});
sdk.start();

async function main() {
const auth = new GitHubAuth({ token: process.env.GITHUB_TOKEN! });
const client = createCopilotClient({ auth });

 const session = await client.startSession({
   repo: "owner/repo",
 });

 const stream = session.stream({
   prompt: "Add a README to this project",
 });

 for await (const chunk of stream) {
   if (chunk.type === "text") process.stdout.write(chunk.text);
 }

 // Graceful shutdown flushes traces
 await sdk.shutdown();

}

main().catch(console.error);
“`

  1. Run it:
    bash
    GITHUB_TOKEN=ghp_xxx npx tsx src/with-tracing.ts

Complete Workflow Diagram


Troubleshooting & FAQ

Error / Symptom Cause Fix
403 Forbidden on session start Token missing copilot scope Recreate PAT with copilot scope at github.com/settings/tokens
Module not found: @github/copilot-sdk Package not installed or wrong registry Run npm install @github/copilot-sdk; ensure npm registry is default
MCP server spawn fails npx not in PATH or binary missing Use absolute path: /usr/local/bin/npx or full path to Node.js
BYOK returns 401 Unauthorized Invalid API key or wrong provider string Verify key at provider dashboard; provider must be openai, anthropic, or azure
TypeScript errors on stream() tsconfig.json not using NodeNext modules Copy the exact tsconfig.json from Step 1
Session hangs on first prompt No internet access in sandbox (enterprise) Check org policy: Copilot agent needs outbound to api.github.com
Rust/Java/Go SDK not found Wrong package name Use exact names: github-copilot-sdk (PyPI), github.com/github/copilot-sdk/go, GitHub.Copilot.SDK (NuGet), github-copilot-sdk (crates.io), Maven com.github.copilot:sdk

Q: Do I need a Copilot subscription to use the SDK?
A: No — with BYOK (Bring Your Own Key), you can use OpenAI, Anthropic, or Azure keys. Copilot Free/Pro/Enterprise users can also use their included subscription.

Q: Can the agent access my private repositories?
A: Only if you pass repo: "owner/repo" to startSession() and the token has repo scope. The agent clones and reads the repo for context (RAG-powered code search).

Q: How does pricing work?
A: Copilot subscribers: included (uses premium requests). BYOK: you pay your LLM provider directly. No separate Copilot SDK charge.

Q: Can I run this in a CI/CD pipeline?
A: Yes — the SDK works in GitHub Actions, GitLab CI, etc. Use a GitHub App token or PAT with appropriate scopes. See GitHub Actions example.

Q: What’s the difference between Copilot SDK and the Copilot CLI?
A: CLI is a ready-made terminal interface. SDK is a programmatic library to embed the agent engine in your own app (VS Code extension, web app, CLI tool, etc.).


Best Use Cases

✅ Great for:
– Building custom AI coding assistants in your IDE/editor
– Automating PR reviews with agent-powered analysis
– Creating domain-specific agents (security audit, migration, documentation)
– Embedding Copilot in internal developer portals

❌ Not ideal for:
– Non-coding tasks (general chat, creative writing) — use ChatGPT/Claude directly
– Ultra-low-latency requirements (local models via Ollama/vLLM are faster)
– Teams without any GitHub infrastructure (auth requires GitHub)

🔄 Alternatives:
– Vercel AI SDK for web-native chat agents (React/Next.js focus)
– LangGraph for complex multi-agent orchestration
– Ollama + custom tools for fully local, no-cloud agents


Quick Checklist (Copy-Paste)

[ ] GitHub PAT with copilot scope created
[ ] Node.js 18+ installed
[ ] Project initialized with NodeNext modules
[ ] Basic agent session runs and streams output
[ ] Custom tool registered and invoked
[ ] MCP server connected (optional)
[ ] BYOK tested with OpenAI/Anthropic key (optional)
[ ] OpenTelemetry traces visible in console
[ ] Error handling added for production

Source & References

  • Official Announcement: GitHub Changelog — Copilot SDK GA (June 2, 2026) [^github-changelog]
  • Documentation: GitHub Copilot SDK Docs [^github-docs]
  • Cookbook: Practical recipes across all 6 languages [^github-cookbook]
  • SDK Repository: github/copilot-sdk [^github-repo]
  • Our Test Environment: Node.js 22.12.0, TypeScript 5.6, macOS Sequoia 15.5, tested June 16, 2026

Last updated 2026-06-16: Reviewed and updated for accuracy and current sourcing.

Editorially independent: we accept no payment for coverage and currently use no affiliate links. Read our Editorial Standards and Corrections Policy. Published: Jun 15, 2026.
Aira

Founding Editor and Publisher of ZBrandCo, covering artificial intelligence, open-source software, and the developer tools people actually use. Signal over hype: every story starts from a primary source and explains why it matters. ZBrandCo runs no paid reviews and no affiliate links. Tips and corrections: editorial@zbrandco.com.