AI capabilities are becoming part of many business applications. Developers are adding AI assistants to desktop applications, internal developer tools, customer support platforms, and enterprise services. However, building an AI assistant involves more than sending a prompt to a model and displaying its response. A useful assistant may need to maintain conversation sessions, call application functions, work with files, stream responses, and request permission before performing sensitive operations.
The GitHub Copilot SDK makes it possible to embed Copilot's agent runtime directly into a C# application. Instead of implementing the complete agent orchestration layer, developers can use the SDK to create sessions, send messages, receive responses, and expose custom tools that the agent can invoke.
For example, imagine an internal developer assistant that can answer programming questions, retrieve project information, and check build status. The application can provide these operations as C# tools while Copilot handles the agent interaction and decides when a tool is useful.
In this article, we will build a basic Copilot SDK integration using C#. We will create a console application, connect to the Copilot runtime, send a message, stream responses, and expose a custom C# function as an agent tool.
Understanding the GitHub Copilot SDK
The GitHub Copilot SDK provides a programmatic interface to the agent runtime behind Copilot. It allows developers to use agent capabilities inside their own applications instead of building every part of an agent system from scratch.
The SDK supports several important capabilities:
Creating and managing conversation sessions.
Sending prompts and receiving assistant responses.
Streaming responses as they are generated.
Defining custom tools using application code.
Handling tool permissions.
Working with multiple sessions.
Connecting to supported authentication and model providers.
The SDK is available for several programming languages, including C#, TypeScript, Python, Go, Java, and Rust.
One important naming change is worth understanding before installation. The SDK was originally known as the GitHub Copilot SDK, but its repository and package are transitioning to the Microsoft Copilot SDK. The current .NET package is Microsoft.Copilot.SDK, and its C# namespace is Microsoft.Copilot. Existing projects may still contain older package references and examples using GitHub-related names, so use the package and API names from the current SDK documentation when starting a new integration.
The SDK communicates with the Copilot runtime. By default, the .NET SDK manages the runtime connection for the application, so a separate CLI installation is not necessarily required. Authentication must still be configured through a supported method, such as an authenticated GitHub environment, a supported GitHub token, or a supported bring-your-own-key provider.
Creating a C# Project
Start by creating a console application:
dotnet new console -n CopilotDemo
cd CopilotDemo
Install the current .NET SDK package:
dotnet add package Microsoft.Copilot.SDK
The package provides the C# client, session APIs, event handling, and tool integration functionality.
Before running the application, make sure the environment has a supported authentication method configured. For local development, you can use an authenticated Copilot CLI environment. The SDK can also use supported token-based authentication, depending on your deployment requirements.
The SDK package manages the matching Copilot runtime for supported build environments. This is useful because the application does not need to implement its own process management or communication protocol for the agent runtime.
Connecting to the Copilot Runtime
The first step is to create a CopilotClient and start it.
Update Program.cs:
using Microsoft.Copilot;
await using var client = new CopilotClient(
new CopilotClientOptions
{
Mode = CopilotClientMode.CodingAgent
});
await client.StartAsync();
Console.WriteLine("Copilot client started.");
The CopilotClient represents the application's connection to the Copilot runtime. It manages the communication between the C# application and the underlying agent engine.
The Mode property is important. The SDK requires an explicit client mode. CodingAgent selects the coding-agent experience, including its associated defaults and capabilities. The SDK also provides an Empty mode for applications that want to opt into capabilities explicitly.
For a simple developer assistant, CodingAgent is a convenient starting point. For a multi-user service or an application that needs tighter control over enabled features, evaluate Empty mode and configure the required capabilities deliberately.
The client implements asynchronous disposal, so await using ensures that the connection and associated resources are released when the application exits.
Creating a Copilot Session
A client connection and a conversation session serve different purposes.
The client manages the runtime connection, while a session represents a particular conversation. Each session maintains its own conversation context, allowing an application to keep different users or tasks separate.
Create a session after starting the client:
await using var session =
await client.CreateSessionAsync(
new CreateSessionOptions
{
Model = "auto"
});
The Model property identifies the model selection for the session. Using auto allows the runtime to select an appropriate available model.
For applications that need predictable model behavior, you can configure an explicit supported model instead. The available model identifiers depend on the provider, account access, and runtime configuration.
Once the session is created, the application can send messages to it.
Sending the First Message
The SendAndWaitAsync() method sends a message and waits for the assistant's response to complete.
Add the following code after creating the session:
var response = await session.SendAndWaitAsync(
new MessageOptions
{
Prompt = "Explain dependency injection in C#."
});
Console.WriteLine(response?.Data.Content);
The MessageOptions object contains the prompt and can also support other message-related settings.
The returned response contains the assistant's message data. The null-conditional operator prevents an exception if no assistant response is available.
A complete minimal application looks like this:
using Microsoft.Copilot;
await using var client = new CopilotClient(
new CopilotClientOptions
{
Mode = CopilotClientMode.CodingAgent
});
await client.StartAsync();
await using var session =
await client.CreateSessionAsync(
new CreateSessionOptions
{
Model = "auto"
});
var response = await session.SendAndWaitAsync(
new MessageOptions
{
Prompt = "Explain dependency injection in C#."
});
Console.WriteLine(response?.Data.Content);
Run the application:
dotnet run
The application starts the Copilot runtime, creates a conversation session, sends the prompt, and displays the completed response.
This is enough to establish a basic integration. However, many real applications need to display responses as they arrive rather than waiting for the entire response.
Streaming Copilot Responses
In a desktop application or web-based chat interface, waiting for the complete response can make the assistant feel slow. Streaming allows the application to display response text as it is generated.
The SDK provides session events for this purpose.
Enable streaming when creating the session:
await using var session =
await client.CreateSessionAsync(
new CreateSessionOptions
{
Model = "auto",
Events = new SessionEventOptions
{
Streaming = true
}
});
Subscribe to session events before sending a message:
session.On<SessionEvent>(evt =>
{
if (evt is AssistantMessageDeltaEvent delta)
{
Console.Write(delta.Data.DeltaContent);
}
if (evt is SessionIdleEvent)
{
Console.WriteLine();
}
});
The AssistantMessageDeltaEvent contains a newly generated portion of the assistant's response. The application writes each portion to the console as it arrives.
The SessionIdleEvent indicates that the session has become idle. It is useful when the application needs to know when the current processing activity has finished.
Now send a message:
await session.SendAndWaitAsync(
new MessageOptions
{
Prompt = "Explain async and await in C# with an example."
});
The assistant's response appears progressively instead of being displayed only after generation finishes.
For a graphical application, the event handler can update a chat component or publish the received text to the UI layer. If the callback executes outside the UI thread, use the framework's dispatcher before modifying UI controls.
Also remember that session events can arrive asynchronously. Subscribe before sending the message so the application does not miss early response events.
Exposing a C# Method as a Custom Tool
The real value of an agent integration becomes clearer when the assistant can interact with application functionality.
Suppose you are building a developer assistant that needs to retrieve the current build status. You already have a C# method that can access this information. Instead of asking the model to invent an answer, expose the method as a custom tool.
The SDK supports custom tools through CopilotTool.DefineTool().
First, add the required namespaces:
using Microsoft.Copilot;
using Microsoft.Extensions.AI;
using System.ComponentModel;
Define a tool:
var getBuildStatus = CopilotTool.DefineTool(
([Description("The project name")] string projectName) =>
{
var status = projectName switch
{
"InventoryApi" => "Build successful",
"PaymentApi" => "Build failed",
_ => "Project not found"
};
return new
{
Project = projectName,
Status = status
};
},
factoryOptions: new AIFunctionFactoryOptions
{
Name = "get_build_status",
Description = "Get the latest build status for a project"
});
This example creates a tool named get_build_status.
The parameter description helps the model understand what value it should provide. The tool description explains its purpose and helps the agent decide when to use it.
The function returns a structured object containing the project name and build status.
In a production application, the implementation could call an Azure DevOps API, query a build database, or use an internal deployment service. The model does not need direct access to those systems. It only receives the information returned by the application-controlled tool.
Next, register the tool with the session:
await using var session =
await client.CreateSessionAsync(
new CreateSessionOptions
{
Model = "auto",
Tools = new SessionToolOptions
{
Definitions = [getBuildStatus]
}
});
The tool definition becomes available to the Copilot runtime for that session.
Now ask a question that requires the tool:
var response = await session.SendAndWaitAsync(
new MessageOptions
{
Prompt = "Check the build status of PaymentApi."
});
Console.WriteLine(response?.Data.Content);
The agent can recognize that the request requires build information, invoke get_build_status, and use the returned result to construct its response.
This is an important distinction between a traditional chat integration and an agent integration. A traditional chat application sends text to a model and displays the answer. An agent integration can also give the model controlled access to application operations.
Handling Tool Permissions
Custom tools can perform operations that affect real business data. A read-only tool that retrieves build information has a different risk level from a tool that deletes a project or updates a customer record.
The Copilot SDK provides permission handling through SessionPermissionOptions.
For a local demonstration where automatic approval is acceptable, the SDK provides PermissionHandler.ApproveAll:
await using var session =
await client.CreateSessionAsync(
new CreateSessionOptions
{
Model = "auto",
Permissions = new SessionPermissionOptions
{
OnRequest = PermissionHandler.ApproveAll
},
Tools = new SessionToolOptions
{
Definitions = [getBuildStatus]
}
});
This is convenient for a controlled example, but it should not be copied into a production application without understanding its consequences. ApproveAll automatically approves ordinary permission requests and is not appropriate when tools can modify files, execute commands, or access sensitive business operations. It is also not valid when managed settings are enabled.
For production systems, implement a permission handler that evaluates the requested operation, user identity, and application security rules. Keep sensitive operations behind explicit authorization checks, and require human approval when the business process demands it.
Tool permissions should not depend only on the model's decision. The application must enforce authorization independently of the prompt and generated response.
Organizing the Integration for a Real Application
The examples above keep everything in Program.cs to make the SDK workflow easy to understand. In a real application, the Copilot client, session management, and custom tools should be separated.
A practical structure could look like this:
CopilotDemo/
│
├── Program.cs
│
├── Copilot/
│ ├── CopilotService.cs
│ └── CopilotSessionManager.cs
│
├── Tools/
│ ├── BuildStatusTool.cs
│ ├── ProjectSearchTool.cs
│ └── RepositoryTool.cs
│
├── Models/
│ └── CopilotRequest.cs
│
└── Configuration/
└── CopilotOptions.cs
CopilotService can manage the client lifecycle and session creation. The session manager can keep conversations separate for different users. Tool classes can contain application-specific operations.
For an ASP.NET Core application, avoid creating a new runtime client for every HTTP request. Manage the client lifecycle at the application level and create or resume sessions according to the application's conversation model.
A multi-user service also needs to isolate sessions by authenticated user or tenant. Do not let one user's session identifier provide access to another user's conversation.
The SDK documentation also distinguishes between coding-agent mode and empty mode. For multi-user services, an explicitly configured empty mode can be a better foundation because the application opts into the capabilities it intends to expose instead of inheriting a broad coding-agent setup.
Important Considerations Before Production
The Copilot SDK simplifies agent integration, but it does not remove the need for normal application security and operational controls.
Authentication should be configured for the deployment environment. Avoid embedding long-lived tokens in source code or desktop application binaries. Store secrets in an appropriate secret-management system and restrict access to the credentials used by the runtime.
Session management also deserves attention. A session should have a clear owner, lifetime, and persistence strategy. Applications that create many sessions should monitor resource usage and clean up sessions when they are no longer needed.
Custom tools should perform their own input validation. A model-generated parameter is still untrusted input. Validate project names, file paths, record identifiers, and other values before passing them to databases or external services.
Finally, handle cancellation and failures. Runtime startup can fail because of missing runtime files, authentication problems, or unavailable services. Message processing can also fail or exceed application timeouts. Log useful diagnostic information without recording access tokens, private prompts, or sensitive tool results.
Conclusion
The GitHub Copilot SDK provides a practical way to integrate Copilot's agent runtime into C# applications. Developers can create a client, manage conversation sessions, send prompts, stream responses, and expose existing application methods as custom tools.
The most important benefit is that the application can combine an agent's reasoning capabilities with controlled access to existing business functionality. Instead of building a complete orchestration engine, developers can focus on the tools, permissions, and application workflows that make the assistant useful.
Start with a small integration, expose only the tools the application needs, and add session isolation, authentication, permission handling, and monitoring before moving into production.
Himanshu SharmaPosted Nov 30, 2026, 11:05 AM
This is a useful approach for integrating AI capabilities into existing C# applications without building the entire agent orchestration layer from scratch. I especially like the combination of session management, streaming responses, and custom tools, as these features can make an AI assistant more practical for real development workflows. The permission-handling section is also important because exposing application methods to an AI agent requires proper authorization and input validation. For production use, I would focus on session isolation, secure authentication, and controlled access to sensitive operations. Starting with a small use case and gradually expanding the available tools seems like a sensible way to build a reliable Copilot integration.