Skip to main content
rule official · GitHub

csharp-mcp-server — GitHub Copilot rule

This rule guides C# MCP server work with the Model Context Protocol SDK. It fits projects where tools, prompts, DI, and stdio transport need a consistent setup.

Install into GitHub Copilot · Manually: put the files in place All methods and platforms ↓
.github/instructions/csharp-mcp-server.instructions.md
Open on GitHub

What csharp-mcp-server does

The rule applies to .cs and .csproj files and lays out a C# approach for MCP servers. It covers the ModelContextProtocol, ModelContextProtocol.AspNetCore, and ModelContextProtocol.Core packages, project structure with Microsoft.Extensions.Hosting, dependency injection, and SDK attributes for tools and prompts.

Its patterns include stdio transport, assembly-based tool discovery with WithToolsFromAssembly(), async methods with CancellationToken, sampling through McpServer.AsSamplingChatClient(), and protocol errors via McpProtocolException. You can test a server with McpClient or another compliant MCP client. For stdio transport, logs must go to stderr so they do not corrupt the protocol stream.

What it helps with

  • build a C# MCP server over stdio
  • expose methods as SDK tools with attributes
  • inject HttpClient and other services into tools
  • return protocol errors with McpProtocolException
  • test an MCP server through McpClient

Example prompts for the agent

  • Build a C# MCP server over stdio and configure logging with LogToStandardErrorThreshold.
  • Add an MCP tool with [McpServerTool], parameter descriptions, and CancellationToken support.
  • Test this server with McpClient and fix any tool registration errors.

How to install csharp-mcp-server

Manually: put the files in place

.github/instructions/csharp-mcp-server.instructions.md

The applyTo field sets which files it applies to

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about csharp-mcp-server

How do I install csharp-mcp-server in GitHub Copilot?

Place the rule file at .github/instructions/csharp-mcp-server.instructions.md.

What does csharp-mcp-server do?

It guides C# MCP server development with the Model Context Protocol SDK, including package selection, tool and prompt attributes, DI, stdio transport, and error handling.

Which files does the csharp-mcp-server rule apply to?

It applies to .cs and .csproj files.

Source text

csharp-mcp-server.instructions.md · MIT
---
description: 'Instructions for building Model Context Protocol (MCP) servers using the C# SDK'
applyTo: '**/*.cs, **/*.csproj'
---

# C# MCP Server Development

## Instructions

- Use the **ModelContextProtocol** NuGet package (prerelease) for most projects: `dotnet add package ModelContextProtocol --prerelease`
- Use **ModelContextProtocol.AspNetCore** for HTTP-based MCP servers
- Use **ModelContextProtocol.Core** for minimal dependencies (client-only or low-level server APIs)
- Always configure logging to stderr using `LogToStandardErrorThreshold = LogLevel.Trace` to avoid interfering with stdio transport
- Use the `[McpServerToolType]` attribute on classes containing MCP tools
- Use the `[McpServerTool]` attribute on methods to expose them as tools
- Use the `[Description]` attribute from `System.ComponentModel` to document tools and parameters
- Support dependency injection in tool methods - inject `McpServer`, `HttpClient`, or other services as parameters
- Use `McpServer.AsSamplingChatClient()` to make sampling requests back to the client from within tools
- Expose prompts using `[McpServerPromptType]` on classes and `[McpServerPrompt]` on methods
- For stdio transport, use `WithStdioServerTransport()` when building the server
- Use `WithToolsFromAssembly()` to auto-discover and register all tools from the current assembly
- Tool methods can be synchronous or async (return `Task` or `Task<T>`)
- Always include comprehensive descriptions for tools and parameters to help LLMs understand their purpose
- Use `CancellationToken` parameters in async tools for proper cancellation support
- Return simple types (string, int, etc.) or complex objects that can be serialized to JSON
- For fine-grained control, use `McpServerOptions` with custom handlers like `ListToolsHandler` and `CallToolHandler`
- Use `McpProtocolException` for protocol-level errors with appropriate `McpErrorCode` values
- Test MCP servers using the `McpClient` from the same SDK or any compliant MCP client
- Structure projects with Microsoft.Extensions.Hosting for proper DI and lifecycle management

## Best Practices

- Keep tool methods focused and single-purpose
- Use meaningful tool names that clearly indicate their function
- Provide detailed descriptions that explain what the tool does, what parameters it expects, and what it returns
- Validate input parameters and throw `McpProtocolException` with `McpErrorCode.InvalidParams` for invalid inputs
- Use structured logging to help with debugging without polluting stdout
- Organize related tools into logical classes with `[McpServerToolType]`
- Consider security implications when exposing tools that access external resources
- Use the built-in DI container to manage service lifetimes and dependencies
- Implement proper error handling and return meaningful error messages
- Test tools individually before integrating with LLMs

## Common Patterns

### Basic Server Setup
```csharp
var builder = Host.CreateApplicationBuilder(args);
builder.Logging.AddConsole(options => 
    options.LogToStandardErrorThreshold = LogLevel.Trace);
builder.Services
    .AddMcpServer()
    .WithStdioServerTransport()
    .WithToolsFromAssembly();
await builder.Build().RunAsync();
```

### Simple Tool
```csharp
[McpServerToolType]
public static class MyTools
{
    [McpServerTool, Description("Description of what the tool does")]
    public static string ToolName(
        [Description("Parameter description")] string param) => 
        $"Result: {param}";
}
```

### Tool with Dependency Injection
```csharp
[McpServerTool, Description("Fetches data from a URL")]
public static async Task<string> FetchData(
    HttpClient httpClient,
    [Description("The URL to fetch")] string url,
    CancellationToken cancellationToken) =>
    await httpClient.GetStringAsync(url, cancellationToken);
```

### Tool with Sampling
```csharp
[McpServerTool, Description("Analyzes content using the client's LLM")]
public static async Task<string> Analyze(
    McpServer server,
    [Description("Content to analyze")] string content,
    CancellationToken cancellationToken)
{
    var messages = new ChatMessage[]
    {
        new(ChatRole.User, $"Analyze this: {content}")
    };
    return await server.AsSamplingChatClient()
        .GetResponseAsync(messages, cancellationToken: cancellationToken);
}
```

© github · MIT · github/awesome-copilot

Similar IDE rules

All IDE rules for Programming languages →

From the same set732

The whole set →
dataverse-python-agentic-workflows A GitHub Copilot rule covering agentic workflows with the Dataverse SDK for Python: autonomous agents, MCP, A2A and data quality checks. ★ 40,418repo stars dart-n-flutter This rule guides Dart and Flutter work in .dart files, covering code style, documentation, language usage, and API design. ★ 40,418repo stars csharp A rule that pins Copilot to one C# style: naming, nullable types, formatting and ASP.NET Core patterns. Useful when the agent writes differently in every file. ★ 40,418repo stars csharp-razorpages Configures GitHub Copilot to write idiomatic Razor Pages across .cshtml and .cshtml.cs files. It enforces PageModel conventions, secure model binding, and clean data queries. ★ 40,418repo stars cpp-language-service-tools This rule guides GitHub Copilot to use C++ IntelliSense tools for definitions, references, and call relationships. It helps when refactoring or changing function signatures. ★ 40,418repo stars copilot-thought-logging This rule makes Copilot keep a Copilot-Processing.md file with a plan and progress marks, so you can watch the run and steer it. ★ 40,418repo stars copilot-sdk-python Coding instructions for GitHub Copilot when building Python apps with github-copilot-sdk. Guides async client initialization, session setup, tools, and streaming events. ★ 40,418repo stars copilot-sdk-nodejs Guidance for Node.js and TypeScript apps built with the GitHub Copilot SDK, covering client startup, sessions, events, and streamed output. ★ 40,418repo stars

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor