本文へ移動
cccskills
無料GitHub で公開

copilot-sdk

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.

インストール方法を見る

含まれるファイル(1)

  • SKILL.md15.0 KB

SKILL.md(原文)

インストールする前に、エージェントに与えられる指示の中身を確認できます。

GitHub Copilot SDK

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.

Prerequisites

  • GitHub Copilot CLI installed and authenticated (copilot --version to verify)
  • GitHub Copilot subscription (Individual, Business, or Enterprise) — not required for BYOK
  • Runtime: Node.js 18+ / Python 3.8+ / Go 1.21+ / .NET 8.0+

Installation

LanguagePackageInstall
Node.js@github/copilot-sdknpm install @github/copilot-sdk
Pythongithub-copilot-sdkpip install github-copilot-sdk
Gogithub.com/github/copilot-sdk/gogo get github.com/github/copilot-sdk/go
.NETGitHub.Copilot.SDKdotnet add package GitHub.Copilot.SDK

Core Pattern: Client → Session → Message

All SDK usage follows this pattern: create a client, create a session, send messages.

Node.js / TypeScript

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();

Python

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())

Go

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)

.NET

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);

Streaming Responses

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" });

Python equivalent:

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()

session.on(handle_event)
await session.send_and_wait({"prompt": "Tell me a joke"})

Event Subscription

MethodDescription
on(handler)Subscribe to all events; returns unsubscribe function
on(eventType, handler)Subscribe to specific event type (Node.js only)

Custom Tools

Define tools that Copilot can call to extend its capabilities.

Node.js

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],
});

Python

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]})

Go

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},
})

.NET

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],
});

Hooks

Intercept and customize session behavior at key lifecycle points.

HookTriggerUse Case
onPreToolUseBefore tool executesPermission control, argument modification
onPostToolUseAfter tool executesResult transformation, logging
onUserPromptSubmittedUser sends messagePrompt modification, filtering
onSessionStartSession beginsAdd context, configure session
onSessionEndSession endsCleanup, analytics
onErrorOccurredError happensCustom error handling, retry logic

Example: Tool Permission Control

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" };
        },
    },
});

Pre-Tool Use Output

FieldTypeDescription
permissionDecision"allow" | "deny" | "ask"Whether to allow the tool call
permissionDecisionReasonstringExplanation for deny/ask
modifiedArgsobjectModified arguments to pass
additionalContextstringExtra context for conversation
suppressOutputbooleanHide tool output from conversation

MCP Server Integration

Connect to MCP servers for pre-built tool capabilities.

Remote HTTP Server

const session = await client.createSession({
    mcpServers: {
        github: { type: "http", url: "https://api.githubcopilot.com/mcp/" },
    },
});

Local Stdio Server

const session = await client.createSession({
    mcpServers: {
        filesystem: {
            type: "local",
            command: "npx",
            args: ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"],
            tools: ["*"],
        },
    },
});

MCP Config Fields

FieldTypeDescription
type"local" | "http"Server transport type
commandstringExecutable path (local)
argsstring[]Command arguments (local)
urlstringServer URL (http)
toolsstring[]["*"] or specific tool names
envobjectEnvironment variables
cwdstringWorking directory (local)
timeoutnumberTimeout in milliseconds

Authentication

Methods (Priority Order)

  1. Explicit token — githubToken in constructor
  2. Environment variables — COPILOT_GITHUB_TOKEN → GH_TOKEN → GITHUB_TOKEN
  3. Stored OAuth — From copilot auth login
  4. GitHub CLI — gh auth credentials

Programmatic Token

const client = new CopilotClient({ githubToken: process.env.GITHUB_TOKEN });

BYOK (Bring Your Own Key)

Use your own API keys — no Copilot subscription required.

const session = await client.createSession({
    model: "gpt-5.2-codex",
    provider: {
        type: "openai",
        baseUrl: "https://your-resource.openai.azure.com/openai/v1/",
        wireApi: "responses",
        apiKey: process.env.FOUNDRY_API_KEY,
    },
});
ProviderTypeNotes
OpenAI"openai"OpenAI API and compatible endpoints
Azure OpenAI"azure"Native Azure endpoints (don't include /openai/v1)
Azure AI Foundry"openai"OpenAI-compatible Foundry endpoints
Anthropic"anthropic"Claude models
Ollama"openai"Local models, no API key needed

Wire API: Use "responses" for GPT-5 series, "completions" (default) for others.


Session Persistence

Resume 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
const resumed = await client.resumeSession("user-123-task-456");
await resumed.sendAndWait({ prompt: "What did we discuss?" });

Session management:

const sessions = await client.listSessions();          // List all
await client.deleteSession("user-123-task-456");       // Delete
await session.destroy();                                // Destroy active

BYOK sessions: Must re-provide provider config on resume (keys are not persisted).

Infinite Sessions

For long-running workflows that may exceed context limits:

const session = await client.createSession({
    infiniteSessions: {
        enabled: true,
        backgroundCompactionThreshold: 0.80,
        bufferExhaustionThreshold: 0.95,
    },
});

Custom Agents

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.",
    }],
});

System Message

Control AI behavior and personality:

const session = await client.createSession({
    systemMessage: { content: "You are a helpful assistant. Always be concise." },
});

Skills Integration

Load skill directories to extend Copilot's capabilities:

const session = await client.createSession({
    skillDirectories: ["./skills/code-review", "./skills/documentation"],
    disabledSkills: ["experimental-feature"],
});

Permission & Input Handlers

Handle tool permissions and user input requests programmatically:

const session = await client.createSession({
    onPermissionRequest: async (request) => {
        // Auto-approve git commands only
        if (request.kind === "shell") {
            return { approved: request.command.startsWith("git") };
        }
        return { approved: true };
    },
    onUserInputRequest: async (request) => {
        // Handle ask_user tool calls
        return { response: "yes" };
    },
});

External CLI Server

Connect to a separately running CLI instead of auto-managing the process:

copilot --headless --port 4321
const client = new CopilotClient({ cliUrl: "localhost:4321" });

Client Configuration

OptionTypeDescription
cliPathstringPath to Copilot CLI executable
cliUrlstringURL of external CLI server
githubTokenstringGitHub token for auth
useLoggedInUserbooleanUse stored CLI credentials (default: true)
logLevelstring"none" | "error" | "warning" | "info" | "debug"
autoRestartbooleanAuto-restart CLI on crash (default: true)
useStdiobooleanUse stdio transport (default: true)

Session Configuration

OptionTypeDescription
modelstringModel to use (e.g., "gpt-4.1")
sessionIdstringCustom ID for resumable sessions
streamingbooleanEnable streaming responses
toolsTool[]Custom tools
mcpServersobjectMCP server configurations
hooksobjectSession hooks
providerobjectBYOK provider config
customAgentsobject[]Custom agent definitions
systemMessageobjectSystem message override
skillDirectoriesstring[]Directories to load skills from
disabledSkillsstring[]Skills to disable
reasoningEffortstringReasoning effort level
availableToolsstring[]Restrict available tools
excludedToolsstring[]Exclude specific tools
infiniteSessionsobjectAuto-compaction config
workingDirectorystringWorking directory

Debugging

Enable debug logging to troubleshoot issues:

const client = new CopilotClient({ logLevel: "debug" });

Common issues:

  • CLI not found → Install CLI or set cliPath
  • Not authenticated → Run copilot auth login or provide githubToken
  • Session not found → Don't use session after destroy()
  • Connection refused → Check CLI process, enable autoRestart

Key API Summary

LanguageClientSession CreateSendStop
Node.jsnew CopilotClient()client.createSession()session.sendAndWait()client.stop()
PythonCopilotClient()client.create_session()session.send_and_wait()client.stop()
Gocopilot.NewClient(nil)client.CreateSession()session.SendAndWait()client.Stop()
.NETnew CopilotClient()client.CreateSessionAsync()session.SendAndWaitAsync()client.DisposeAsync()

References

When to Use

This skill is applicable to execute the workflow or actions described in the overview.

Limitations

  • Use this skill only when the task clearly matches the scope described above.
  • Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
  • Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.

レビュー

まだレビューはありません。使ってみた感想をお寄せください。

同じリポジトリのスキル

概要と使いどころ

Use this skill whenever the user wants to create or improve a presentation for an academic context — conference papers, seminar talks, thesis defenses, grant briefings, lab meetings, invited lectures, or any presentation where the audience will evaluate reasoning and evidence. Triggers include: 'conference talk', 'seminar slides', 'thesis defense', 'research presentation', 'academic deck', 'academic presentation'. Also triggers when the user asks to 'make slides' in combination with academic content (e.g., 'make slides for my paper on X', 'create a presentation for my dissertation defense', 'build a deck for my grant proposal'). This skill governs CONTENT and STRUCTURE decisions. For the technical work of creating or editing the .pptx file itself, also read the pptx SKILL.md.

日本語の概要は準備中です。原文の説明を表示しています。

skillmds/skillmd712026年10月9日 更新

adp

無料

Redpanda's Agentic Data Plane: governance infrastructure for building, running, and governing AI agents and MCP servers, plus a proxying AI Gateway for LLM providers, operated via `rpk ai` and the ADP API. Use when creating or managing AI agents (managed or self-managed) via `rpk ai agent` or `AgentRegistryService`; configuring MCP servers (remote or managed catalog, code mode, auth); setting up LLM providers or querying models via `rpk ai llm`/`rpk ai model` or the AI Gateway proxy; or configuring budgets, guardrails, or Cedar access-control policies through the governance APIs. Also covers reading agent transcripts and spending insights, and wiring OAuth clients or providers to the aigw Authorization Server. For the separate rpk cloud mcp control-plane MCP server, see `/redpanda:rpk-cloud`.

日本語の概要は準備中です。原文の説明を表示しています。

skillmds/skillmd712026年10月9日 更新

ads

無料

Operate professional paid advertising across Google, Meta, YouTube, LinkedIn, TikTok, Microsoft, Apple, Amazon, Reddit, Pinterest, Snapchat, and X. Use for account intake, source-grounded audits, strategy, budget and measurement planning, creative production, experiments, reporting, monitoring, and explicitly approved campaign changes. Also trigger on PPC, paid social, retail media, attribution, tracking, landing pages, cross-platform conversion totals, negative keywords or search terms, beta-feature scoring, stale platform claims, API-token or credential setup, campaign deletion, and safe Claude Ads installation or uninstall.

日本語の概要は準備中です。原文の説明を表示しています。

skillmds/skillmd712026年10月9日 更新

ads-apple

無料

Audit Apple Ads measurement, AdServices and AdAttributionKit, campaign and keyword structure, Search Match, App Store placements, custom product pages, bidding, budgets, MMP reconciliation, and policy. Use for Apple Ads, Apple Search Ads, App Store ads, Search Match, custom product pages, AdServices, or Apple app-install campaigns.

日本語の概要は準備中です。原文の説明を表示しています。

skillmds/skillmd712026年10月9日 更新

Research competitor paid-ad presence, messaging, creative, formats, landing pages, keyword and auction signals, transparent ad libraries, and strategic gaps across supported platforms. Use for competitor ads, ad libraries, ad spy, competitive PPC analysis, competitor creative, Google Ads Transparency, Meta Ad Library, or paid-media competitor research.

日本語の概要は準備中です。原文の説明を表示しています。

skillmds/skillmd712026年10月9日 更新

ads-dna

無料

Extract a public-safe brand and offer profile for paid advertising from an authorized website and operator input. Triggers on: brand DNA, brand profile, brand identity, brand style, brand colors, brand voice, visual identity, style guide, website brand analysis.

日本語の概要は準備中です。原文の説明を表示しています。

skillmds/skillmd712026年10月9日 更新

skillmds のスキルをすべて見る

このスキルの問題を報告する