Loading...
Loading...
This skill should be used when the user asks to "integrate GitHub Copilot into an app", "use the Copilot SDK", "build a Copilot-powered agent", "embed Copilot in a service", or needs guidance on the GitHub Copilot SDK for Python, TypeScript, Go, or .NET.
npx skill4agent add the-perfect-developer/the-perfect-opencode copilot-sdkStatus: Technical Preview — breaking changes possible between releases.
Your Application
|
SDK Client (manages CLI process lifecycle + JSON-RPC transport)
|
Copilot CLI (server mode — planning, tool invocation, file edits)# Follow: https://docs.github.com/en/copilot/how-tos/set-up/install-copilot-cli
copilot --version # verifyreferences/authentication.md| Language | Package | Install |
|---|---|---|
| Node.js / TypeScript | | |
| Python | | |
| Go | | |
| .NET | | |
CopilotClientclient.start()client.createSession(config)client.stop()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();
process.exit(0);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())createSessioncreate_sessionSessionConfig| Option | Type | Description |
|---|---|---|
| string | Model ID — required with BYOK. E.g. |
| bool | Emit |
| Tool[] | Custom tools the agent can invoke |
| object | Inject or replace the system prompt |
| object | Context compaction config (enabled by default) |
| object | BYOK — custom LLM provider config |
| object | Lifecycle hook handlers |
| callable | Enable |
| string | Deterministic / resumable session ID |
// Fire-and-forget (returns message ID)
await session.send({ prompt: "Generate a README" });
// Send and await idle state (returns final AssistantMessageEvent)
const result = await session.sendAndWait({ prompt: "Explain this code" });# Python equivalent
await session.send({"prompt": "Generate a README"})
result = await session.send_and_wait({"prompt": "Explain this code"})streaming: trueconst 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("\nDone."));
await session.sendAndWait({ prompt: "Write a haiku about testing" });| Event | Fires when |
|---|---|
| User message enqueued |
| Final full response available |
| Streaming chunk (requires |
| Chain-of-thought chunk (model-dependent) |
| Agent begins a tool call |
| Tool call finished |
| Processing complete, session ready |
| Infinite session compaction started |
| Compaction finished |
session.on()import { defineTool, CopilotClient } from "@github/copilot-sdk";
import { z } from "zod";
const lookupIssue = defineTool("lookup_issue", {
description: "Fetch issue details from the tracker",
parameters: z.object({
id: z.string().describe("Issue identifier"),
}),
handler: async ({ id }) => {
return await fetchIssue(id); // any JSON-serializable value
},
});
const session = await client.createSession({
model: "gpt-4.1",
tools: [lookupIssue],
});from pydantic import BaseModel, Field
from copilot import define_tool
class LookupIssueParams(BaseModel):
id: str = Field(description="Issue identifier")
@define_tool(description="Fetch issue details from the tracker")
async def lookup_issue(params: LookupIssueParams) -> str:
return await fetch_issue(params.id)
session = await client.create_session({
"model": "gpt-4.1",
"tools": [lookup_issue],
})const session = await client.createSession({
model: "gpt-4.1",
systemMessage: {
content: `
<workflow_rules>
- Always check for security vulnerabilities
- Suggest performance improvements when applicable
</workflow_rules>`,
},
});mode: "replace"systemMessage: { mode: "replace", content: "You are a terse code reviewer." }~/.copilot/session-state/{sessionId}/// Custom thresholds
const session = await client.createSession({
model: "gpt-4.1",
infiniteSessions: {
enabled: true,
backgroundCompactionThreshold: 0.80, // compact at 80% usage
bufferExhaustionThreshold: 0.95, // block at 95% until done
},
});
// Disable (fixed context window)
const session = await client.createSession({
model: "gpt-4.1",
infiniteSessions: { enabled: false },
});const session = await client.resumeSession("my-session-id");await session.send({
prompt: "Review this module",
attachments: [{ type: "file", path: "/src/auth.ts", displayName: "auth.ts" }],
});viewconst session = await client.createSession({
model: "gpt-4.1",
mcpServers: {
github: {
type: "http",
url: "https://api.githubcopilot.com/mcp/",
},
},
});copilot --headless --port 4321const client = new CopilotClient({ cliUrl: "localhost:4321" });cliUrlstop()try {
const session = await client.createSession({ model: "gpt-4.1" });
await session.sendAndWait({ prompt: "Fix the bug" });
} catch (error) {
console.error("SDK error:", error.message);
} finally {
const errors = await client.stop();
if (errors.length) console.error("Cleanup errors:", errors);
}client.forceStop()// List sessions (optionally filter by working directory)
const sessions = await client.listSessions();
// Delete a session
await client.deleteSession("session-id");
// Get all messages from a session
const messages = await session.getMessages();
// Abort current processing
await session.abort();
// Destroy session and free resources
await session.destroy();const session1 = await client.createSession({ model: "gpt-4.1" });
const session2 = await client.createSession({ model: "claude-sonnet-4.5" });
await Promise.all([
session1.sendAndWait({ prompt: "Draft a PR description" }),
session2.sendAndWait({ prompt: "Review the security implications" }),
]);CopilotClient options: cliPath, cliUrl, port, useStdio, logLevel,
autoStart, autoRestart, githubToken, useLoggedInUser
SessionConfig: model, streaming, tools, systemMessage,
infiniteSessions, provider, hooks,
onUserInputRequest, sessionId
session.send() → Promise<string> (message ID)
session.sendAndWait() → Promise<AssistantMessageEvent | undefined>
session.on() → () => void (unsubscribe fn)
session.abort() → Promise<void>
session.destroy() → Promise<void>
session.getMessages() → Promise<SessionEvent[]>references/authentication.mdreferences/tools-and-hooks.mdonPreToolUseonPostToolUseonUserPromptSubmittedonSessionStartonSessionEndonErrorOccurred