Copilot SDK

Copilot SDK

Teaches an agent to embed Copilot's agent runtime in apps with the Copilot SDK: custom tools, streaming, sessions, MCP servers and custom agents.

Skill files1 file
SKILL.md910 lines
1
---
2
name: copilot-sdk
3
description: Build agentic applications with the Microsoft Copilot SDK, transitioning from GitHub Copilot SDK. Use when embedding AI agents in apps, creating custom tools, implementing streaming responses, managing sessions, connecting to MCP servers, or creating custom agents. Triggers on Copilot SDK, Microsoft Copilot SDK, GitHub Copilot SDK, agentic app, embed Copilot, programmable agent, MCP server, custom agent.
4
---
5
6
# Microsoft Copilot SDK
7
8
Embed Copilot's agentic workflows in any application using Python, TypeScript, Go, or .NET.
9
10
## Overview
11
12
The Microsoft Copilot SDK is transitioning from the GitHub Copilot SDK. It is becoming the programmable interface for the Microsoft Copilot harness, the shared agent foundation used across Microsoft and GitHub products. This transition is happening in phases, and no immediate changes are required for existing users. Package names, namespaces, and some documentation may continue to use GitHub branding during the transition.
13
14
This guide keeps the currently published package names and imports in its examples. Follow the [official transition announcement](https://github.blog/changelog/2026-10-28-github-copilot-sdk-is-becoming-microsoft-copilot-sdk/) for migration updates.
15
16
The SDK provides a production-tested agent runtime you can invoke programmatically. You define agent behavior, while Copilot handles planning, tool invocation, file edits, and more.
17
18
## Prerequisites
19
20
1. **GitHub Copilot access** and an authenticated environment
21
2. **Language runtime**: Node.js ^20.19.0 or >=22.12.0, Python 3.11+, Go 1.24+, or a .NET Standard 2.0-compatible implementation
22
3. **Go**: GitHub Copilot CLI installed and authenticated ([Installation guide](https://docs.github.com/en/copilot/how-tos/set-up/install-copilot-cli))
23
24
The TypeScript, Python, and .NET packages use a bundled Copilot runtime by default, so they do not need a separate CLI installation.
25
26
## Installation
27
28
### Node.js/TypeScript
29
```bash
30
mkdir copilot-demo && cd copilot-demo
31
npm init -y --init-type module
32
npm install @github/copilot-sdk tsx
33
```
34
35
### Python
36
```bash
37
pip install github-copilot-sdk
38
39
# Optional: pre-download the bundled runtime instead of downloading it on first use
40
python -m copilot download-runtime
41
```
42
43
Published Python wheels include a pinned runtime version. The pre-download command caches that runtime locally; if skipped, the SDK attempts to download it automatically on first use.
44
45
### Go
46
```bash
47
mkdir copilot-demo && cd copilot-demo
48
go mod init copilot-demo
49
go get github.com/github/copilot-sdk/go
50
```
51
52
### .NET
53
```bash
54
dotnet new console -n CopilotDemo && cd CopilotDemo
55
dotnet add package GitHub.Copilot.SDK
56
```
57
58
## Quick Start
59
60
### TypeScript
61
```typescript
62
import { CopilotClient, approveAll } from "@github/copilot-sdk";
63
64
const client = new CopilotClient();
65
const session = await client.createSession({
66
onPermissionRequest: approveAll,
67
model: "gpt-4.1",
68
});
69
70
const response = await session.sendAndWait({ prompt: "What is 2 + 2?" });
71
console.log(response?.data.content);
72
73
await client.stop();
74
process.exit(0);
75
```
76
77
Run: `npx tsx index.ts`
78
79
### Python
80
```python
81
import asyncio
82
from copilot import CopilotClient, PermissionHandler
83
84
async def main():
85
async with CopilotClient() as client:
86
async with await client.create_session(
87
on_permission_request=PermissionHandler.approve_all,
88
model="gpt-4.1",
89
) as session:
90
response = await session.send_and_wait("What is 2 + 2?")
91
print(response.data.content)
92
93
asyncio.run(main())
94
```
95
96
### Go
97
```go
98
package main
99
100
import (
101
"fmt"
102
"log"
103
"os"
104
copilot "github.com/github/copilot-sdk/go"
105
)
106
107
func main() {
108
client := copilot.NewClient(nil)
109
if err := client.Start(); err != nil {
110
log.Fatal(err)
111
}
112
defer client.Stop()
113
114
session, err := client.CreateSession(&copilot.SessionConfig{
115
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
116
Model: "gpt-4.1",
117
})
118
if err != nil {
119
log.Fatal(err)
120
}
121
122
response, err := session.SendAndWait(copilot.MessageOptions{Prompt: "What is 2 + 2?"}, 0)
123
if err != nil {
124
log.Fatal(err)
125
}
126
127
fmt.Println(*response.Data.Content)
128
os.Exit(0)
129
}
130
```
131
132
### .NET (C#)
133
```csharp
134
using GitHub.Copilot.SDK;
135
136
await using var client = new CopilotClient();
137
await using var session = await client.CreateSessionAsync(new SessionConfig
138
{
139
OnPermissionRequest = PermissionHandler.ApproveAll,
140
Model = "gpt-4.1",
141
});
142
143
var response = await session.SendAndWaitAsync(new MessageOptions { Prompt = "What is 2 + 2?" });
144
Console.WriteLine(response?.Data.Content);
145
```
146
147
Run: `dotnet run`
148
149
## Streaming Responses
150
151
Enable real-time output for better UX:
152
153
### TypeScript
154
```typescript
155
import { CopilotClient, approveAll, SessionEvent } from "@github/copilot-sdk";
156
157
const client = new CopilotClient();
158
const session = await client.createSession({
159
onPermissionRequest: approveAll,
160
model: "gpt-4.1",
161
streaming: true,
162
});
163
164
session.on((event: SessionEvent) => {
165
if (event.type === "assistant.message_delta") {
166
process.stdout.write(event.data.deltaContent);
167
}
168
if (event.type === "session.idle") {
169
console.log(); // New line when done
170
}
171
});
172
173
await session.sendAndWait({ prompt: "Tell me a short joke" });
174
175
await client.stop();
176
process.exit(0);
177
```
178
179
### Python
180
```python
181
import asyncio
182
import sys
183
from copilot import CopilotClient, PermissionHandler
184
from copilot.generated.session_events import SessionEventType
185
186
async def main():
187
async with CopilotClient() as client:
188
async with await client.create_session(
189
on_permission_request=PermissionHandler.approve_all,
190
model="gpt-4.1",
191
streaming=True,
192
) as session:
193
def handle_event(event):
194
if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:
195
sys.stdout.write(event.data.delta_content)
196
sys.stdout.flush()
197
if event.type == SessionEventType.SESSION_IDLE:
198
print()
199
200
session.on(handle_event)
201
await session.send_and_wait("Tell me a short joke")
202
203
asyncio.run(main())
204
```
205
206
### Go
207
```go
208
session, err := client.CreateSession(&copilot.SessionConfig{
209
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
210
Model: "gpt-4.1",
211
Streaming: true,
212
})
213
214
session.On(func(event copilot.SessionEvent) {
215
if event.Type == "assistant.message_delta" {
216
fmt.Print(*event.Data.DeltaContent)
217
}
218
if event.Type == "session.idle" {
219
fmt.Println()
220
}
221
})
222
223
_, err = session.SendAndWait(copilot.MessageOptions{Prompt: "Tell me a short joke"}, 0)
224
```
225
226
### .NET
227
```csharp
228
await using var session = await client.CreateSessionAsync(new SessionConfig
229
{
230
OnPermissionRequest = PermissionHandler.ApproveAll,
231
Model = "gpt-4.1",
232
Streaming = true,
233
});
234
235
session.On(ev =>
236
{
237
if (ev is AssistantMessageDeltaEvent deltaEvent)
238
Console.Write(deltaEvent.Data.DeltaContent);
239
if (ev is SessionIdleEvent)
240
Console.WriteLine();
241
});
242
243
await session.SendAndWaitAsync(new MessageOptions { Prompt = "Tell me a short joke" });
244
```
245
246
## Custom Tools
247
248
Define tools that Copilot can invoke during reasoning. When you define a tool, you tell Copilot:
249
1. **What the tool does** (description)
250
2. **What parameters it needs** (schema)
251
3. **What code to run** (handler)
252
253
### TypeScript (JSON Schema)
254
```typescript
255
import { CopilotClient, approveAll, defineTool, SessionEvent } from "@github/copilot-sdk";
256
257
const getWeather = defineTool("get_weather", {
258
description: "Get the current weather for a city",
259
parameters: {
260
type: "object",
261
properties: {
262
city: { type: "string", description: "The city name" },
263
},
264
required: ["city"],
265
},
266
handler: async (args: { city: string }) => {
267
const { city } = args;
268
// In a real app, call a weather API here
269
const conditions = ["sunny", "cloudy", "rainy", "partly cloudy"];
270
const temp = Math.floor(Math.random() * 30) + 50;
271
const condition = conditions[Math.floor(Math.random() * conditions.length)];
272
return { city, temperature: `${temp}°F`, condition };
273
},
274
});
275
276
const client = new CopilotClient();
277
const session = await client.createSession({
278
onPermissionRequest: approveAll,
279
model: "gpt-4.1",
280
streaming: true,
281
tools: [getWeather],
282
});
283
284
session.on((event: SessionEvent) => {
285
if (event.type === "assistant.message_delta") {
286
process.stdout.write(event.data.deltaContent);
287
}
288
});
289
290
await session.sendAndWait({
291
prompt: "What's the weather like in Seattle and Tokyo?",
292
});
293
294
await client.stop();
295
process.exit(0);
296
```
297
298
### Python (Pydantic)
299
```python
300
import asyncio
301
import random
302
import sys
303
from copilot import CopilotClient, PermissionHandler
304
from copilot.tools import define_tool
305
from copilot.generated.session_events import SessionEventType
306
from pydantic import BaseModel, Field
307
308
class GetWeatherParams(BaseModel):
309
city: str = Field(description="The name of the city to get weather for")
310
311
@define_tool(description="Get the current weather for a city")
312
async def get_weather(params: GetWeatherParams) -> dict:
313
city = params.city
314
conditions = ["sunny", "cloudy", "rainy", "partly cloudy"]
315
temp = random.randint(50, 80)
316
condition = random.choice(conditions)
317
return {"city": city, "temperature": f"{temp}°F", "condition": condition}
318
319
async def main():
320
async with CopilotClient() as client:
321
async with await client.create_session(
322
on_permission_request=PermissionHandler.approve_all,
323
model="gpt-4.1",
324
streaming=True,
325
tools=[get_weather],
326
) as session:
327
def handle_event(event):
328
if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:
329
sys.stdout.write(event.data.delta_content)
330
sys.stdout.flush()
331
332
session.on(handle_event)
333
await session.send_and_wait(
334
"What's the weather like in Seattle and Tokyo?"
335
)
336
337
asyncio.run(main())
338
```
339
340
### Go
341
```go
342
type WeatherParams struct {
343
City string `json:"city" jsonschema:"The city name"`
344
}
345
346
type WeatherResult struct {
347
City string `json:"city"`
348
Temperature string `json:"temperature"`
349
Condition string `json:"condition"`
350
}
351
352
getWeather := copilot.DefineTool(
353
"get_weather",
354
"Get the current weather for a city",
355
func(params WeatherParams, inv copilot.ToolInvocation) (WeatherResult, error) {
356
conditions := []string{"sunny", "cloudy", "rainy", "partly cloudy"}
357
temp := rand.Intn(30) + 50
358
condition := conditions[rand.Intn(len(conditions))]
359
return WeatherResult{
360
City: params.City,
361
Temperature: fmt.Sprintf("%d°F", temp),
362
Condition: condition,
363
}, nil
364
},
365
)
366
367
session, _ := client.CreateSession(&copilot.SessionConfig{
368
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
369
Model: "gpt-4.1",
370
Streaming: true,
371
Tools: []copilot.Tool{getWeather},
372
})
373
```
374
375
### .NET (Microsoft.Extensions.AI)
376
```csharp
377
using GitHub.Copilot.SDK;
378
using Microsoft.Extensions.AI;
379
using System.ComponentModel;
380
381
var getWeather = AIFunctionFactory.Create(
382
([Description("The city name")] string city) =>
383
{
384
var conditions = new[] { "sunny", "cloudy", "rainy", "partly cloudy" };
385
var temp = Random.Shared.Next(50, 80);
386
var condition = conditions[Random.Shared.Next(conditions.Length)];
387
return new { city, temperature = $"{temp}°F", condition };
388
},
389
"get_weather",
390
"Get the current weather for a city"
391
);
392
393
await using var session = await client.CreateSessionAsync(new SessionConfig
394
{
395
OnPermissionRequest = PermissionHandler.ApproveAll,
396
Model = "gpt-4.1",
397
Streaming = true,
398
Tools = [getWeather],
399
});
400
```
401
402
## How Tools Work
403
404
When Copilot decides to call your tool:
405
1. Copilot sends a tool call request with the parameters
406
2. The SDK runs your handler function
407
3. The result is sent back to Copilot
408
4. Copilot incorporates the result into its response
409
410
Copilot decides when to call your tool based on the user's question and your tool's description.
411
412
## Interactive CLI Assistant
413
414
Build a complete interactive assistant:
415
416
### TypeScript
417
```typescript
418
import { CopilotClient, approveAll, defineTool, SessionEvent } from "@github/copilot-sdk";
419
import * as readline from "readline";
420
421
const getWeather = defineTool("get_weather", {
422
description: "Get the current weather for a city",
423
parameters: {
424
type: "object",
425
properties: {
426
city: { type: "string", description: "The city name" },
427
},
428
required: ["city"],
429
},
430
handler: async ({ city }) => {
431
const conditions = ["sunny", "cloudy", "rainy", "partly cloudy"];
432
const temp = Math.floor(Math.random() * 30) + 50;
433
const condition = conditions[Math.floor(Math.random() * conditions.length)];
434
return { city, temperature: `${temp}°F`, condition };
435
},
436
});
437
438
const client = new CopilotClient();
439
const session = await client.createSession({
440
onPermissionRequest: approveAll,
441
model: "gpt-4.1",
442
streaming: true,
443
tools: [getWeather],
444
});
445
446
session.on((event: SessionEvent) => {
447
if (event.type === "assistant.message_delta") {
448
process.stdout.write(event.data.deltaContent);
449
}
450
});
451
452
const rl = readline.createInterface({
453
input: process.stdin,
454
output: process.stdout,
455
});
456
457
console.log("Weather Assistant (type 'exit' to quit)");
458
console.log("Try: 'What's the weather in Paris?'\n");
459
460
const prompt = () => {
461
rl.question("You: ", async (input) => {
462
if (input.toLowerCase() === "exit") {
463
await client.stop();
464
rl.close();
465
return;
466
}
467
468
process.stdout.write("Assistant: ");
469
await session.sendAndWait({ prompt: input });
470
console.log("\n");
471
prompt();
472
});
473
};
474
475
prompt();
476
```
477
478
### Python
479
```python
480
import asyncio
481
import random
482
import sys
483
from copilot import CopilotClient, PermissionHandler
484
from copilot.tools import define_tool
485
from copilot.generated.session_events import SessionEventType
486
from pydantic import BaseModel, Field
487
488
class GetWeatherParams(BaseModel):
489
city: str = Field(description="The name of the city to get weather for")
490
491
@define_tool(description="Get the current weather for a city")
492
async def get_weather(params: GetWeatherParams) -> dict:
493
conditions = ["sunny", "cloudy", "rainy", "partly cloudy"]
494
temp = random.randint(50, 80)
495
condition = random.choice(conditions)
496
return {"city": params.city, "temperature": f"{temp}°F", "condition": condition}
497
498
async def main():
499
async with CopilotClient() as client:
500
async with await client.create_session(
501
on_permission_request=PermissionHandler.approve_all,
502
model="gpt-4.1",
503
streaming=True,
504
tools=[get_weather],
505
) as session:
506
def handle_event(event):
507
if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:
508
sys.stdout.write(event.data.delta_content)
509
sys.stdout.flush()
510
511
session.on(handle_event)
512
513
print("Weather Assistant (type 'exit' to quit)")
514
print("Try: 'What's the weather in Paris?'\n")
515
516
while True:
517
try:
518
user_input = input("You: ")
519
except EOFError:
520
break
521
522
if user_input.lower() == "exit":
523
break
524
525
sys.stdout.write("Assistant: ")
526
await session.send_and_wait(user_input)
527
print("\n")
528
529
asyncio.run(main())
530
```
531
532
## MCP Server Integration
533
534
Connect to MCP (Model Context Protocol) servers for pre-built tools. Connect to GitHub's MCP server for repository, issue, and PR access:
535
536
### TypeScript
537
```typescript
538
const session = await client.createSession({
539
onPermissionRequest: approveAll,
540
model: "gpt-4.1",
541
mcpServers: {
542
github: {
543
type: "http",
544
url: "https://api.githubcopilot.com/mcp/",
545
},
546
},
547
});
548
```
549
550
### Python
551
```python
552
async with await client.create_session(
553
on_permission_request=PermissionHandler.approve_all,
554
model="gpt-4.1",
555
mcp_servers={
556
"github": {
557
"type": "http",
558
"url": "https://api.githubcopilot.com/mcp/",
559
},
560
},
561
) as session:
562
...
563
```
564
565
### Go
566
```go
567
session, _ := client.CreateSession(&copilot.SessionConfig{
568
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
569
Model: "gpt-4.1",
570
MCPServers: map[string]copilot.MCPServerConfig{
571
"github": {
572
"type": "http",
573
"url": "https://api.githubcopilot.com/mcp/",
574
},
575
},
576
})
577
```
578
579
### .NET
580
```csharp
581
await using var session = await client.CreateSessionAsync(new SessionConfig
582
{
583
OnPermissionRequest = PermissionHandler.ApproveAll,
584
Model = "gpt-4.1",
585
McpServers = new Dictionary<string, McpServerConfig>
586
{
587
["github"] = new McpServerConfig
588
{
589
Type = "http",
590
Url = "https://api.githubcopilot.com/mcp/",
591
},
592
},
593
});
594
```
595
596
## Custom Agents
597
598
Define specialized AI personas for specific tasks:
599
600
### TypeScript
601
```typescript
602
const session = await client.createSession({
603
onPermissionRequest: approveAll,
604
model: "gpt-4.1",
605
customAgents: [{
606
name: "pr-reviewer",
607
displayName: "PR Reviewer",
608
description: "Reviews pull requests for best practices",
609
prompt: "You are an expert code reviewer. Focus on security, performance, and maintainability.",
610
}],
611
});
612
```
613
614
### Python
615
```python
616
async with await client.create_session(
617
on_permission_request=PermissionHandler.approve_all,
618
model="gpt-4.1",
619
custom_agents=[{
620
"name": "pr-reviewer",
621
"display_name": "PR Reviewer",
622
"description": "Reviews pull requests for best practices",
623
"prompt": "You are an expert code reviewer. Focus on security, performance, and maintainability.",
624
}],
625
) as session:
626
...
627
```
628
629
## System Message
630
631
Customize the AI's behavior and personality:
632
633
### TypeScript
634
```typescript
635
const session = await client.createSession({
636
onPermissionRequest: approveAll,
637
model: "gpt-4.1",
638
systemMessage: {
639
content: "You are a helpful assistant for our engineering team. Always be concise.",
640
},
641
});
642
```
643
644
### Python
645
```python
646
async with await client.create_session(
647
on_permission_request=PermissionHandler.approve_all,
648
model="gpt-4.1",
649
system_message={
650
"content": "You are a helpful assistant for our engineering team. Always be concise.",
651
},
652
) as session:
653
...
654
```
655
656
## External CLI Server
657
658
Run the CLI in server mode separately and connect the SDK to it. Useful for debugging, resource sharing, or custom environments.
659
660
### Start CLI in Server Mode
661
```bash
662
copilot --server --port 4321
663
```
664
665
### Connect SDK to External Server
666
667
#### TypeScript
668
```typescript
669
const client = new CopilotClient({
670
cliUrl: "localhost:4321"
671
});
672
673
const session = await client.createSession({
674
onPermissionRequest: approveAll,
675
model: "gpt-4.1",
676
});
677
```
678
679
#### Python
680
```python
681
from copilot import CopilotClient, PermissionHandler, RuntimeConnection
682
683
async with CopilotClient(
684
connection=RuntimeConnection.for_uri("localhost:4321")
685
) as client:
686
async with await client.create_session(
687
on_permission_request=PermissionHandler.approve_all,
688
model="gpt-4.1",
689
) as session:
690
...
691
```
692
693
#### Go
694
```go
695
client := copilot.NewClient(&copilot.ClientOptions{
696
CLIUrl: "localhost:4321",
697
})
698
699
if err := client.Start(); err != nil {
700
log.Fatal(err)
701
}
702
703
session, _ := client.CreateSession(&copilot.SessionConfig{
704
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
705
Model: "gpt-4.1",
706
})
707
```
708
709
#### .NET
710
```csharp
711
using var client = new CopilotClient(new CopilotClientOptions
712
{
713
CliUrl = "localhost:4321"
714
});
715
716
await using var session = await client.CreateSessionAsync(new SessionConfig
717
{
718
OnPermissionRequest = PermissionHandler.ApproveAll,
719
Model = "gpt-4.1",
720
});
721
```
722
723
**Note:** When configured to use an external server, the SDK manages only its connection and does not manage the external process.
724
725
## Event Types
726
727
| Event | Description |
728
|-------|-------------|
729
| `user.message` | User input added |
730
| `assistant.message` | Complete model response |
731
| `assistant.message_delta` | Streaming response chunk |
732
| `assistant.reasoning` | Model reasoning (model-dependent) |
733
| `assistant.reasoning_delta` | Streaming reasoning chunk |
734
| `tool.execution_start` | Tool invocation started |
735
| `tool.execution_complete` | Tool execution finished |
736
| `session.idle` | No active processing |
737
| `session.error` | Error occurred |
738
739
## Client Configuration
740
741
| Option | Description | Default |
742
|--------|-------------|---------|
743
| `cliPath` | Path to Copilot CLI executable | System PATH |
744
| `cliUrl` | Connect to existing server (e.g., "localhost:4321") | None |
745
| `port` | Server communication port | Random |
746
| `useStdio` | Use stdio transport instead of TCP | true |
747
| `logLevel` | Logging verbosity | "info" |
748
| `autoStart` | Launch server automatically | true |
749
| `autoRestart` | Restart on crashes | true |
750
| `cwd` | Working directory for CLI process | Inherited |
751
752
## Session Configuration
753
754
| Option | Description |
755
|--------|-------------|
756
| `model` | LLM to use ("gpt-4.1", "claude-sonnet-4.5", etc.) |
757
| `sessionId` | Custom session identifier |
758
| `tools` | Custom tool definitions |
759
| `mcpServers` | MCP server connections |
760
| `customAgents` | Custom agent personas |
761
| `systemMessage` | Override default system prompt |
762
| `streaming` | Enable incremental response chunks |
763
| `availableTools` | Whitelist of permitted tools |
764
| `excludedTools` | Blacklist of disabled tools |
765
766
## Session Persistence
767
768
Save and resume conversations across restarts:
769
770
### Create with Custom ID
771
```typescript
772
const session = await client.createSession({
773
onPermissionRequest: approveAll,
774
sessionId: "user-123-conversation",
775
model: "gpt-4.1"
776
});
777
```
778
779
### Resume Session
780
```typescript
781
const session = await client.resumeSession("user-123-conversation", { onPermissionRequest: approveAll });
782
await session.send({ prompt: "What did we discuss earlier?" });
783
```
784
785
### List and Delete Sessions
786
```typescript
787
const sessions = await client.listSessions();
788
await client.deleteSession("old-session-id");
789
```
790
791
## Error Handling
792
793
```typescript
794
try {
795
const client = new CopilotClient();
796
const session = await client.createSession({
797
onPermissionRequest: approveAll,
798
model: "gpt-4.1",
799
});
800
const response = await session.sendAndWait(
801
{ prompt: "Hello!" },
802
30000 // timeout in ms
803
);
804
} catch (error) {
805
if (error.code === "ENOENT") {
806
console.error("Copilot CLI not installed");
807
} else if (error.code === "ECONNREFUSED") {
808
console.error("Cannot connect to Copilot server");
809
} else {
810
console.error("Error:", error.message);
811
}
812
} finally {
813
await client.stop();
814
}
815
```
816
817
## Graceful Shutdown
818
819
```typescript
820
process.on("SIGINT", async () => {
821
console.log("Shutting down...");
822
await client.stop();
823
process.exit(0);
824
});
825
```
826
827
## Common Patterns
828
829
### Multi-turn Conversation
830
```typescript
831
const session = await client.createSession({
832
onPermissionRequest: approveAll,
833
model: "gpt-4.1",
834
});
835
836
await session.sendAndWait({ prompt: "My name is Alice" });
837
await session.sendAndWait({ prompt: "What's my name?" });
838
// Response: "Your name is Alice"
839
```
840
841
### File Attachments
842
```typescript
843
await session.send({
844
prompt: "Analyze this file",
845
attachments: [{
846
type: "file",
847
path: "./data.csv",
848
displayName: "Sales Data"
849
}]
850
});
851
```
852
853
### Abort Long Operations
854
```typescript
855
const timeoutId = setTimeout(() => {
856
session.abort();
857
}, 60000);
858
859
session.on((event) => {
860
if (event.type === "session.idle") {
861
clearTimeout(timeoutId);
862
}
863
});
864
```
865
866
## Available Models
867
868
Query available models at runtime:
869
870
```typescript
871
const models = await client.getModels();
872
// Returns: ["gpt-4.1", "gpt-4o", "claude-sonnet-4.5", ...]
873
```
874
875
## Best Practices
876
877
1. **Always clean up**: Use language-native context managers or disposal, or explicitly disconnect sessions and stop clients
878
2. **Set timeouts**: Use `sendAndWait` with timeout for long operations
879
3. **Handle events**: Subscribe to error events for robust error handling
880
4. **Use streaming**: Enable streaming for better UX on long responses
881
5. **Persist sessions**: Use custom session IDs for multi-turn conversations
882
6. **Define clear tools**: Write descriptive tool names and descriptions
883
884
## Architecture
885
886
```
887
Your Application
888
|
889
SDK Client
890
| JSON-RPC
891
Copilot CLI (server mode)
892
|
893
GitHub (models, auth)
894
```
895
896
The SDK manages the CLI process lifecycle automatically. All communication happens via JSON-RPC over stdio or TCP.
897
898
## Resources
899
900
- **GitHub Repository**: https://github.com/github/copilot-sdk
901
- **Getting Started Tutorial**: https://github.com/github/copilot-sdk/blob/main/docs/tutorials/first-app.md
902
- **GitHub MCP Server**: https://github.com/github/github-mcp-server
903
- **MCP Servers Directory**: https://github.com/modelcontextprotocol/servers
904
- **Cookbook**: https://github.com/github/copilot-sdk/tree/main/cookbook
905
- **Samples**: https://github.com/github/copilot-sdk/tree/main/samples
906
907
## Status
908
909
This SDK is in **Technical Preview** and may have breaking changes. Not recommended for production use yet.
910

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…