К основному содержанию
правило официальный · GitHub

csharp-mcp-server — правило для GitHub Copilot

Правило задаёт практики разработки MCP-серверов на C# и подключается к файлам .cs и .csproj. Оно пригодится при создании серверов на SDK Model Context Protocol.

Установить в GitHub Copilot · Вручную: положить файлы Все способы и платформы ↓
.github/instructions/csharp-mcp-server.instructions.md
Открыть на GitHub

Что делает csharp-mcp-server

Правило применяется к файлам .cs и .csproj и подсказывает, как строить MCP-серверы на C#. Оно охватывает выбор пакетов ModelContextProtocol, ModelContextProtocol.AspNetCore и ModelContextProtocol.Core, настройку DI через Microsoft.Extensions.Hosting, регистрацию инструментов и публикацию промптов с помощью атрибутов SDK.

В инструкциях есть шаблоны для stdio-транспорта, автоматического поиска инструментов через WithToolsFromAssembly(), асинхронных методов, CancellationToken, sampling-запросов и обработки ошибок через McpProtocolException. Серверы можно проверять клиентом McpClient. При stdio логирование нужно направлять в stderr, иначе сообщения могут вмешаться в транспорт.

Какие задачи решает

  • собрать MCP-сервер на C# со stdio-транспортом
  • зарегистрировать инструменты через атрибуты SDK
  • подключить HttpClient и другие сервисы через DI
  • обработать ошибки протокола с McpProtocolException
  • проверить сервер клиентом McpClient

Примеры запросов агенту

  • Создай MCP-сервер на C# со stdio-транспортом и настрой логирование через LogToStandardErrorThreshold.
  • Добавь инструмент с [McpServerTool], описанием параметров и поддержкой CancellationToken.
  • Проверь этот MCP-сервер через McpClient и исправь ошибки регистрации инструментов.

Как установить csharp-mcp-server

Вручную: положить файлы

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

Поле applyTo задаёт, к каким файлам применять

По шагам, с командами для каждой платформы: AGENTS.md и CLAUDE.md: что это, кто читает и какой выбрать

Вопросы о csharp-mcp-server

Как установить csharp-mcp-server в GitHub Copilot?

Поместите файл правила в .github/instructions/csharp-mcp-server.instructions.md.

Что делает csharp-mcp-server?

Правило объясняет, как создавать MCP-серверы на C# с SDK Model Context Protocol: подключать нужный NuGet-пакет, объявлять инструменты и промпты, настраивать DI и stdio.

К каким файлам применяется правило csharp-mcp-server?

Оно применяется к файлам .cs и .csproj.

Исходный текст

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

Похожие правила IDE

Все правила IDE по теме «Языки программирования» →

Из того же набора732

Весь набор →
dataverse-python-agentic-workflows Правило для GitHub Copilot с концепциями агентных сценариев на Dataverse SDK для Python: автономные агенты, MCP, A2A и проверка качества данных. ★ 40 418звёзд репо dart-n-flutter Правило задаёт рекомендации для Dart и Flutter в файлах .dart: стиль, документацию, использование языковых возможностей и дизайн API. ★ 40 418звёзд репо csharp Правило задаёт Copilot стиль C#-кода: именование, nullable-типы, форматирование и работу с ASP.NET Core. Пригодится, если агент пишет по-разному в каждом файле. ★ 40 418звёзд репо csharp-razorpages Задаёт стандарты разработки на ASP.NET Core Razor Pages для файлов .cshtml и .cshtml.cs. Помогает Copilot генерировать безопасные обработчики и чистые PageModel. ★ 40 418звёзд репо cpp-language-service-tools Правило направляет GitHub Copilot к инструментам IntelliSense для поиска определений, ссылок и связей вызовов в C++. Пригодится при рефакторинге и изменении сигнатур. ★ 40 418звёзд репо copilot-thought-logging Правило заставляет Copilot вести файл Copilot-Processing.md с планом и отметками о выполнении, чтобы вы видели ход работы и могли его поправить. ★ 40 418звёзд репо copilot-sdk-python Инструкция для GitHub Copilot по разработке Python-приложений на базе github-copilot-sdk. Помогает писать асинхронный код сессий, регистрировать инструменты и обрабатывать стриминг. ★ 40 418звёзд репо copilot-sdk-nodejs Правило задаёт паттерны для Node.js и TypeScript-приложений на GitHub Copilot SDK: от запуска клиента до сессий и событий. ★ 40 418звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой