Microsoft Copilot SDK
## what it does
tl;dr: the procedure for building apps on top of GitHub Copilot. The SDK wraps the Copilot CLI via JSON-RPC, so this skill is mostly a one-shot lookup: which transport (stdio vs TCP), which session config (model + tools + hooks + mcpServers + provider + skillDirectories + customAgents), and how to keep the session resumable across restarts. The recurring trap is auth — by default the SDK uses whatever gh auth or copilot auth login left on disk; the moment you want programmatic or per-user tokens, you set useLoggedInUser: false and pass githubToken.
What it actually does
The SKILL.md (fetched 2026-09-10, part of microsoft/skills Core catalog of 11 skills) walks one core API across four runtimes. The shape is always the same — Client → Session → Message — but the language conventions differ:
| 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 |
Node.js minimum is 18+, Python 3.8+, Go 1.21+, .NET 8.0+. The CLI itself is a prerequisite on every host (copilot --version) — the SDK is a thin wrapper, not a replacement.
The seven surfaces the skill drills into:
- Sessions.
client.createSession({ model: "gpt-4.1" }),session.sendAndWait({ prompt }).sessionIdis required if you want to resume. The skill gives naming patterns:user-{userId}-{taskId}for multi-user apps,tenant-{tenantId}-{workflow}for SaaS,{userId}-{taskType}-{timestamp}for time-based cleanup. - Streaming. Set
streaming: true, subscribe toassistant.message_deltafor incremental output. 40+ event types, but the agent only needsassistant.message_delta+session.idleto print a streamed reply. - Custom tools.
defineTool("name", { description, parameters: <JSON Schema>, handler }). Python requires Pydantic for parameters. Go requires ajsonschema:"…"struct tag. Handler must return JSON-serializable data — returningundefinedornullfrom a tool is a silent failure. - Hooks. Six lifecycle points:
onPreToolUse(permission control, argument modification),onPostToolUse(redact output),onUserPromptSubmitted(template injection),onSessionStart/onSessionEnd(lifecycle),onErrorOccurred(retry/skip/abort). The default permission model is deny-by-default — every tool request is rejected until you provideonPermissionRequest. - MCP servers. Local stdio (
type: "local", command, args, env, cwd, tools, timeout) and remote HTTP (type: "http", url, headers, tools, timeout).tools: ["*"]is the typical enabling filter; the skill flags three debugging traps: missing tools (tools: ["*"]+ verifytools/listresponse), server won’t start (absolute paths + checkcwd), stdout pollution (debug output must go to stderr). - BYOK providers. Four shapes: OpenAI (
type: "openai", baseUrl: "https://api.openai.com/v1"), Azure AI Foundry (type: "openai"+wireApi: "responses"for GPT-5), Azure OpenAI native (type: "azure",baseUrlis just the host — no/openai/v1), Anthropic (type: "anthropic"), Ollama (type: "openai", baseUrl: "http://localhost:11434/v1"). Azure can useDefaultAzureCredentialfor short-lived bearer tokens, but the SDK does not auto-refresh them. - Session persistence. Conversation history, tool results, agent planning state, and session artifacts are saved to
~/.copilot/session-state/{sessionId}/. Provider/API keys are not persisted — re-passprovideron resume.infiniteSessions: { enabled: true, backgroundCompactionThreshold: 0.80, bufferExhaustionThreshold: 0.95 }is the auto-compaction knob for long runs.
Authentication priority (verbatim from the skill)
1. Explicit token — githubToken in constructor
2. HMAC key — CAPI_HMAC_KEY or COPILOT_HMAC_KEY env vars
3. Direct API token — GITHUB_COPILOT_API_TOKEN with COPILOT_API_URL
4. Environment variables — COPILOT_GITHUB_TOKEN → GH_TOKEN → GITHUB_TOKEN
5. Stored OAuth — From `copilot auth login`
6. GitHub CLI — `gh auth` credentials
For multi-user apps, the OAuth pattern is useLoggedInUser: false plus a per-user token. Supported token types: gho_, ghu_, github_pat_. Not supported: ghp_ (classic PAT, deprecated by GitHub).
When to load it
Frontmatter description lists these trigger phrases (paraphrased):
- “Build an app powered by Copilot SDK”
- “Programmatic Copilot integration”
- “Session management / custom tools / streaming / hooks / MCP / BYOK / persistence”
If the user wants the interactive CLI instead (copilot in a terminal with slash commands), this is the wrong skill — the SDK does not ship session export, /usage, /compact, /review, /delegate, or interactive UI. The skill explicitly enumerates those as “CLI-only features” with workarounds (e.g., compile your own usage view from assistant.usage events).
Install
The microsoft/skills README documents npx skills add microsoft/skills as the install path:
# wizard-style install — picks which of the 175 skills to drop into your agent directory
npx skills add microsoft/skills
Manual alternative (from the README’s “Alternative installation methods” section):
git clone https://github.com/microsoft/skills.git
cp -r skills/.github/skills/copilot-sdk your-project/.github/skills/
# multi-agent symlink pattern from the README
ln -s /path/to/skills/.github/skills/copilot-sdk /path/to/your-project/.github/skills/copilot-sdk
Important: the wizard installs to .github/skills/ for GitHub Copilot. Claude Code and Cursor do not auto-discover that path — copy or symlink the result into ~/.claude/skills/copilot-sdk or .claude/skills/copilot-sdk as your host expects.
Quick start (Node.js)
# 1. CLI prerequisite
copilot --version
copilot auth login # one-time; skip if using BYOK
# 2. SDK
npm install @github/copilot-sdk
import { CopilotClient } from "@github/copilot-sdk";
const client = new CopilotClient();
const session = await client.createSession({
model: "gpt-4.1",
streaming: true,
mcpServers: {
filesystem: { type: "local", command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "./data"], tools: ["*"] },
},
hooks: {
onPreToolUse: async (input) =>
input.toolName === "shell"
? { permissionDecision: "deny", permissionDecisionReason: "shell disabled" }
: { permissionDecision: "allow" },
},
});
session.on("assistant.message_delta", (e) => process.stdout.write(e.data.deltaContent));
session.on("session.idle", () => console.log());
await session.sendAndWait({ prompt: "List the files in ./data" });
await client.stop();
Gotchas
- CLI is a hard prerequisite.
copilot --versionmust succeed before the SDK runs. The README puts it under “Quick Start” and the SKILL.md puts it under “Prerequisites” — both treat it as non-negotiable. - Subscription OR BYOK, never neither. GitHub Copilot Individual / Business / Enterprise is the default path. BYOK (OpenAI / Azure / Anthropic / Ollama) is the escape hatch. There is no built-in path that uses a non-listed provider without writing a custom provider wrapper.
useLoggedInUser: falseis mandatory for OAuth-app flows. If you want to act as the user who clicked “Sign in with GitHub” rather than whoever rancopilot auth loginon the host, set this and pass their token.ghp_tokens are deprecated. The skill explicitly excludes them; usegithub_pat_orghu_(GitHub App installation tokens).- Tool handlers must return JSON-serializable data. Returning
undefinedfrom a Node.js handler breaks the JSON-RPC reply. Python tools return a dict; Go returns a struct withjson:tags; .NET returns anyJsonSerializer-friendly shape. - MCP stdout pollution breaks the protocol. Debug output from MCP servers must go to stderr. The skill flags this as the #1 cause of “server not starting” reports.
- Bearer tokens for Azure are not auto-refreshed.
DefaultAzureCredentialtokens expire (~1 hour). For long-running services, refresh the token before each new session. The SDK does not do this for you. - CLI-only features have no SDK equivalent. Session export,
/usage,/compact,/review,/delegate— collect events manually (session.on()+session.getMessages()) or useinfiniteSessions/onPermissionRequestinstead. Do not expectsession.sendAndWait()to honor slash commands. infiniteSessionsthresholds are ratios, not tokens.backgroundCompactionThreshold: 0.80means “compact when context is 80% full,” not “compact at 80k tokens.” Off-by-one on these is the usual misconfiguration.- Path-severity list matters for
mcpServers.commandis required,argsis required,cwdmust be writable,timeoutis in milliseconds (the default is short for HTTP servers — bump to 30000+ for cold starts). sandbox_test.verdict: untested— we readSKILL.mdand the upstream README, we did not runnpm install @github/copilot-sdkin the sandbox. Perconfig/skill-safety.md, that verdict does not change until a human runs the eval-vs-prompt harness.
Related: MCP Builder (Anthropic) — the Copilot SDK ships its own MCP server config schema; this is the deeper “how do I write an MCP server” skill. Vercel CLI with Tokens — same agent-CLI-with-env-auth pattern, just a different vendor. Verification Before Completion (obra/superpowers) — the agent-loop partner skill; run it after a session to confirm the integration actually works before declaring success.
## compatibility
## embed this badge
