alpha

Guides a coding assistant in building C# applications with the Copilot SDK, covering client setup, sessions, options, tools and async patterns.
applyTo: '**.cs, **.csproj'
description: 'This file provides guidance on building C# applications using the Microsoft Copilot SDK.'
name: 'Microsoft Copilot SDK C# Instructions'
The Microsoft Copilot SDK is transitioning from the GitHub Copilot SDK in phases. No immediate changes are required; package names and examples below use the currently published identifiers. See the [official transition announcement](https://github.blog/changelog/2026-10-28-github-copilot-sdk-is-becoming-microsoft-copilot-sdk/).
Always install via NuGet:
dotnet add package GitHub.Copilot.SDK
await using var client = new CopilotClient();
await client.StartAsync();
When creating a CopilotClient, use CopilotClientOptions:
CliPath - Path to CLI executable (default: "copilot" from PATH)CliArgs - Extra arguments prepended before SDK-managed flagsCliUrl - URL of existing CLI server (e.g., "localhost:8080"). When provided, client won't spawn a processPort - Server port (default: 0 for random)UseStdio - Use stdio transport instead of TCP (default: true)LogLevel - Log level (default: "info")AutoStart - Auto-start server (default: true)AutoRestart - Auto-restart on crash (default: true)Cwd - Working directory for the CLI processEnvironment - Environment variables for the CLI processLogger - ILogger instance for SDK loggingFor explicit control:
var client = new CopilotClient(new CopilotClientOptions { AutoStart = false });
await client.StartAsync();
// Use client...
await client.StopAsync();
Use ForceStopAsync() when StopAsync() takes too long.
Use SessionConfig for configuration:
await using var session = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "gpt-5",
Streaming = true,
Tools = [...],
SystemMessage = new SystemMessageConfig { ... },
AvailableTools = ["tool1", "tool2"],
ExcludedTools = ["tool3"],
Provider = new ProviderConfig { ... }
});
SessionId - Custom session IDModel - Model name ("gpt-5", "claude-sonnet-4.5", etc.)Tools - Custom tools exposed to the CLISystemMessage - System message customizationAvailableTools - Allowlist of tool namesExcludedTools - Blocklist of tool namesProvider - Custom API provider configuration (BYOK)Streaming - Enable streaming response chunks (default: false)var session = await client.ResumeSessionAsync(sessionId, new ResumeSessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
// ...
});
session.SessionId - Get session identifiersession.SendAsync(new MessageOptions { Prompt = "...", Attachments = [...] }) - Send messagesession.AbortAsync() - Abort current processingsession.GetMessagesAsync() - Get all events/messagesawait session.DisposeAsync() - Clean up resourcesALWAYS use TaskCompletionSource for waiting on session events:
var done = new TaskCompletionSource();
session.On(evt =>
{
if (evt is AssistantMessageEvent msg)
{
Console.WriteLine(msg.Data.Content);
}
else if (evt is SessionIdleEvent)
{
done.SetResult();
}
});
await session.SendAsync(new MessageOptions { Prompt = "..." });
await done.Task;
The On() method returns an IDisposable:
var subscription = session.On(evt => { /* handler */ });
// Later...
subscription.Dispose();
Use pattern matching or switch expressions for event handling:
session.On(evt =>
{
switch (evt)
{
case UserMessageEvent userMsg:
// Handle user message
break;
case AssistantMessageEvent assistantMsg:
Console.WriteLine(assistantMsg.Data.Content);
break;
case ToolExecutionStartEvent toolStart:
// Tool execution started
break;
case ToolExecutionCompleteEvent toolComplete:
// Tool execution completed
break;
case SessionStartEvent start:
// Session started
break;
case SessionIdleEvent idle:
// Session is idle (processing complete)
break;
case SessionErrorEvent error:
Console.WriteLine($"Error: {error.Data.Message}");
break;
}
});
Set Streaming = true in SessionConfig:
var session = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "gpt-5",
Streaming = true
});
Handle both delta events (incremental) and final events:
var done = new TaskCompletionSource();
session.On(evt =>
{
switch (evt)
{
case AssistantMessageDeltaEvent delta:
// Incremental text chunk
Console.Write(delta.Data.DeltaContent);
break;
case AssistantReasoningDeltaEvent reasoningDelta:
// Incremental reasoning chunk (model-dependent)
Console.Write(reasoningDelta.Data.DeltaContent);
break;
case AssistantMessageEvent msg:
// Final complete message
Console.WriteLine("\n--- Final ---");
Console.WriteLine(msg.Data.Content);
break;
case AssistantReasoningEvent reasoning:
// Final reasoning content
Console.WriteLine("--- Reasoning ---");
Console.WriteLine(reasoning.Data.Content);
break;
case SessionIdleEvent:
done.SetResult();
break;
}
});
await session.SendAsync(new MessageOptions { Prompt = "Tell me a story" });
await done.Task;
Note: Final events (AssistantMessageEvent, AssistantReasoningEvent) are ALWAYS sent regardless of streaming setting.
Use Microsoft.Extensions.AI.AIFunctionFactory.Create for type-safe tools:
using Microsoft.Extensions.AI;
using System.ComponentModel;
var session = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "gpt-5",
Tools = [
AIFunctionFactory.Create(
async ([Description("Issue ID")] string id) => {
var issue = await FetchIssueAsync(id);
return issue;
},
"lookup_issue",
"Fetch issue details from tracker"),
]
});
ToolResultAIContent wrapping ToolResultObject for full control over metadataWhen Copilot invokes a tool, the client automatically:
var session = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "gpt-5",
SystemMessage = new SystemMessageConfig
{
Mode = SystemMessageMode.Append,
Content = @"
<workflow_rules>
- Always check for security vulnerabilities
- Suggest performance improvements when applicable
</workflow_rules>
"
}
});
var session = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "gpt-5",
SystemMessage = new SystemMessageConfig
{
Mode = SystemMessageMode.Replace,
Content = "You are a helpful assistant."
}
});
Attach files to messages using UserMessageDataAttachmentsItem:
await session.SendAsync(new MessageOptions
{
Prompt = "Analyze this file",
Attachments = new List<UserMessageDataAttachmentsItem>
{
new UserMessageDataAttachmentsItem
{
Type = UserMessageDataAttachmentsItemType.File,
Path = "/path/to/file.cs",
DisplayName = "My File"
}
}
});
Use the Mode property in MessageOptions:
"enqueue" - Queue message for processing"immediate" - Process message immediatelyawait session.SendAsync(new MessageOptions
{
Prompt = "...",
Mode = "enqueue"
});
Sessions are independent and can run concurrently:
var session1 = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "gpt-5",
});
var session2 = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "claude-sonnet-4.5",
});
await session1.SendAsync(new MessageOptions { Prompt = "Hello from session 1" });
await session2.SendAsync(new MessageOptions { Prompt = "Hello from session 2" });
Use custom API providers via ProviderConfig:
var session = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
Provider = new ProviderConfig
{
Type = "openai",
BaseUrl = "https://api.openai.com/v1",
ApiKey = "your-api-key"
}
});
var sessions = await client.ListSessionsAsync();
foreach (var metadata in sessions)
{
Console.WriteLine($"Session: {metadata.SessionId}");
}
await client.DeleteSessionAsync(sessionId);
var state = client.State;
try
{
var session = await client.CreateSessionAsync(new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll });
await session.SendAsync(new MessageOptions { Prompt = "Hello" });
}
catch (StreamJsonRpc.RemoteInvocationException ex)
{
Console.Error.WriteLine($"JSON-RPC Error: {ex.Message}");
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error: {ex.Message}");
}
Monitor SessionErrorEvent for runtime errors:
session.On(evt =>
{
if (evt is SessionErrorEvent error)
{
Console.Error.WriteLine($"Session Error: {error.Data.Message}");
}
});
Use PingAsync to verify server connectivity:
var response = await client.PingAsync("test message");
ALWAYS use await using for automatic disposal:
await using var client = new CopilotClient();
await using var session = await client.CreateSessionAsync(new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll });
// Resources automatically cleaned up
If not using await using:
var client = new CopilotClient();
try
{
await client.StartAsync();
// Use client...
}
finally
{
await client.StopAsync();
}
await using for CopilotClient and CopilotSessionawait using var client = new CopilotClient();
await client.StartAsync();
await using var session = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "gpt-5"
});
var done = new TaskCompletionSource();
session.On(evt =>
{
if (evt is AssistantMessageEvent msg)
{
Console.WriteLine(msg.Data.Content);
}
else if (evt is SessionIdleEvent)
{
done.SetResult();
}
});
await session.SendAsync(new MessageOptions { Prompt = "What is 2+2?" });
await done.Task;
await using var session = await client.CreateSessionAsync(new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll });
async Task SendAndWait(string prompt)
{
var done = new TaskCompletionSource();
var subscription = session.On(evt =>
{
if (evt is AssistantMessageEvent msg)
{
Console.WriteLine(msg.Data.Content);
}
else if (evt is SessionIdleEvent)
{
done.SetResult();
}
});
await session.SendAsync(new MessageOptions { Prompt = prompt });
await done.Task;
subscription.Dispose();
}
await SendAndWait("What is the capital of France?");
await SendAndWait("What is its population?");
var session = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
Tools = [
AIFunctionFactory.Create(
([Description("User ID")] string userId) => {
return new {
Id = userId,
Name = "John Doe",
Email = "john@example.com",
Role = "Developer"
};
},
"get_user",
"Retrieve user information")
]
});
© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com


Solar Project Development Optimization Expert
Acts as a senior solar developer who optimizes projects from site assessment through permitting, interconnection, offtake and financing, with risk mitigation.
system-prompt, act-as, expert-advice, planner, renewable-energy, project-management, risk-management, corporate-finance, financial-analysis, sustainability, business-strategy, compliance, due-diligence, for-executives, for-investors, for-consultants, xml-tags, structured-output, roadmap, timeline, report, advanced, long-form, engineering, solar-energy, project-finance

Luxury Smartwatch Campaign Grid
Generates a 3x3 grid campaign image of a luxury titanium smartwatch, from hero shot to macro, lifestyle and surreal scenes.
image-prompt, json-prompt, structured-output, multi-panel, product-photography, advertising, social-media-graphic, 3d-render, futuristic, cyberpunk, luxury, neon, macro, dramatic-lighting, vertical-format, nano-banana, branding, for-marketers, for-designers, long-form, mockup

Young Korean woman walks Seoul alley on DV camcorder
Generates a 30-second early-2000s DV camcorder home video of a young woman running errands through an older Seoul neighbourhood, with natural sound only.
video-prompt, vlog, home-video, handheld, korea, character-consistency, photorealistic, negative-prompt, seedance, cityscape, animals, film-grain, vintage, candid, woman, tracking-shot, short-film, documentary, natural-light, muted-colors, medium-shot, single-take, food-photography
Loading reviews…
Loading comments…