How to Use the GitHub Copilot SDK with Node.js: Complete Integration Guide
The GitHub Copilot SDK for Node.js lets you embed the Copilot CLI engine into JavaScript applications using CopilotClient to spawn JSON-RPC processes, CopilotSession to manage conversations, and defineTool to expose custom functions to the model.
The GitHub Copilot SDK provides a TypeScript-native way to integrate GitHub's AI coding assistant directly into Node.js applications. Unlike the VS Code extension, this SDK allows you to programmatically control Copilot sessions, define custom tools, and handle streaming responses within your own software. This guide explains how to use the GitHub Copilot SDK with Node.js based on the official github/copilot-sdk repository source code.
Installation and Prerequisites
Install the SDK from the official npm registry. The package bundles the Copilot CLI binary automatically, so no separate installation is required.
npm install @github/copilot-sdk
You will also need Zod for schema validation when defining tools:
npm install zod
Core Architecture
The SDK abstracts the low-level JSON-RPC communication with three primary components:
CopilotClient
The CopilotClient class in nodejs/src/client.ts serves as the entry point. It spawns the Copilot CLI process, establishes a JSON-RPC channel over stdio (or TCP), and manages the lifecycle including authentication and telemetry.
Key methods include:
start()– Launches the CLI processcreateSession()– Initializes a new conversation contextstop()– Gracefully shuts down the CLI
CopilotSession
The CopilotSession class in nodejs/src/session.ts represents a single conversation with the model. It handles message transmission, awaits responses, and routes events such as assistant.message, tool.execution_start, and tool.execution_complete.
Use session.sendAndWait() to transmit prompts and block until the model returns a final response.
Tool Definitions
The defineTool helper in nodejs/src/toolSet.ts enables you to expose JavaScript functions to the model. When the model invokes a tool, the SDK serializes the arguments, executes your handler, and returns the result to the CLI.
Implementing Your First Integration
Creating a Client
Instantiate CopilotClient with configuration options. Use the await using syntax (TC39 explicit resource management) to ensure automatic cleanup, or manually call client.stop() if using older Node.js versions.
import { CopilotClient } from "@github/copilot-sdk";
await using client = new CopilotClient({ logLevel: "info" });
Managing Sessions
Create a session using client.createSession(). Configure permission handling with approveAll for automatic tool approval, or provide custom logic to review each request.
import { approveAll } from "@github/copilot-sdk";
await using session = await client.createSession({
onPermissionRequest: approveAll,
});
console.log(`Session created: ${session.sessionId}`);
Sending Prompts
Send messages and await responses using the sendAndWait() method. This returns a typed result containing the assistant's content.
const result = await session.sendAndWait({
prompt: "What is 2 + 2?"
});
console.log("Answer:", result?.data.content);
Working with Custom Tools
Defining Tools with Zod
Use defineTool() to register functions that the model can invoke. Define parameters using Zod schemas for runtime validation and type safety.
import { defineTool } from "@github/copilot-sdk";
import { z } from "zod";
const lookupFact = defineTool("lookup_fact", {
description: "Returns a fun fact about a given topic.",
parameters: z.object({
topic: z.string()
}),
handler: ({ topic }) => {
const facts: Record<string, string> = {
javascript: "Created in 10 days by Brendan Eich (1995).",
node: "Runs JavaScript outside the browser using V8."
};
return facts[topic.toLowerCase()] ?? `No fact for ${topic}.`;
},
});
Handling Tool Execution
Pass your tool definitions to the session configuration:
await using session = await client.createSession({
onPermissionRequest: approveAll,
tools: [lookupFact],
});
// The model can now invoke lookup_fact automatically
const result = await session.sendAndWait({
prompt: "Use lookup_fact to tell me about 'node'"
});
Advanced Configuration
Streaming Responses
Listen to events on the session instance to handle streaming tokens or track tool execution progress. This is defined in nodejs/src/session.ts.
session.on("assistant.message_delta", (e) => {
process.stdout.write(e.data.deltaContent);
});
session.on("assistant.message", (e) => {
console.log("\nFinal:", e.data.content);
});
session.on("session.idle", () => {
console.log("Session idle");
});
Custom LLM Providers
The SDK supports Bring Your Own Key (BYOK) configurations to use non-GitHub models such as Ollama or private OpenAI endpoints. Specify the provider details in createSession():
await using session = await client.createSession({
model: "deepseek-coder-v2:16b",
provider: {
type: "openai",
baseUrl: "http://localhost:11434/v1", // Ollama endpoint
},
});
Summary
- Install the SDK via
npm install @github/copilot-sdk—the CLI binary is bundled automatically. - Initialize with
CopilotClientinnodejs/src/client.tsto manage the JSON-RPC transport. - Create sessions using
client.createSession()to establish isolated conversation contexts. - Define tools with
defineTool()fromnodejs/src/toolSet.tsto expose custom JavaScript functions to the model using Zod schemas. - Stream output by listening to
assistant.message_deltaevents on the session object. - Use custom providers by specifying
providerconfiguration in the session options for non-GitHub LLMs.
Frequently Asked Questions
Do I need VS Code installed to use the Copilot SDK?
No. According to the github/copilot-sdk source code, the SDK bundles the Copilot CLI engine automatically. The CopilotClient spawns this process and manages the JSON-RPC communication independently of any editor.
How does authentication work with the SDK?
The SDK handles authentication automatically through the bundled CLI. When you first run your application, the CLI process prompts for GitHub authentication via the standard device flow, caching credentials for subsequent sessions. You do not need to manually manage tokens in your Node.js code.
Can I use models other than GitHub Copilot?
Yes. As implemented in nodejs/src/session.ts, you can configure custom providers in the session options. Set the provider property with type: "openai" and specify your baseUrl to connect to Ollama, Azure OpenAI, or other compatible endpoints.
What Node.js version is required for the await using syntax?
The await using keyword requires Node.js 20 or newer with the explicit resource management proposal enabled, or Node.js 22+ where it is available by default. For older versions, manually call session.disconnect() and client.stop() to prevent process hanging.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →