copilot-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGitHub Copilot SDK
GitHub Copilot SDK
Embed Copilot's agentic workflows in any application using Python, TypeScript, Go, or .NET.
使用Python、TypeScript、Go或.NET在任意应用中嵌入Copilot的智能代理工作流。
Overview
概述
The GitHub Copilot SDK exposes the same engine behind Copilot CLI: a production-tested agent runtime you can invoke programmatically. No need to build your own orchestration - you define agent behavior, Copilot handles planning, tool invocation, file edits, and more.
GitHub Copilot SDK 暴露了Copilot CLI背后的同款引擎:一个经过生产环境验证的代理运行时,你可以通过编程方式调用它。无需自行构建编排逻辑——你只需定义Agent的行为,Copilot会处理规划、工具调用、文件编辑等工作。
Prerequisites
前置条件
- GitHub Copilot CLI installed and authenticated (Installation guide)
- Language runtime: Node.js 18+, Python 3.8+, Go 1.21+, or .NET 8.0+
Verify CLI:
copilot --version- 已安装并验证GitHub Copilot CLI(安装指南)
- 语言运行时:Node.js 18+、Python 3.8+、Go 1.21+ 或 .NET 8.0+
验证CLI:
copilot --versionInstallation
安装
Node.js/TypeScript
Node.js/TypeScript
bash
mkdir copilot-demo && cd copilot-demo
npm init -y --init-type module
npm install @github/copilot-sdk tsxbash
mkdir copilot-demo && cd copilot-demo
npm init -y --init-type module
npm install @github/copilot-sdk tsxPython
Python
bash
pip install github-copilot-sdkbash
pip install github-copilot-sdkGo
Go
bash
mkdir copilot-demo && cd copilot-demo
go mod init copilot-demo
go get github.com/github/copilot-sdk/gobash
mkdir copilot-demo && cd copilot-demo
go mod init copilot-demo
go get github.com/github/copilot-sdk/go.NET
.NET
bash
dotnet new console -n CopilotDemo && cd CopilotDemo
dotnet add package GitHub.Copilot.SDKbash
dotnet new console -n CopilotDemo && cd CopilotDemo
dotnet add package GitHub.Copilot.SDKQuick Start
快速开始
TypeScript
TypeScript
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();
process.exit(0);Run:
npx tsx index.tstypescript
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);运行:
npx tsx index.tsPython
Python
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())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
Go
go
package main
import (
"fmt"
"log"
"os"
copilot "github.com/github/copilot-sdk/go"
)
func main() {
client := copilot.NewClient(nil)
if err := client.Start(); err != nil {
log.Fatal(err)
}
defer client.Stop()
session, err := client.CreateSession(&copilot.SessionConfig{Model: "gpt-4.1"})
if err != nil {
log.Fatal(err)
}
response, err := session.SendAndWait(copilot.MessageOptions{Prompt: "What is 2 + 2?"}, 0)
if err != nil {
log.Fatal(err)
}
fmt.Println(*response.Data.Content)
os.Exit(0)
}go
package main
import (
"fmt"
"log"
"os"
copilot "github.com/github/copilot-sdk/go"
)
func main() {
client := copilot.NewClient(nil)
if err := client.Start(); err != nil {
log.Fatal(err)
}
defer client.Stop()
session, err := client.CreateSession(&copilot.SessionConfig{Model: "gpt-4.1"})
if err != nil {
log.Fatal(err)
}
response, err := session.SendAndWait(copilot.MessageOptions{Prompt: "What is 2 + 2?"}, 0)
if err != nil {
log.Fatal(err)
}
fmt.Println(*response.Data.Content)
os.Exit(0)
}.NET (C#)
.NET (C#)
csharp
using GitHub.Copilot.SDK;
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);Run:
dotnet runcsharp
using GitHub.Copilot.SDK;
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);运行:
dotnet runStreaming Responses
流式响应
Enable real-time output for better UX:
启用实时输出以提升用户体验:
TypeScript
TypeScript
typescript
import { CopilotClient, SessionEvent } from "@github/copilot-sdk";
const client = new CopilotClient();
const session = await client.createSession({
model: "gpt-4.1",
streaming: true,
});
session.on((event: SessionEvent) => {
if (event.type === "assistant.message_delta") {
process.stdout.write(event.data.deltaContent);
}
if (event.type === "session.idle") {
console.log(); // New line when done
}
});
await session.sendAndWait({ prompt: "Tell me a short joke" });
await client.stop();
process.exit(0);typescript
import { CopilotClient, SessionEvent } from "@github/copilot-sdk";
const client = new CopilotClient();
const session = await client.createSession({
model: "gpt-4.1",
streaming: true,
});
session.on((event: SessionEvent) => {
if (event.type === "assistant.message_delta") {
process.stdout.write(event.data.deltaContent);
}
if (event.type === "session.idle") {
console.log(); // 完成时换行
}
});
await session.sendAndWait({ prompt: "Tell me a short joke" });
await client.stop();
process.exit(0);Python
Python
python
import asyncio
import sys
from copilot import CopilotClient
from copilot.generated.session_events import SessionEventType
async def main():
client = CopilotClient()
await client.start()
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 short joke"})
await client.stop()
asyncio.run(main())python
import asyncio
import sys
from copilot import CopilotClient
from copilot.generated.session_events import SessionEventType
async def main():
client = CopilotClient()
await client.start()
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 short joke"})
await client.stop()
asyncio.run(main())Go
Go
go
session, err := client.CreateSession(&copilot.SessionConfig{
Model: "gpt-4.1",
Streaming: true,
})
session.On(func(event copilot.SessionEvent) {
if event.Type == "assistant.message_delta" {
fmt.Print(*event.Data.DeltaContent)
}
if event.Type == "session.idle" {
fmt.Println()
}
})
_, err = session.SendAndWait(copilot.MessageOptions{Prompt: "Tell me a short joke"}, 0)go
session, err := client.CreateSession(&copilot.SessionConfig{
Model: "gpt-4.1",
Streaming: true,
})
session.On(func(event copilot.SessionEvent) {
if event.Type == "assistant.message_delta" {
fmt.Print(*event.Data.DeltaContent)
}
if event.Type == "session.idle" {
fmt.Println()
}
})
_, err = session.SendAndWait(copilot.MessageOptions{Prompt: "Tell me a short joke"}, 0).NET
.NET
csharp
await using var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "gpt-4.1",
Streaming = true,
});
session.On(ev =>
{
if (ev is AssistantMessageDeltaEvent deltaEvent)
Console.Write(deltaEvent.Data.DeltaContent);
if (ev is SessionIdleEvent)
Console.WriteLine();
});
await session.SendAndWaitAsync(new MessageOptions { Prompt = "Tell me a short joke" });csharp
await using var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "gpt-4.1",
Streaming = true,
});
session.On(ev =>
{
if (ev is AssistantMessageDeltaEvent deltaEvent)
Console.Write(deltaEvent.Data.DeltaContent);
if (ev is SessionIdleEvent)
Console.WriteLine();
});
await session.SendAndWaitAsync(new MessageOptions { Prompt = "Tell me a short joke" });Custom Tools
自定义工具
Define tools that Copilot can invoke during reasoning. When you define a tool, you tell Copilot:
- What the tool does (description)
- What parameters it needs (schema)
- What code to run (handler)
定义Copilot可以在推理过程中调用的工具。定义工具时,你需要告知Copilot:
- 工具的功能(描述)
- 所需的参数(Schema)
- 执行的代码(处理函数)
TypeScript (JSON Schema)
TypeScript (JSON Schema)
typescript
import { CopilotClient, defineTool, SessionEvent } 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 (args: { city: string }) => {
const { city } = args;
// In a real app, call a weather API here
const conditions = ["sunny", "cloudy", "rainy", "partly cloudy"];
const temp = Math.floor(Math.random() * 30) + 50;
const condition = conditions[Math.floor(Math.random() * conditions.length)];
return { city, temperature: `${temp}°F`, condition };
},
});
const client = new CopilotClient();
const session = await client.createSession({
model: "gpt-4.1",
streaming: true,
tools: [getWeather],
});
session.on((event: SessionEvent) => {
if (event.type === "assistant.message_delta") {
process.stdout.write(event.data.deltaContent);
}
});
await session.sendAndWait({
prompt: "What's the weather like in Seattle and Tokyo?",
});
await client.stop();
process.exit(0);typescript
import { CopilotClient, defineTool, SessionEvent } 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 (args: { city: string }) => {
const { city } = args;
// 在实际应用中,这里调用天气API
const conditions = ["sunny", "cloudy", "rainy", "partly cloudy"];
const temp = Math.floor(Math.random() * 30) + 50;
const condition = conditions[Math.floor(Math.random() * conditions.length)];
return { city, temperature: `${temp}°F`, condition };
},
});
const client = new CopilotClient();
const session = await client.createSession({
model: "gpt-4.1",
streaming: true,
tools: [getWeather],
});
session.on((event: SessionEvent) => {
if (event.type === "assistant.message_delta") {
process.stdout.write(event.data.deltaContent);
}
});
await session.sendAndWait({
prompt: "What's the weather like in Seattle and Tokyo?",
});
await client.stop();
process.exit(0);Python (Pydantic)
Python (Pydantic)
python
import asyncio
import random
import sys
from copilot import CopilotClient
from copilot.tools import define_tool
from copilot.generated.session_events import SessionEventType
from pydantic import BaseModel, Field
class GetWeatherParams(BaseModel):
city: str = Field(description="The name of the city to get weather for")
@define_tool(description="Get the current weather for a city")
async def get_weather(params: GetWeatherParams) -> dict:
city = params.city
conditions = ["sunny", "cloudy", "rainy", "partly cloudy"]
temp = random.randint(50, 80)
condition = random.choice(conditions)
return {"city": city, "temperature": f"{temp}°F", "condition": condition}
async def main():
client = CopilotClient()
await client.start()
session = await client.create_session({
"model": "gpt-4.1",
"streaming": True,
"tools": [get_weather],
})
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": "What's the weather like in Seattle and Tokyo?"
})
await client.stop()
asyncio.run(main())python
import asyncio
import random
import sys
from copilot import CopilotClient
from copilot.tools import define_tool
from copilot.generated.session_events import SessionEventType
from pydantic import BaseModel, Field
class GetWeatherParams(BaseModel):
city: str = Field(description="The name of the city to get weather for")
@define_tool(description="Get the current weather for a city")
async def get_weather(params: GetWeatherParams) -> dict:
city = params.city
conditions = ["sunny", "cloudy", "rainy", "partly cloudy"]
temp = random.randint(50, 80)
condition = random.choice(conditions)
return {"city": city, "temperature": f"{temp}°F", "condition": condition}
async def main():
client = CopilotClient()
await client.start()
session = await client.create_session({
"model": "gpt-4.1",
"streaming": True,
"tools": [get_weather],
})
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": "What's the weather like in Seattle and Tokyo?"
})
await client.stop()
asyncio.run(main())Go
Go
go
type WeatherParams struct {
City string `json:"city" jsonschema:"The city name"`
}
type WeatherResult struct {
City string `json:"city"`
Temperature string `json:"temperature"`
Condition string `json:"condition"`
}
getWeather := copilot.DefineTool(
"get_weather",
"Get the current weather for a city",
func(params WeatherParams, inv copilot.ToolInvocation) (WeatherResult, error) {
conditions := []string{"sunny", "cloudy", "rainy", "partly cloudy"}
temp := rand.Intn(30) + 50
condition := conditions[rand.Intn(len(conditions))]
return WeatherResult{
City: params.City,
Temperature: fmt.Sprintf("%d°F", temp),
Condition: condition,
}, nil
},
)
session, _ := client.CreateSession(&copilot.SessionConfig{
Model: "gpt-4.1",
Streaming: true,
Tools: []copilot.Tool{getWeather},
})go
type WeatherParams struct {
City string `json:"city" jsonschema:"The city name"`
}
type WeatherResult struct {
City string `json:"city"`
Temperature string `json:"temperature"`
Condition string `json:"condition"`
}
getWeather := copilot.DefineTool(
"get_weather",
"Get the current weather for a city",
func(params WeatherParams, inv copilot.ToolInvocation) (WeatherResult, error) {
conditions := []string{"sunny", "cloudy", "rainy", "partly cloudy"}
temp := rand.Intn(30) + 50
condition := conditions[rand.Intn(len(conditions))]
return WeatherResult{
City: params.City,
Temperature: fmt.Sprintf("%d°F", temp),
Condition: condition,
}, nil
},
)
session, _ := client.CreateSession(&copilot.SessionConfig{
Model: "gpt-4.1",
Streaming: true,
Tools: []copilot.Tool{getWeather},
}).NET (Microsoft.Extensions.AI)
.NET (Microsoft.Extensions.AI)
csharp
using GitHub.Copilot.SDK;
using Microsoft.Extensions.AI;
using System.ComponentModel;
var getWeather = AIFunctionFactory.Create(
([Description("The city name")] string city) =>
{
var conditions = new[] { "sunny", "cloudy", "rainy", "partly cloudy" };
var temp = Random.Shared.Next(50, 80);
var condition = conditions[Random.Shared.Next(conditions.Length)];
return new { city, temperature = $"{temp}°F", condition };
},
"get_weather",
"Get the current weather for a city"
);
await using var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "gpt-4.1",
Streaming = true,
Tools = [getWeather],
});csharp
using GitHub.Copilot.SDK;
using Microsoft.Extensions.AI;
using System.ComponentModel;
var getWeather = AIFunctionFactory.Create(
([Description("The city name")] string city) =>
{
var conditions = new[] { "sunny", "cloudy", "rainy", "partly cloudy" };
var temp = Random.Shared.Next(50, 80);
var condition = conditions[Random.Shared.Next(conditions.Length)];
return new { city, temperature = $"{temp}°F", condition };
},
"get_weather",
"Get the current weather for a city"
);
await using var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "gpt-4.1",
Streaming = true,
Tools = [getWeather],
});How Tools Work
工具工作原理
When Copilot decides to call your tool:
- Copilot sends a tool call request with the parameters
- The SDK runs your handler function
- The result is sent back to Copilot
- Copilot incorporates the result into its response
Copilot decides when to call your tool based on the user's question and your tool's description.
当Copilot决定调用你的工具时:
- Copilot发送带有参数的工具调用请求
- SDK运行你的处理函数
- 结果被返回给Copilot
- Copilot将结果整合到响应中
Copilot会根据用户的问题和工具的描述,决定何时调用你的工具。
Interactive CLI Assistant
交互式CLI助手
Build a complete interactive assistant:
构建完整的交互式助手:
TypeScript
TypeScript
typescript
import { CopilotClient, defineTool, SessionEvent } from "@github/copilot-sdk";
import * as readline from "readline";
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 }) => {
const conditions = ["sunny", "cloudy", "rainy", "partly cloudy"];
const temp = Math.floor(Math.random() * 30) + 50;
const condition = conditions[Math.floor(Math.random() * conditions.length)];
return { city, temperature: `${temp}°F`, condition };
},
});
const client = new CopilotClient();
const session = await client.createSession({
model: "gpt-4.1",
streaming: true,
tools: [getWeather],
});
session.on((event: SessionEvent) => {
if (event.type === "assistant.message_delta") {
process.stdout.write(event.data.deltaContent);
}
});
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
console.log("Weather Assistant (type 'exit' to quit)");
console.log("Try: 'What's the weather in Paris?'\n");
const prompt = () => {
rl.question("You: ", async (input) => {
if (input.toLowerCase() === "exit") {
await client.stop();
rl.close();
return;
}
process.stdout.write("Assistant: ");
await session.sendAndWait({ prompt: input });
console.log("\n");
prompt();
});
};
prompt();typescript
import { CopilotClient, defineTool, SessionEvent } from "@github/copilot-sdk";
import * as readline from "readline";
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 }) => {
const conditions = ["sunny", "cloudy", "rainy", "partly cloudy"];
const temp = Math.floor(Math.random() * 30) + 50;
const condition = conditions[Math.floor(Math.random() * conditions.length)];
return { city, temperature: `${temp}°F`, condition };
},
});
const client = new CopilotClient();
const session = await client.createSession({
model: "gpt-4.1",
streaming: true,
tools: [getWeather],
});
session.on((event: SessionEvent) => {
if (event.type === "assistant.message_delta") {
process.stdout.write(event.data.deltaContent);
}
});
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
console.log("Weather Assistant (type 'exit' to quit)");
console.log("Try: 'What's the weather in Paris?'\n");
const prompt = () => {
rl.question("You: ", async (input) => {
if (input.toLowerCase() === "exit") {
await client.stop();
rl.close();
return;
}
process.stdout.write("Assistant: ");
await session.sendAndWait({ prompt: input });
console.log("\n");
prompt();
});
};
prompt();Python
Python
python
import asyncio
import random
import sys
from copilot import CopilotClient
from copilot.tools import define_tool
from copilot.generated.session_events import SessionEventType
from pydantic import BaseModel, Field
class GetWeatherParams(BaseModel):
city: str = Field(description="The name of the city to get weather for")
@define_tool(description="Get the current weather for a city")
async def get_weather(params: GetWeatherParams) -> dict:
conditions = ["sunny", "cloudy", "rainy", "partly cloudy"]
temp = random.randint(50, 80)
condition = random.choice(conditions)
return {"city": params.city, "temperature": f"{temp}°F", "condition": condition}
async def main():
client = CopilotClient()
await client.start()
session = await client.create_session({
"model": "gpt-4.1",
"streaming": True,
"tools": [get_weather],
})
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)
print("Weather Assistant (type 'exit' to quit)")
print("Try: 'What's the weather in Paris?'\n")
while True:
try:
user_input = input("You: ")
except EOFError:
break
if user_input.lower() == "exit":
break
sys.stdout.write("Assistant: ")
await session.send_and_wait({"prompt": user_input})
print("\n")
await client.stop()
asyncio.run(main())python
import asyncio
import random
import sys
from copilot import CopilotClient
from copilot.tools import define_tool
from copilot.generated.session_events import SessionEventType
from pydantic import BaseModel, Field
class GetWeatherParams(BaseModel):
city: str = Field(description="The name of the city to get weather for")
@define_tool(description="Get the current weather for a city")
async def get_weather(params: GetWeatherParams) -> dict:
conditions = ["sunny", "cloudy", "rainy", "partly cloudy"]
temp = random.randint(50, 80)
condition = random.choice(conditions)
return {"city": params.city, "temperature": f"{temp}°F", "condition": condition}
async def main():
client = CopilotClient()
await client.start()
session = await client.create_session({
"model": "gpt-4.1",
"streaming": True,
"tools": [get_weather],
})
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)
print("Weather Assistant (type 'exit' to quit)")
print("Try: 'What's the weather in Paris?'\n")
while True:
try:
user_input = input("You: ")
except EOFError:
break
if user_input.lower() == "exit":
break
sys.stdout.write("Assistant: ")
await session.send_and_wait({"prompt": user_input})
print("\n")
await client.stop()
asyncio.run(main())MCP Server Integration
MCP服务器集成
Connect to MCP (Model Context Protocol) servers for pre-built tools. Connect to GitHub's MCP server for repository, issue, and PR access:
连接到MCP(Model Context Protocol,模型上下文协议)服务器以使用预构建工具。连接GitHub的MCP服务器可访问仓库、Issue和PR:
TypeScript
TypeScript
typescript
const session = await client.createSession({
model: "gpt-4.1",
mcpServers: {
github: {
type: "http",
url: "https://api.githubcopilot.com/mcp/",
},
},
});typescript
const session = await client.createSession({
model: "gpt-4.1",
mcpServers: {
github: {
type: "http",
url: "https://api.githubcopilot.com/mcp/",
},
},
});Python
Python
python
session = await client.create_session({
"model": "gpt-4.1",
"mcp_servers": {
"github": {
"type": "http",
"url": "https://api.githubcopilot.com/mcp/",
},
},
})python
session = await client.create_session({
"model": "gpt-4.1",
"mcp_servers": {
"github": {
"type": "http",
"url": "https://api.githubcopilot.com/mcp/",
},
},
})Go
Go
go
session, _ := client.CreateSession(&copilot.SessionConfig{
Model: "gpt-4.1",
MCPServers: map[string]copilot.MCPServerConfig{
"github": {
Type: "http",
URL: "https://api.githubcopilot.com/mcp/",
},
},
})go
session, _ := client.CreateSession(&copilot.SessionConfig{
Model: "gpt-4.1",
MCPServers: map[string]copilot.MCPServerConfig{
"github": {
Type: "http",
URL: "https://api.githubcopilot.com/mcp/",
},
},
}).NET
.NET
csharp
await using var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "gpt-4.1",
McpServers = new Dictionary<string, McpServerConfig>
{
["github"] = new McpServerConfig
{
Type = "http",
Url = "https://api.githubcopilot.com/mcp/",
},
},
});csharp
await using var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "gpt-4.1",
McpServers = new Dictionary<string, McpServerConfig>
{
["github"] = new McpServerConfig
{
Type = "http",
Url = "https://api.githubcopilot.com/mcp/",
},
},
});Custom Agents
自定义Agent
Define specialized AI personas for specific tasks:
为特定任务定义专用的AI角色:
TypeScript
TypeScript
typescript
const session = await client.createSession({
model: "gpt-4.1",
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.",
}],
});typescript
const session = await client.createSession({
model: "gpt-4.1",
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.",
}],
});Python
Python
python
session = await client.create_session({
"model": "gpt-4.1",
"custom_agents": [{
"name": "pr-reviewer",
"display_name": "PR Reviewer",
"description": "Reviews pull requests for best practices",
"prompt": "You are an expert code reviewer. Focus on security, performance, and maintainability.",
}],
})python
session = await client.create_session({
"model": "gpt-4.1",
"custom_agents": [{
"name": "pr-reviewer",
"display_name": "PR Reviewer",
"description": "Reviews pull requests for best practices",
"prompt": "You are an expert code reviewer. Focus on security, performance, and maintainability.",
}],
})System Message
系统消息
Customize the AI's behavior and personality:
自定义AI的行为和个性:
TypeScript
TypeScript
typescript
const session = await client.createSession({
model: "gpt-4.1",
systemMessage: {
content: "You are a helpful assistant for our engineering team. Always be concise.",
},
});typescript
const session = await client.createSession({
model: "gpt-4.1",
systemMessage: {
content: "You are a helpful assistant for our engineering team. Always be concise.",
},
});Python
Python
python
session = await client.create_session({
"model": "gpt-4.1",
"system_message": {
"content": "You are a helpful assistant for our engineering team. Always be concise.",
},
})python
session = await client.create_session({
"model": "gpt-4.1",
"system_message": {
"content": "You are a helpful assistant for our engineering team. Always be concise.",
},
})External CLI Server
外部CLI服务器
Run the CLI in server mode separately and connect the SDK to it. Useful for debugging, resource sharing, or custom environments.
单独以服务器模式运行CLI,并将SDK连接到它。适用于调试、资源共享或自定义环境。
Start CLI in Server Mode
以服务器模式启动CLI
bash
copilot --server --port 4321bash
copilot --server --port 4321Connect SDK to External Server
将SDK连接到外部服务器
TypeScript
TypeScript
typescript
const client = new CopilotClient({
cliUrl: "localhost:4321"
});
const session = await client.createSession({ model: "gpt-4.1" });typescript
const client = new CopilotClient({
cliUrl: "localhost:4321"
});
const session = await client.createSession({ model: "gpt-4.1" });Python
Python
python
client = CopilotClient({
"cli_url": "localhost:4321"
})
await client.start()
session = await client.create_session({"model": "gpt-4.1"})python
client = CopilotClient({
"cli_url": "localhost:4321"
})
await client.start()
session = await client.create_session({"model": "gpt-4.1"})Go
Go
go
client := copilot.NewClient(&copilot.ClientOptions{
CLIUrl: "localhost:4321",
})
if err := client.Start(); err != nil {
log.Fatal(err)
}
session, _ := client.CreateSession(&copilot.SessionConfig{Model: "gpt-4.1"})go
client := copilot.NewClient(&copilot.ClientOptions{
CLIUrl: "localhost:4321",
})
if err := client.Start(); err != nil {
log.Fatal(err)
}
session, _ := client.CreateSession(&copilot.SessionConfig{Model: "gpt-4.1"}).NET
.NET
csharp
using var client = new CopilotClient(new CopilotClientOptions
{
CliUrl = "localhost:4321"
});
await using var session = await client.CreateSessionAsync(new SessionConfig { Model = "gpt-4.1" });Note: When is provided, the SDK will not spawn or manage a CLI process - it only connects to the existing server.
cliUrlcsharp
using var client = new CopilotClient(new CopilotClientOptions
{
CliUrl = "localhost:4321"
});
await using var session = await client.CreateSessionAsync(new SessionConfig { Model = "gpt-4.1" });注意:当提供时,SDK不会启动或管理CLI进程——它只会连接到已有的服务器。
cliUrlEvent Types
事件类型
| Event | Description |
|---|---|
| User input added |
| Complete model response |
| Streaming response chunk |
| Model reasoning (model-dependent) |
| Streaming reasoning chunk |
| Tool invocation started |
| Tool execution finished |
| No active processing |
| Error occurred |
| 事件 | 描述 |
|---|---|
| 添加了用户输入 |
| 完整的模型响应 |
| 流式响应的片段 |
| 模型推理过程(取决于模型) |
| 流式推理的片段 |
| 工具调用已启动 |
| 工具执行已完成 |
| 无活跃处理任务 |
| 发生错误 |
Client Configuration
客户端配置
| Option | Description | Default |
|---|---|---|
| Path to Copilot CLI executable | System PATH |
| Connect to existing server (e.g., "localhost:4321") | None |
| Server communication port | Random |
| Use stdio transport instead of TCP | true |
| Logging verbosity | "info" |
| Launch server automatically | true |
| Restart on crashes | true |
| Working directory for CLI process | Inherited |
| 选项 | 描述 | 默认值 |
|---|---|---|
| Copilot CLI可执行文件的路径 | 系统PATH |
| 连接到已存在的服务器(例如:"localhost:4321") | 无 |
| 服务器通信端口 | 随机 |
| 使用stdio传输而非TCP | true |
| 日志详细程度 | "info" |
| 自动启动服务器 | true |
| 崩溃时自动重启 | true |
| CLI进程的工作目录 | 继承当前目录 |
Session Configuration
会话配置
| Option | Description |
|---|---|
| LLM to use ("gpt-4.1", "claude-sonnet-4.5", etc.) |
| Custom session identifier |
| Custom tool definitions |
| MCP server connections |
| Custom agent personas |
| Override default system prompt |
| Enable incremental response chunks |
| Whitelist of permitted tools |
| Blacklist of disabled tools |
| 选项 | 描述 |
|---|---|
| 使用的大语言模型("gpt-4.1"、"claude-sonnet-4.5"等) |
| 自定义会话标识符 |
| 自定义工具定义 |
| MCP服务器连接配置 |
| 自定义Agent角色 |
| 覆盖默认系统提示词 |
| 启用增量响应片段 |
| 允许使用的工具白名单 |
| 禁用的工具黑名单 |
Session Persistence
会话持久化
Save and resume conversations across restarts:
在重启之间保存和恢复对话:
Create with Custom ID
使用自定义ID创建会话
typescript
const session = await client.createSession({
sessionId: "user-123-conversation",
model: "gpt-4.1"
});typescript
const session = await client.createSession({
sessionId: "user-123-conversation",
model: "gpt-4.1"
});Resume Session
恢复会话
typescript
const session = await client.resumeSession("user-123-conversation");
await session.send({ prompt: "What did we discuss earlier?" });typescript
const session = await client.resumeSession("user-123-conversation");
await session.send({ prompt: "What did we discuss earlier?" });List and Delete Sessions
列出和删除会话
typescript
const sessions = await client.listSessions();
await client.deleteSession("old-session-id");typescript
const sessions = await client.listSessions();
await client.deleteSession("old-session-id");Error Handling
错误处理
typescript
try {
const client = new CopilotClient();
const session = await client.createSession({ model: "gpt-4.1" });
const response = await session.sendAndWait(
{ prompt: "Hello!" },
30000 // timeout in ms
);
} catch (error) {
if (error.code === "ENOENT") {
console.error("Copilot CLI not installed");
} else if (error.code === "ECONNREFUSED") {
console.error("Cannot connect to Copilot server");
} else {
console.error("Error:", error.message);
}
} finally {
await client.stop();
}typescript
try {
const client = new CopilotClient();
const session = await client.createSession({ model: "gpt-4.1" });
const response = await session.sendAndWait(
{ prompt: "Hello!" },
30000 // 超时时间(毫秒)
);
} catch (error) {
if (error.code === "ENOENT") {
console.error("Copilot CLI未安装");
} else if (error.code === "ECONNREFUSED") {
console.error("无法连接到Copilot服务器");
} else {
console.error("错误:", error.message);
}
} finally {
await client.stop();
}Graceful Shutdown
优雅关闭
typescript
process.on("SIGINT", async () => {
console.log("Shutting down...");
await client.stop();
process.exit(0);
});typescript
process.on("SIGINT", async () => {
console.log("正在关闭...");
await client.stop();
process.exit(0);
});Common Patterns
常见模式
Multi-turn Conversation
多轮对话
typescript
const session = await client.createSession({ model: "gpt-4.1" });
await session.sendAndWait({ prompt: "My name is Alice" });
await session.sendAndWait({ prompt: "What's my name?" });
// Response: "Your name is Alice"typescript
const session = await client.createSession({ model: "gpt-4.1" });
await session.sendAndWait({ prompt: "My name is Alice" });
await session.sendAndWait({ prompt: "What's my name?" });
// 响应: "Your name is Alice"File Attachments
文件附件
typescript
await session.send({
prompt: "Analyze this file",
attachments: [{
type: "file",
path: "./data.csv",
displayName: "Sales Data"
}]
});typescript
await session.send({
prompt: "Analyze this file",
attachments: [{
type: "file",
path: "./data.csv",
displayName: "Sales Data"
}]
});Abort Long Operations
终止长操作
typescript
const timeoutId = setTimeout(() => {
session.abort();
}, 60000);
session.on((event) => {
if (event.type === "session.idle") {
clearTimeout(timeoutId);
}
});typescript
const timeoutId = setTimeout(() => {
session.abort();
}, 60000);
session.on((event) => {
if (event.type === "session.idle") {
clearTimeout(timeoutId);
}
});Available Models
可用模型
Query available models at runtime:
typescript
const models = await client.getModels();
// Returns: ["gpt-4.1", "gpt-4o", "claude-sonnet-4.5", ...]在运行时查询可用模型:
typescript
const models = await client.getModels();
// 返回: ["gpt-4.1", "gpt-4o", "claude-sonnet-4.5", ...]Best Practices
最佳实践
- Always cleanup: Use or
try-finallyto ensuredeferis calledclient.stop() - Set timeouts: Use with timeout for long operations
sendAndWait - Handle events: Subscribe to error events for robust error handling
- Use streaming: Enable streaming for better UX on long responses
- Persist sessions: Use custom session IDs for multi-turn conversations
- Define clear tools: Write descriptive tool names and descriptions
- 始终清理资源:使用或
try-finally确保调用deferclient.stop() - 设置超时:对长操作使用带超时参数的
sendAndWait - 处理事件:订阅错误事件以实现健壮的错误处理
- 使用流式响应:对长响应启用流式输出以提升用户体验
- 持久化会话:使用自定义会话ID实现多轮对话
- 定义清晰的工具:编写描述性的工具名称和说明
Architecture
架构
Your Application
|
SDK Client
| JSON-RPC
Copilot CLI (server mode)
|
GitHub (models, auth)The SDK manages the CLI process lifecycle automatically. All communication happens via JSON-RPC over stdio or TCP.
你的应用
|
SDK客户端
| JSON-RPC
Copilot CLI(服务器模式)
|
GitHub(模型、认证)SDK会自动管理CLI进程的生命周期。所有通信通过stdio或TCP上的JSON-RPC进行。
Resources
资源
- GitHub Repository: https://github.com/github/copilot-sdk
- Getting Started Tutorial: https://github.com/github/copilot-sdk/blob/main/docs/tutorials/first-app.md
- GitHub MCP Server: https://github.com/github/github-mcp-server
- MCP Servers Directory: https://github.com/modelcontextprotocol/servers
- Cookbook: https://github.com/github/copilot-sdk/tree/main/cookbook
- Samples: https://github.com/github/copilot-sdk/tree/main/samples
- GitHub仓库:https://github.com/github/copilot-sdk
- 入门教程:https://github.com/github/copilot-sdk/blob/main/docs/tutorials/first-app.md
- GitHub MCP服务器:https://github.com/github/github-mcp-server
- MCP服务器目录:https://github.com/modelcontextprotocol/servers
- 食谱:https://github.com/github/copilot-sdk/tree/main/cookbook
- 示例:https://github.com/github/copilot-sdk/tree/main/samples
Status
状态
This SDK is in Technical Preview and may have breaking changes. Not recommended for production use yet.
本SDK处于技术预览阶段,可能会有破坏性变更。目前不建议用于生产环境。