Copilot SDK
intellectronica/agent-skills
This skill helps with GitHub Copilot SDK work across Node.js/TypeScript, Python, Go, .NET, and Java.
Build applications powered by GitHub Copilot using the Copilot SDK.
$ npx skills add microsoft/skills --skill copilot-sdk -a claude-codeProject install by default; add -g for ~/.claude/skills/.
$ gh skill install microsoft/skills copilot-sdk --agent claude-codeProject scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).
$ git clone --depth 1 https://github.com/microsoft/skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.github/skills/copilot-sdk .claude/skills/copilot-sdk && rm -rf skills-srcUse ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.
Claude Code skills documentation · loads skills from .claude/skills/
Install the "copilot-sdk" agent skill from https://github.com/microsoft/skills/tree/main/.github/skills/copilot-sdk into .claude/skills/copilot-sdk/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "copilot-sdk", then confirm the skill loads.Claude Code copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$skill-installer install https://github.com/microsoft/skills/tree/main/.github/skills/copilot-sdkType this inside Codex. $skill-installer <name> installs a curated skill from openai/skills. The installer writes to $CODEX_HOME/skills (default ~/.codex/skills). Restart Codex if the skill does not show up.
$ npx skills add microsoft/skills --skill copilot-sdk -a codexProject install goes to .agents/skills/; add -g for ~/.codex/skills/.
$ gh skill install microsoft/skills copilot-sdk --agent codexProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/microsoft/skills.git skills-src && mkdir -p .agents/skills && cp -r skills-src/.github/skills/copilot-sdk .agents/skills/copilot-sdk && rm -rf skills-srcUse ~/.agents/skills/ instead of .agents/skills for a personal install.
Codex skills documentation · loads skills from .agents/skills/
Install the "copilot-sdk" agent skill from https://github.com/microsoft/skills/tree/main/.github/skills/copilot-sdk into .agents/skills/copilot-sdk/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "copilot-sdk", then confirm the skill loads.Codex copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add microsoft/skills --skill copilot-sdk -a cursorProject install goes to .agents/skills/; add -g for ~/.cursor/skills/.
$ gh skill install microsoft/skills copilot-sdk --agent cursorProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/microsoft/skills.git skills-src && mkdir -p .cursor/skills && cp -r skills-src/.github/skills/copilot-sdk .cursor/skills/copilot-sdk && rm -rf skills-srcUse ~/.cursor/skills/ instead of .cursor/skills for a personal install.
Cursor skills documentation · loads skills from .cursor/skills/, .agents/skills/, .claude/skills/, .codex/skills/
Install the "copilot-sdk" agent skill from https://github.com/microsoft/skills/tree/main/.github/skills/copilot-sdk into .cursor/skills/copilot-sdk/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "copilot-sdk", then confirm the skill loads.Cursor copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gemini skills install https://github.com/microsoft/skills.git --path .github/skills/copilot-sdk--scope user (default) or --scope workspace; --path is the subfolder of the repo that holds the skill; --consent skips the security confirmation prompt.
$ npx skills add microsoft/skills --skill copilot-sdk -a gemini-cliProject install goes to .agents/skills/; add -g for ~/.gemini/skills/.
$ gh skill install microsoft/skills copilot-sdk --agent gemini-cliProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/microsoft/skills.git skills-src && mkdir -p .gemini/skills && cp -r skills-src/.github/skills/copilot-sdk .gemini/skills/copilot-sdk && rm -rf skills-srcUse ~/.gemini/skills/ instead of .gemini/skills for a personal install, then run /skills reload.
Gemini CLI skills documentation · loads skills from .gemini/skills/, .agents/skills/
Install the "copilot-sdk" agent skill from https://github.com/microsoft/skills/tree/main/.github/skills/copilot-sdk into .gemini/skills/copilot-sdk/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "copilot-sdk", then confirm the skill loads.Gemini CLI copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gh skill install microsoft/skills copilot-sdkInstalls for Copilot at project scope by default; add --scope user for a personal install. Preview a skill first with gh skill preview. Needs GitHub CLI 2.90.0 or later (public preview).
$ npx skills add microsoft/skills --skill copilot-sdk -a github-copilotProject install goes to .agents/skills/; add -g for ~/.copilot/skills/.
$ git clone --depth 1 https://github.com/microsoft/skills.git skills-src && mkdir -p .github/skills && cp -r skills-src/.github/skills/copilot-sdk .github/skills/copilot-sdk && rm -rf skills-srcUse ~/.copilot/skills/ instead of .github/skills for a personal install. Commit .github/skills so cloud agent and code review can use it.
GitHub Copilot skills documentation · loads skills from .github/skills/, .claude/skills/, .agents/skills/
Install the "copilot-sdk" agent skill from https://github.com/microsoft/skills/tree/main/.github/skills/copilot-sdk into .github/skills/copilot-sdk/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "copilot-sdk", then confirm the skill loads.GitHub Copilot copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add microsoft/skills --skill copilot-sdk -a opencodeOpenCode documents no install command of its own. Project install goes to .agents/skills/; add -g for ~/.config/opencode/skills/.
$ gh skill install microsoft/skills copilot-sdk --agent opencodeProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/microsoft/skills.git skills-src && mkdir -p .opencode/skills && cp -r skills-src/.github/skills/copilot-sdk .opencode/skills/copilot-sdk && rm -rf skills-srcUse ~/.config/opencode/skills/ instead of .opencode/skills for a personal install.
OpenCode skills documentation · loads skills from .opencode/skills/, .claude/skills/, .agents/skills/
Install the "copilot-sdk" agent skill from https://github.com/microsoft/skills/tree/main/.github/skills/copilot-sdk into .opencode/skills/copilot-sdk/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "copilot-sdk", then confirm the skill loads.OpenCode copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
copilot-sdkBuild applications powered by GitHub Copilot using the Copilot SDK.
Copilot SDK is an agent skill from microsoft/skills, published by the product's own GitHub organization. Build applications powered by GitHub Copilot using the Copilot SDK. Use when creating programmatic integrations with Copilot across Node.js/TypeScript, Python, Go, or .NET. Covers session management, custom tools, streaming, hooks, MCP servers, BYOK providers, session persistence, custom agents, skills, and deployment patterns. Requires GitHub Copilot CLI installed and a GitHub Copilot subscription (unless using BYOK).
Its SKILL.md is about 7.1k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.
It sits in Agent Workflows, covering Authentication and MCP servers. It works with TypeScript, .NET, Python and Node.js. The repository describes itself as: Skills, MCP servers, Custom Agents, Agents.md for SDKs to ground Coding Agents. The licence is MIT.
6 steps, taken from the first numbered list in SKILL.md.
Read from SKILL.md and the folder at commit 354361d. It shows what the files ask for, not the result of running them.
Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.
From allowed-tools in the SKILL.md frontmatter.
Shell commands in SKILL.md call:
npxnpmpipgodotnetghFrom the folder's file list and the shell code blocks in SKILL.md.
Hosts in commands or code, which the agent is likely to contact:
api.githubcopilot.comapi.openai.comapi.anthropic.comcognitiveservices.azure.comAlso links to:
github.comdocs.github.commodelcontextprotocol.ioFrom URLs in SKILL.md, links to its own repository left out.
Names these keys or tokens, usually read from environment variables:
COPILOT_GITHUB_TOKENGITHUB_TOKENCAPI_HMAC_KEYCOPILOT_HMAC_KEYGITHUB_COPILOT_API_TOKENGH_TOKENOPENAI_API_KEYFOUNDRY_API_KEYAZURE_OPENAI_KEYANTHROPIC_API_KEYFrom names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.
Copilot SDK loads about 7.1k tokens when it runs. Until then it costs about 109 tokens; SKILL.md has 1,535 words of instructions outside code blocks.
Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.
The automated check found no risky patterns in SKILL.md.
Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.
The full file from microsoft/skills at commit 354361d, republished under its MIT licence (© microsoft). 1,535 words, ~7,118 tokens.
.claude/skills/copilot-sdk/SKILL.md (or your agent's skills folder).Build applications that programmatically interact with GitHub Copilot. The SDK wraps the Copilot CLI via JSON-RPC, providing session management, custom tools, hooks, MCP server integration, and streaming across Node.js, Python, Go, and .NET.
copilot --version)| Language | Package | Install |
|---|---|---|
| Node.js | @github/copilot-sdk | npm install @github/copilot-sdk |
| Python | github-copilot-sdk | pip install github-copilot-sdk |
| Go | github.com/github/copilot-sdk/go | go get github.com/github/copilot-sdk/go |
| .NET | GitHub.Copilot.SDK | dotnet add package GitHub.Copilot.SDK |
The SDK communicates with the Copilot CLI via JSON-RPC over stdio (default) or TCP. The CLI manages model calls, tool execution, session state, and MCP server lifecycle.
Your App → SDK Client → [stdio/TCP] → Copilot CLI → Model Provider
↕
MCP ServersTransport modes:
| Mode | Description | Use Case |
|---|---|---|
| Stdio (default) | CLI as subprocess via pipes | Local dev, single process |
| TCP | CLI as network server | Multi-client, backend services |
All SDK usage follows: create a client, create a session, send messages.
import { CopilotClient } from "@github/copilot-sdk";
const client = new CopilotClient();
const session = await client.createSession({ model: "gpt-4.1" });
const response = await session.sendAndWait({ prompt: "What is 2 + 2?" });
console.log(response?.data.content);
await client.stop();import asyncio
from copilot import CopilotClient
async def main():
client = CopilotClient()
await client.start()
session = await client.create_session({"model": "gpt-4.1"})
response = await session.send_and_wait({"prompt": "What is 2 + 2?"})
print(response.data.content)
await client.stop()
asyncio.run(main())client := copilot.NewClient(nil)
if err := client.Start(ctx); err != nil { log.Fatal(err) }
defer client.Stop()
session, _ := client.CreateSession(ctx, &copilot.SessionConfig{Model: "gpt-4.1"})
response, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: "What is 2 + 2?"})
fmt.Println(*response.Data.Content)await using var client = new CopilotClient();
await using var session = await client.CreateSessionAsync(new SessionConfig { Model = "gpt-4.1" });
var response = await session.SendAndWaitAsync(new MessageOptions { Prompt = "What is 2 + 2?" });
Console.WriteLine(response?.Data.Content);Enable real-time output by setting streaming: true and subscribing to delta events.
const session = await client.createSession({ model: "gpt-4.1", streaming: true });
session.on("assistant.message_delta", (event) => {
process.stdout.write(event.data.deltaContent);
});
session.on("session.idle", () => console.log());
await session.sendAndWait({ prompt: "Tell me a joke" });from copilot.generated.session_events import SessionEventType
session = await client.create_session({"model": "gpt-4.1", "streaming": True})
def handle_event(event):
if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:
sys.stdout.write(event.data.delta_content)
sys.stdout.flush()
if event.type == SessionEventType.SESSION_IDLE:
print()
session.on(handle_event)
await session.send_and_wait({"prompt": "Tell me a joke"})| Method | Description |
|---|---|
on(handler) | Subscribe to all events; returns unsubscribe function |
on(eventType, handler) | Subscribe to specific event type (Node.js only) |
Call the returned function to unsubscribe. In .NET, call .Dispose() on the returned disposable.
Define tools that Copilot can call to extend its capabilities.
import { CopilotClient, defineTool } from "@github/copilot-sdk";
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 ({ city }) => ({ city, temperature: "72°F", condition: "sunny" }),
});
const session = await client.createSession({
model: "gpt-4.1",
tools: [getWeather],
});from copilot.tools import define_tool
from pydantic import BaseModel, Field
class GetWeatherParams(BaseModel):
city: str = Field(description="The city name")
@define_tool(description="Get the current weather for a city")
async def get_weather(params: GetWeatherParams) -> dict:
return {"city": params.city, "temperature": "72°F", "condition": "sunny"}
session = await client.create_session({"model": "gpt-4.1", "tools": [get_weather]})type WeatherParams struct {
City string `json:"city" jsonschema:"The city name"`
}
getWeather := copilot.DefineTool("get_weather", "Get weather for a city",
func(params WeatherParams, inv copilot.ToolInvocation) (WeatherResult, error) {
return WeatherResult{City: params.City, Temperature: "72°F"}, nil
},
)
session, _ := client.CreateSession(ctx, &copilot.SessionConfig{
Model: "gpt-4.1",
Tools: []copilot.Tool{getWeather},
})using Microsoft.Extensions.AI;
using System.ComponentModel;
var getWeather = AIFunctionFactory.Create(
([Description("The city name")] string city) => new { city, temperature = "72°F" },
"get_weather", "Get the current weather for a city");
await using var session = await client.CreateSessionAsync(new SessionConfig {
Model = "gpt-4.1", Tools = [getWeather],
});undefined)Intercept and customize session behavior at key lifecycle points.
| Hook | Trigger | Use Case |
|---|---|---|
onPreToolUse | Before tool executes | Permission control, argument modification |
onPostToolUse | After tool executes | Result transformation, logging, redaction |
onUserPromptSubmitted | User sends message | Prompt modification, filtering, context injection |
onSessionStart | Session begins (new or resumed) | Add context, configure session |
onSessionEnd | Session ends | Cleanup, analytics, metrics |
onErrorOccurred | Error happens | Custom error handling, retry logic, monitoring |
Control tool permissions, modify arguments, or inject context before tool execution.
const session = await client.createSession({
hooks: {
onPreToolUse: async (input) => {
if (["shell", "bash"].includes(input.toolName)) {
return { permissionDecision: "deny", permissionDecisionReason: "Shell access not permitted" };
}
return { permissionDecision: "allow" };
},
},
});Input fields: timestamp, cwd, toolName, toolArgs
Output fields:
| Field | Type | Description |
|---|---|---|
permissionDecision | "allow" | "deny" | "ask" | Whether to allow the tool call |
permissionDecisionReason | string | Explanation for deny/ask |
modifiedArgs | object | Modified arguments to pass |
additionalContext | string | Extra context for conversation |
suppressOutput | boolean | Hide tool output from conversation |
Transform results, redact sensitive data, or log tool activity after execution.
hooks: {
onPostToolUse: async (input) => {
// Redact sensitive data from results
if (typeof input.toolResult === "string") {
let redacted = input.toolResult;
for (const pattern of SENSITIVE_PATTERNS) {
redacted = redacted.replace(pattern, "[REDACTED]");
}
if (redacted !== input.toolResult) {
return { modifiedResult: redacted };
}
}
return null; // Pass through unchanged
},
}Output fields: modifiedResult, additionalContext, suppressOutput
Modify or enhance user prompts before processing. Useful for prompt templates, context injection, and input validation.
hooks: {
onUserPromptSubmitted: async (input) => {
return {
modifiedPrompt: `[User from engineering team] ${input.prompt}`,
additionalContext: "Follow company coding standards.",
};
},
}Output fields: modifiedPrompt, additionalContext, suppressOutput
hooks: {
onSessionStart: async (input, invocation) => {
// input.source: "startup" | "resume" | "new"
console.log(`Session ${invocation.sessionId} started (${input.source})`);
return { additionalContext: "Project uses TypeScript and React." };
},
onSessionEnd: async (input, invocation) => {
// input.reason: "complete" | "error" | "abort" | "timeout" | "user_exit"
await recordMetrics({ sessionId: invocation.sessionId, reason: input.reason });
return null;
},
}hooks: {
onErrorOccurred: async (input) => {
// input.errorContext: "model_call" | "tool_execution" | "system" | "user_input"
// input.recoverable: boolean
if (input.errorContext === "model_call" && input.error.includes("rate")) {
return { errorHandling: "retry", retryCount: 3, userNotification: "Rate limited. Retrying..." };
}
return null; // Default error handling
},
}Output fields: suppressOutput, errorHandling ("retry" | "skip" | "abort"), retryCount, userNotification
async def on_pre_tool_use(input_data, invocation):
if input_data["toolName"] in ["shell", "bash"]:
return {"permissionDecision": "deny", "permissionDecisionReason": "Not permitted"}
return {"permissionDecision": "allow"}
session = await client.create_session({
"hooks": {"on_pre_tool_use": on_pre_tool_use}
})session, _ := client.CreateSession(ctx, &copilot.SessionConfig{
Hooks: &copilot.SessionHooks{
OnPreToolUse: func(input copilot.PreToolUseHookInput, inv copilot.HookInvocation) (*copilot.PreToolUseHookOutput, error) {
return &copilot.PreToolUseHookOutput{PermissionDecision: "allow"}, nil
},
},
})Connect to MCP (Model Context Protocol) servers for pre-built tool capabilities.
const session = await client.createSession({
mcpServers: {
filesystem: {
type: "local",
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"],
tools: ["*"],
env: { DEBUG: "true" },
cwd: "./servers",
timeout: 30000,
},
},
});const session = await client.createSession({
mcpServers: {
github: {
type: "http",
url: "https://api.githubcopilot.com/mcp/",
headers: { Authorization: "Bearer ${TOKEN}" },
tools: ["*"],
},
},
});Local/Stdio:
| Field | Type | Required | Description |
|---|---|---|---|
type | "local" | No | Defaults to local |
command | string | Yes | Executable path |
args | string[] | Yes | Command arguments |
env | object | No | Environment variables |
cwd | string | No | Working directory |
tools | string[] | No | ["*"] for all, [] for none |
timeout | number | No | Timeout in milliseconds |
Remote HTTP:
| Field | Type | Required | Description |
|---|---|---|---|
type | "http" | Yes | Server type |
url | string | Yes | Server URL |
headers | object | No | HTTP headers |
tools | string[] | No | Tool filter |
timeout | number | No | Timeout in ms |
Test MCP servers independently before integrating:
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}' | /path/to/your/mcp-serverUse the MCP Inspector for interactive debugging:
npx @modelcontextprotocol/inspector /path/to/your/mcp-serverCommon MCP issues:
tools: ["*"] and verify server responds to tools/listcwdgithubToken in constructorCAPI_HMAC_KEY or COPILOT_HMAC_KEY env varsGITHUB_COPILOT_API_TOKEN with COPILOT_API_URLCOPILOT_GITHUB_TOKEN → GH_TOKEN → GITHUB_TOKENcopilot auth logingh auth credentialsconst client = new CopilotClient({ githubToken: process.env.GITHUB_TOKEN });For multi-user apps where users sign in with GitHub:
const client = new CopilotClient({
githubToken: userAccessToken, // gho_ or ghu_ token from OAuth flow
useLoggedInUser: false, // Don't use stored CLI credentials
});Supported token types: gho_ (OAuth), ghu_ (GitHub App), github_pat_ (fine-grained PAT).
Not supported: ghp_ (classic PAT — deprecated).
Prevent the SDK from using stored credentials:
const client = new CopilotClient({ useLoggedInUser: false });Use your own API keys — no Copilot subscription required. The CLI acts as agent runtime only.
OpenAI:
provider: { type: "openai", baseUrl: "https://api.openai.com/v1", apiKey: process.env.OPENAI_API_KEY }Azure AI Foundry (OpenAI-compatible):
provider: {
type: "openai",
baseUrl: "https://your-resource.openai.azure.com/openai/v1/",
apiKey: process.env.FOUNDRY_API_KEY,
wireApi: "responses", // Use "responses" for GPT-5 series, "completions" for others
}Azure OpenAI (native endpoint):
provider: {
type: "azure",
baseUrl: "https://my-resource.openai.azure.com", // Just the host — no /openai/v1
apiKey: process.env.AZURE_OPENAI_KEY,
azure: { apiVersion: "2024-10-21" },
}Anthropic:
provider: { type: "anthropic", baseUrl: "https://api.anthropic.com", apiKey: process.env.ANTHROPIC_API_KEY }Ollama (local):
provider: { type: "openai", baseUrl: "http://localhost:11434/v1" }| Field | Type | Description |
|---|---|---|
type | "openai" | "azure" | "anthropic" | Provider type |
baseUrl | string | Required. API endpoint URL |
apiKey | string | API key (optional for local providers) |
bearerToken | string | Bearer token auth (takes precedence over apiKey) |
wireApi | "completions" | "responses" | API format (default: "completions") |
azure.apiVersion | string | Azure API version (default: "2024-10-21") |
Use DefaultAzureCredential to get short-lived bearer tokens for Azure deployments:
from azure.identity import DefaultAzureCredential
from copilot import CopilotClient, ProviderConfig, SessionConfig
credential = DefaultAzureCredential()
token = credential.get_token("https://cognitiveservices.azure.com/.default").token
session = await client.create_session(SessionConfig(
model="gpt-4.1",
provider=ProviderConfig(
type="openai",
base_url=f"{foundry_url}/openai/v1/",
bearer_token=token,
wire_api="responses",
),
))Note: Bearer tokens expire (~1 hour). For long-running apps, refresh the token before each new session. The SDK does not auto-refresh tokens.
provider config on session resumeResume sessions across restarts by providing your own session ID.
// Create with explicit ID
const session = await client.createSession({
sessionId: "user-123-task-456",
model: "gpt-4.1",
});
// Resume later (even from a different client instance)
const resumed = await client.resumeSession("user-123-task-456");
await resumed.sendAndWait({ prompt: "What did we discuss?" });const sessions = await client.listSessions(); // List all
const lastId = await client.getLastSessionId(); // Get most recent
await client.deleteSession("user-123-task-456"); // Delete from storage
await session.destroy(); // Destroy active sessionWhen resuming, you can reconfigure: model, systemMessage, availableTools, excludedTools, provider (required for BYOK), reasoningEffort, streaming, mcpServers, customAgents, skillDirectories, infiniteSessions.
| Pattern | Example | Use Case |
|---|---|---|
user-{userId}-{taskId} | user-alice-pr-review-42 | Multi-user apps |
tenant-{tenantId}-{workflow} | tenant-acme-onboarding | Multi-tenant SaaS |
{userId}-{taskType}-{timestamp} | alice-deploy-1706932800 | Time-based cleanup |
Session state is saved to ~/.copilot/session-state/{sessionId}/:
| Data | Persisted? | Notes |
|---|---|---|
| Conversation history | ✅ Yes | Full message thread |
| Tool call results | ✅ Yes | Cached for context |
| Agent planning state | ✅ Yes | plan.md file |
| Session artifacts | ✅ Yes | In files/ directory |
| Provider/API keys | ❌ No | Must re-provide on resume |
| In-memory tool state | ❌ No | Design tools to be stateless |
For long-running workflows that may exceed context limits, enable auto-compaction:
const session = await client.createSession({
infiniteSessions: {
enabled: true,
backgroundCompactionThreshold: 0.80, // Start background compaction at 80%
bufferExhaustionThreshold: 0.95, // Block and compact at 95%
},
});Thresholds are context utilization ratios (0.0–1.0), not absolute token counts.
Define specialized AI personas:
const session = await client.createSession({
customAgents: [{
name: "pr-reviewer",
displayName: "PR Reviewer",
description: "Reviews pull requests for best practices",
prompt: "You are an expert code reviewer. Focus on security, performance, and maintainability.",
}],
});Control AI behavior and personality:
const session = await client.createSession({
systemMessage: { content: "You are a helpful assistant. Always be concise." },
});Load skill directories to extend Copilot's capabilities:
const session = await client.createSession({
skillDirectories: ["./skills/code-review", "./skills/documentation"],
disabledSkills: ["experimental-feature"],
});Skills can be combined with custom agents and MCP servers:
const session = await client.createSession({
skillDirectories: ["./skills/security"],
customAgents: [{ name: "auditor", prompt: "Focus on OWASP Top 10." }],
mcpServers: { postgres: { type: "local", command: "npx", args: ["-y", "@modelcontextprotocol/server-postgres"], tools: ["*"] } },
});Handle tool permissions and user input requests programmatically. The SDK uses a deny-by-default permission model — all permission requests are denied unless you provide a handler.
const session = await client.createSession({
onPermissionRequest: async (request) => {
if (request.kind === "shell") {
return { approved: request.command.startsWith("git") };
}
return { approved: true };
},
onUserInputRequest: async (request) => {
return { response: "yes" };
},
});Subscribe to usage events instead of using CLI /usage:
session.on("assistant.usage", (event) => {
console.log("Tokens:", { input: event.data.inputTokens, output: event.data.outputTokens });
});SDK auto-spawns CLI as subprocess. Simplest setup — zero configuration.
const client = new CopilotClient(); // Auto-manages CLI processRun CLI in headless mode, connect SDK over TCP:
copilot --headless --port 4321const client = new CopilotClient({ cliUrl: "localhost:4321" });Multi-client support: Multiple SDK clients can share one CLI server.
Ship CLI binary with your app:
const client = new CopilotClient({ cliPath: path.join(__dirname, "vendor", "copilot") });services:
copilot-cli:
image: ghcr.io/github/copilot-cli:latest
command: ["--headless", "--port", "4321"]
environment:
- COPILOT_GITHUB_TOKEN=${COPILOT_GITHUB_TOKEN}
volumes:
- session-data:/root/.copilot/session-state
api:
build: .
environment:
- CLI_URL=copilot-cli:4321
depends_on: [copilot-cli]
volumes:
session-data:| Pattern | Isolation | Resources | Best For |
|---|---|---|---|
| CLI per user | Complete | High | Multi-tenant SaaS, compliance |
| Shared CLI + session IDs | Logical | Low | Internal tools |
| Shared sessions | None | Low | Team collaboration (requires locking) |
~/.copilot/session-state/ for containers| Option | Type | Default | Description |
|---|---|---|---|
cliPath | string | Auto-detected | Path to Copilot CLI executable |
cliUrl | string | — | URL of external CLI server |
githubToken | string | — | GitHub token for auth |
useLoggedInUser | boolean | true | Use stored CLI credentials |
logLevel | string | "none" | "none" | "error" | "warning" | "info" | "debug" |
autoRestart | boolean | true | Auto-restart CLI on crash |
useStdio | boolean | true | Use stdio transport |
| Option | Type | Description |
|---|---|---|
model | string | Model to use (e.g., "gpt-4.1", "claude-sonnet-4") |
sessionId | string | Custom ID for resumable sessions |
streaming | boolean | Enable streaming responses |
tools | Tool[] | Custom tools |
mcpServers | object | MCP server configurations |
hooks | object | Session hooks |
provider | object | BYOK provider config |
customAgents | object[] | Custom agent definitions |
systemMessage | object | System message override |
skillDirectories | string[] | Directories to load skills from |
disabledSkills | string[] | Skills to disable |
reasoningEffort | string | Reasoning effort level |
availableTools | string[] | Restrict available tools |
excludedTools | string[] | Exclude specific tools |
infiniteSessions | object | Auto-compaction config |
workingDirectory | string | Working directory |
Session management, messaging (send/sendAndWait/abort), message history (getMessages), custom tools, tool permission hooks, MCP servers (local + HTTP), streaming, model selection, BYOK providers, custom agents, system message, skills, infinite sessions, permission handlers, 40+ event types.
Session export (--share), slash commands, interactive UI, terminal rendering, YOLO mode, login/logout flows, /compact (use infiniteSessions instead), /usage (use usage events), /review, /delegate.
Workarounds:
session.on() + session.getMessages()onPermissionRequest handler instead of --allow-all-pathsinfiniteSessions config instead of /compactEnable debug logging:
const client = new CopilotClient({ logLevel: "debug" });Custom log directory:
const client = new CopilotClient({ cliArgs: ["--log-dir", "/path/to/logs"] });| Issue | Cause | Solution |
|---|---|---|
CLI not found | CLI not installed or not in PATH | Install CLI or set cliPath |
Not authenticated | No valid credentials | Run copilot auth login or provide githubToken |
Session not found | Using session after destroy() | Check listSessions() for valid IDs |
Connection refused | CLI process crashed | Enable autoRestart: true, check port conflicts |
| MCP tools missing | Server init failure or tools not enabled | Set tools: ["*"], test server independently |
console.log("State:", client.getState()); // "connected" after start()
client.on("stateChange", (state) => console.log("Changed to:", state));| Language | Client | Session Create | Send | Resume | Stop |
|---|---|---|---|---|---|
| Node.js | new CopilotClient() | client.createSession() | session.sendAndWait() | client.resumeSession() | client.stop() |
| Python | CopilotClient() | client.create_session() | session.send_and_wait() | client.resume_session() | client.stop() |
| Go | copilot.NewClient(nil) | client.CreateSession() | session.SendAndWait() | client.ResumeSession() | client.Stop() |
| .NET | new CopilotClient() | client.CreateSessionAsync() | session.SendAndWaitAsync() | client.ResumeSessionAsync() | client.DisposeAsync() |
© microsoft, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file
Just SKILL.md in .github/skills/copilot-sdk of microsoft/skills.
Open the folder on GitHubat commit 354361d
Copilot SDK next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.
| Skill | Stars | Used in | Tokens | Auto-check | Licence | Repo updated |
|---|---|---|---|---|---|---|
| Copilot SDK this skillmicrosoft/skills | 3.1k | — | ~7.1k | Automated safety check: Pass | MIT | |
| Copilot SDKintellectronica/agent-skills | 295 | — | ~3.2k | Automated safety check: Pass | CC0-1.0 | |
| Copilot SDKaiskillstore/marketplace | 430 | 5 repos | ~3.8k | Automated safety check: Pass | None | |
| Copilot SDKgithub/awesome-copilot | 40k | 5 repos | ~6.3k | Automated safety check: Pass | MIT | |
| MCP Server Builderanthropics/skills | 180k | 62 repos | ~2.3k | Automated safety check: Pass | Apache-2.0 | |
| MCP Server BuildershareAI-lab/learn-claude-code | 78k | 5 repos | ~1.2k | Automated safety check: Pass | MIT |
intellectronica/agent-skills
This skill helps with GitHub Copilot SDK work across Node.js/TypeScript, Python, Go, .NET, and Java.
aiskillstore/marketplace
Build applications that programmatically interact with GitHub Copilot.
github/awesome-copilot
Build agentic applications with GitHub Copilot SDK. An agent skill from github/awesome-copilot.
anthropics/skills
Guides the design and implementation of Model Context Protocol servers in TypeScript or Python, from tool naming and error messages to evaluation.
shareAI-lab/learn-claude-code
Walks through building MCP servers in Python or TypeScript that expose tools, resources and prompts to Claude, with templates, registration and testing.
mcp-use/mcp-use
Builds, modifies, debugs, migrates and verifies TypeScript MCP servers and MCP Apps with the mcp-use framework, treating the installed package's types as the source of truth.
microsoft/skills
Reference for building on Microsoft Foundry with the azure-ai-projects Python SDK: project clients, versioned agents, evaluations, connections, datasets and indexes.
microsoft/skills
Python guidance for the Azure AI Search SDK covering vector, hybrid and semantic search, index management and indexers, with Entra ID authentication preferred over keys.
microsoft/skills
Covers producer, consumer, and checkpoint-store setup for Azure Event Hubs streaming in Python, with Entra ID auth and partition targeting.
microsoft/skills
Create Pydantic models following the multi-model pattern with Base, Create, Update, Response, and InDB variants.
microsoft/skills
Builds podcast-style audio narration from text with Azure OpenAI's GPT Realtime Mini over WebSocket, from a Python FastAPI backend to a React player.
microsoft/skills
Build dark-themed React applications using Tailwind CSS with custom theming, glassmorphism effects, and Framer Motion animations.
Categories
Build applications powered by GitHub Copilot using the Copilot SDK. Copilot SDK is an agent skill from microsoft/skills, published by the product's own GitHub organization. Build applications powered by GitHub Copilot using the Copilot SDK.
Copilot SDK fits situations like: creating programmatic integrations with Copilot across Node.js/TypeScript; tasks that involve Authentication; tasks that involve MCP servers.
Run `npx skills add microsoft/skills --skill copilot-sdk -a claude-code`. Or copy the skill folder (.github/skills/copilot-sdk in microsoft/skills) into .claude/skills/copilot-sdk in your project. Claude Code loads it when a task matches its description.
Run `npx skills add microsoft/skills --skill copilot-sdk -a codex`. Or copy the skill folder (.github/skills/copilot-sdk in microsoft/skills) into .agents/skills/copilot-sdk in your project. Codex loads it when a task matches its description.
Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add microsoft/skills --skill copilot-sdk -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/copilot-sdk, .gemini/skills/copilot-sdk, .github/skills/copilot-sdk and .opencode/skills/copilot-sdk in your project.
Going by SKILL.md and its folder, Copilot SDK needs the command-line tools its instructions call (npx, npm, pip, go, dotnet and gh) and credentials named COPILOT_GITHUB_TOKEN, GITHUB_TOKEN, CAPI_HMAC_KEY and COPILOT_HMAC_KEY. Our summary lists: Python 3; Node.js.
SKILL.md names 7 domains. In commands or code: api.githubcopilot.com, api.openai.com, api.anthropic.com and cognitiveservices.azure.com; the agent is likely to contact these when it follows the instructions. As links in the text: github.com, docs.github.com and modelcontextprotocol.io. This is read from the text; nothing was executed.
Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.
Copilot SDK is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.
About 7.1k tokens (SKILL.md is roughly 28k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.
Skills that share tags, products or a category with Copilot SDK: Copilot SDK (intellectronica/agent-skills, 295 stars), Copilot SDK (aiskillstore/marketplace, 430 stars), Copilot SDK (github/awesome-copilot, 40k stars) and MCP Server Builder (anthropics/skills, 180k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.
microsoft (a GitHub organization, an official publisher) maintains it in microsoft/skills, which has 3,086 GitHub stars. The repository holds 150 skills in this directory. The repository was last updated on October 6, 2026.
Source: microsoft/skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.