Token导航 LogoToken导航

Agent Skill · 开发

copilot-sdk(GitHub Copilot SDK 测试)

copilot-sdk 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

copilot-sdk 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为执行命令;许可证信息还不明确,第三方扫描有提醒项,按安装量在开发类的 21,746 个 Skill 里排第 16,443。

总安装 499周安装 20GitHub Stars 2,185下载 162核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:copilot-sdk(GitHub Copilot SDK 测试)
来源仓库:https://github.com/microsoft/skills
仓库路径:skills/copilot-sdk
安装命令:
npx skills add https://github.com/microsoft/skills --skill copilot-sdk
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/microsoft/skills --skill copilot-sdk

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

用于处理 GitHub 仓库、Issue 和 Pull Request 协作信息。适合围绕代码变更和项目状态进行整理与分析。可辅助生成协作事项的可执行下一步。copilot-sdk 属于开发类 Skill,可作为该场景下的辅助能力补充。涉及写入操作时需确认 token 权限和仓库授权范围。

安装方式:通过 GitHub 仓库使用 npx 命令添加技能。

来源仓库内路径:skills/copilot-sdk

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/microsoft/skills --skill copilot-sdk;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要执行命令,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

copilot-sdk 怎么安装?

在终端执行 npx skills add https://github.com/microsoft/skills --skill copilot-sdk。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

copilot-sdk 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

copilot-sdk 需要什么权限?

权限级别是执行命令。安装流程涉及命令执行,可能通过 npx skills add https://github.com/microsoft/skills --skill copilot-sdk 联网下载 Skill 或依赖。用户安装前应确认命令来源、仓库内容和执行环境。

copilot-sdk 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

copilot-sdk 用的人多吗?

公开数据是累计安装 499 次,近一周安装 20 次,下载 162 次,GitHub 2,185 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

copilot-sdk 安全吗?

第三方扫描有提醒项,说明存在需要人工确认的行为。安装前请打开源码看清它读了什么、联网到哪里。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 来源仓库有 2,185 星,维护活跃度相对可查。

先想清楚的地方

  • 需要执行命令,装到常用环境前要先评估影响面。
  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方扫描存在提醒项或未通过项,需要人工逐条确认。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。

不太适合

  • 不能接受 Skill 在你机器上执行命令的人。
  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
copilot-sdk

GitHub Copilot SDK 测试 · 本页

4992,185执行命令未明确有提醒

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

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

Architecture

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 Servers

Transport modes:

ModeDescriptionUse Case
Stdio (default)CLI as subprocess via pipesLocal dev, single process
TCPCLI as network serverMulti-client, backend services

Core Pattern: Client → Session → Message

All SDK usage follows: 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.

Node.js

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

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

Event Subscription

MethodDescription
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.


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

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

Tool Requirements

  • Handler must return JSON-serializable data (not undefined)
  • Parameters must follow JSON Schema format
  • Tool description should clearly state when the tool should be used

Hooks

Intercept and customize session behavior at key lifecycle points.

HookTriggerUse Case
onPreToolUseBefore tool executesPermission control, argument modification
onPostToolUseAfter tool executesResult transformation, logging, redaction
onUserPromptSubmittedUser sends messagePrompt modification, filtering, context injection
onSessionStartSession begins (new or resumed)Add context, configure session
onSessionEndSession endsCleanup, analytics, metrics
onErrorOccurredError happensCustom error handling, retry logic, monitoring

Pre-Tool Use Hook

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:

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

Post-Tool Use Hook

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

User Prompt Submitted Hook

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

Session Lifecycle Hooks

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

Error Handling Hook

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

Python Hook Example

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

Go Hook Example

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

MCP Server Integration

Connect to MCP (Model Context Protocol) servers for pre-built tool capabilities.

Local Stdio Server

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

Remote HTTP Server

const session = await client.createSession({
    mcpServers: {
        github: {
            type: "http",
            url: "https://api.githubcopilot.com/mcp/",
            headers: { Authorization: "Bearer ${TOKEN}" },
            tools: ["*"],
        },
    },
});

MCP Config Fields

Local/Stdio:

FieldTypeRequiredDescription
type"local"NoDefaults to local
commandstringYesExecutable path
argsstring[]YesCommand arguments
envobjectNoEnvironment variables
cwdstringNoWorking directory
toolsstring[]No["*"] for all, [] for none
timeoutnumberNoTimeout in milliseconds

Remote HTTP:

FieldTypeRequiredDescription
type"http"YesServer type
urlstringYesServer URL
headersobjectNoHTTP headers
toolsstring[]NoTool filter
timeoutnumberNoTimeout in ms

MCP Debugging

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-server

Use the MCP Inspector for interactive debugging:

npx @modelcontextprotocol/inspector /path/to/your/mcp-server

Common MCP issues:

  • Tools not appearing → Set tools: ["*"] and verify server responds to tools/list
  • Server not starting → Use absolute command paths, check cwd
  • Stdout pollution → Debug output must go to stderr, not stdout

Authentication

Methods (Priority Order)

  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

Programmatic Token

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

OAuth GitHub App

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

Disable Auto-Login

Prevent the SDK from using stored credentials:

const client = new CopilotClient({ useLoggedInUser: false });

BYOK (Bring Your Own Key)

Use your own API keys — no Copilot subscription required. The CLI acts as agent runtime only.

Provider Configurations

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

Provider Config Reference

FieldTypeDescription
type"openai" \"azure" \"anthropic"Provider type
baseUrlstringRequired. API endpoint URL
apiKeystringAPI key (optional for local providers)
bearerTokenstringBearer token auth (takes precedence over apiKey)
wireApi"completions" \"responses"API format (default: "completions")
azure.apiVersionstringAzure API version (default: "2024-10-21")

Azure Managed Identity with BYOK

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.

BYOK Limitations

  • Static credentials only — no native Entra ID, OIDC, or managed identity support
  • No auto-refresh — expired tokens require creating a new session
  • Keys not persisted — must re-provide provider config on session resume
  • Model availability — limited to what your provider offers

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 (even from a different client instance)
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
const lastId = await client.getLastSessionId();          // Get most recent
await client.deleteSession("user-123-task-456");         // Delete from storage
await session.destroy();                                 // Destroy active session

Resume Options

When resuming, you can reconfigure: model, systemMessage, availableTools, excludedTools, provider (required for BYOK), reasoningEffort, streaming, mcpServers, customAgents, skillDirectories, infiniteSessions.

Session ID Best Practices

PatternExampleUse Case
user-{userId}-{taskId}user-alice-pr-review-42Multi-user apps
tenant-{tenantId}-{workflow}tenant-acme-onboardingMulti-tenant SaaS
{userId}-{taskType}-{timestamp}alice-deploy-1706932800Time-based cleanup

What Gets Persisted

Session state is saved to ~/.copilot/session-state/{sessionId}/:

DataPersisted?Notes
Conversation history✅ YesFull message thread
Tool call results✅ YesCached for context
Agent planning state✅ Yesplan.md file
Session artifacts✅ YesIn files/ directory
Provider/API keys❌ NoMust re-provide on resume
In-memory tool state❌ NoDesign tools to be stateless

Infinite Sessions

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.

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

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: ["*"] } },
});

Permission & Input Handlers

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

Token Usage Tracking

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

Deployment Patterns

Local CLI (Default)

SDK auto-spawns CLI as subprocess. Simplest setup — zero configuration.

const client = new CopilotClient(); // Auto-manages CLI process

External CLI Server (Backend Services)

Run CLI in headless mode, connect SDK over TCP:

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

Multi-client support: Multiple SDK clients can share one CLI server.

Bundled CLI (Desktop Apps)

Ship CLI binary with your app:

const client = new CopilotClient({ cliPath: path.join(__dirname, "vendor", "copilot") });

Docker Compose

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:

Session Isolation Patterns

PatternIsolationResourcesBest For
CLI per userCompleteHighMulti-tenant SaaS, compliance
Shared CLI + session IDsLogicalLowInternal tools
Shared sessionsNoneLowTeam collaboration (requires locking)

Production Checklist

  • Session cleanup: periodic deletion of expired sessions
  • Health checks: ping CLI server, restart if unresponsive
  • Persistent storage: mount ~/.copilot/session-state/ for containers
  • Secret management: use Vault/K8s Secrets for tokens
  • Session locking: Redis or similar for shared session access
  • Graceful shutdown: drain active sessions before stopping CLI

Client Configuration

OptionTypeDefaultDescription
cliPathstringAuto-detectedPath to Copilot CLI executable
cliUrlstring—URL of external CLI server
githubTokenstring—GitHub token for auth
useLoggedInUserbooleantrueUse stored CLI credentials
logLevelstring"none""none" \"error" \"warning" \"info" \"debug"
autoRestartbooleantrueAuto-restart CLI on crash
useStdiobooleantrueUse stdio transport

Session Configuration

OptionTypeDescription
modelstringModel to use (e.g., "gpt-4.1", "claude-sonnet-4")
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

SDK vs CLI Feature Comparison

✅ Available in SDK

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.

❌ CLI-Only Features

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 export → Collect events manually with session.on() + session.getMessages()
  • Permission control → Use onPermissionRequest handler instead of --allow-all-paths
  • Context compaction → Use infiniteSessions config instead of /compact

Debugging

Enable debug logging:

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

Custom log directory:

const client = new CopilotClient({ cliArgs: ["--log-dir", "/path/to/logs"] });

Common Issues

IssueCauseSolution
CLI not foundCLI not installed or not in PATHInstall CLI or set cliPath
Not authenticatedNo valid credentialsRun copilot auth login or provide githubToken
Session not foundUsing session after destroy()Check listSessions() for valid IDs
Connection refusedCLI process crashedEnable autoRestart: true, check port conflicts
MCP tools missingServer init failure or tools not enabledSet tools: ["*"], test server independently

Connection State

console.log("State:", client.getState());  // "connected" after start()
client.on("stateChange", (state) => console.log("Changed to:", state));

Key API Summary

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

References

平台分布

Codex

33.85%
按下载量换算55

Claude

29.29%
按下载量换算47

Cursor

18.14%
按下载量换算29

Gemini CLI

9.41%
按下载量换算15

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

可疑

权限和风险

执行命令

安装流程涉及命令执行,可能通过 npx skills add https://github.com/microsoft/skills --skill copilot-sdk 联网下载 Skill 或依赖。用户安装前应确认命令来源、仓库内容和执行环境。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在提醒或未通过项,安装前请自行复核。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills