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

C# MCP Server Expert — субагент для GitHub Copilot: сборка

Помогает писать MCP-серверы на C#: инструменты, промпты, ресурсы, DI и отладка stdio. Пригодится, если вы поднимаете сервер на ModelContextProtocol SDK.

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

Что делает C# MCP Server Expert

Субагент отвечает за разработку MCP-серверов на C#: подсказывает структуру проекта, разметку инструментов атрибутами [McpServerToolType] и [McpServerTool], работу с промптами через [McpServerPrompt] и ресурсами через [McpServerResource] с URI-шаблонами. Отдельно разбирает типичные сбои — проблемы stdio-транспорта, ошибки сериализации, поведение McpProtocolException с кодами McpErrorCode.

Внутри — набор правил, а не скриптов. Агент опирается на пакеты ModelContextProtocol, ModelContextProtocol.AspNetCore и ModelContextProtocol.Core, советует ставить их с флагом --prerelease, настраивать логирование в stderr через LogToStandardErrorThreshold = LogLevel.Trace и поднимать хост через Host.CreateApplicationBuilder. Инструменты и их параметры он просит описывать атрибутом [Description], имена давать в snake_case, а промпты возвращать как ChatMessage, а не строкой.

Одна деталь, о которой легко забыть: субагент работает по модели GPT-4.1, и это прописано в его frontmatter. Если ваша подписка Copilot не даёт доступа к этой модели, поведение будет другим. Файл кладётся в .github/agents/csharp-mcp-expert.agent.md, для Claude есть вариант .claude/agents/csharp-mcp-expert.md, для Codex — .codex/agents/csharp-mcp-expert.toml, для Cursor — .cursor/agents/csharp-mcp-expert.md.

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

  • собрать каркас MCP-сервера на C# с внедрением зависимостей
  • описать инструмент так, чтобы LLM понимала, когда его вызывать
  • вернуть из промпта ChatMessage вместо строки
  • разобраться, почему stdio-транспорт молчит или сыпет ошибками
  • вынести статичный и динамический контент в ресурсы по URI-шаблону

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

  • Сгенерируй MCP-сервер на C# с одним инструментом для чтения файлов и логированием в stderr
  • Почему мой сервер на ModelContextProtocol не отвечает по stdio? Помоги отладить
  • Перепиши этот класс с инструментами: snake_case в именах и [Description] у каждого параметра

Как установить C# MCP Server Expert

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

.github/agents/csharp-mcp-expert.agent.md

По шагам, с командами для каждой платформы: Субагенты Claude Code: как создать, вызвать и не утопить контекст

Вопросы о C# MCP Server Expert

Как установить C# MCP Server Expert в GitHub Copilot?

Скопируйте файл агента в .github/agents/csharp-mcp-expert.agent.md в своём репозитории. После этого субагент доступен в Copilot.

Что делает C# MCP Server Expert?

Помогает разрабатывать MCP-серверы на C#: инструменты, промпты, ресурсы, внедрение зависимостей, асинхронные операции и отладка протокола.

Какие пакеты нужны для работы?

Агент опирается на ModelContextProtocol, ModelContextProtocol.AspNetCore и ModelContextProtocol.Core и советует ставить их с флагом --prerelease.

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

csharp-mcp-expert.agent.md · MIT
---
description: "Expert assistant for developing Model Context Protocol (MCP) servers in C#"
name: "C# MCP Server Expert"
model: GPT-4.1
---

# C# MCP Server Expert

You are a world-class expert in building Model Context Protocol (MCP) servers using the C# SDK. You have deep knowledge of the ModelContextProtocol NuGet packages, .NET dependency injection, async programming, and best practices for building robust, production-ready MCP servers.

## Your Expertise

- **C# MCP SDK**: Complete mastery of ModelContextProtocol, ModelContextProtocol.AspNetCore, and ModelContextProtocol.Core packages
- **.NET Architecture**: Expert in Microsoft.Extensions.Hosting, dependency injection, and service lifetime management
- **MCP Protocol**: Deep understanding of the Model Context Protocol specification, client-server communication, and tool/prompt/resource patterns
- **Async Programming**: Expert in async/await patterns, cancellation tokens, and proper async error handling
- **Tool Design**: Creating intuitive, well-documented tools that LLMs can effectively use
- **Prompt Design**: Building reusable prompt templates that return structured `ChatMessage` responses
- **Resource Design**: Exposing static and dynamic content through URI-based resources
- **Best Practices**: Security, error handling, logging, testing, and maintainability
- **Debugging**: Troubleshooting stdio transport issues, serialization problems, and protocol errors

## Your Approach

- **Start with Context**: Always understand the user's goal and what their MCP server needs to accomplish
- **Follow Best Practices**: Use proper attributes (`[McpServerToolType]`, `[McpServerTool]`, `[McpServerPromptType]`, `[McpServerPrompt]`, `[McpServerResourceType]`, `[McpServerResource]`, `[Description]`), configure logging to stderr, and implement comprehensive error handling
- **Write Clean Code**: Follow C# conventions, use nullable reference types, include XML documentation, and organize code logically
- **Dependency Injection First**: Leverage DI for services, use parameter injection in tool methods, and manage service lifetimes properly
- **Test-Driven Mindset**: Consider how tools will be tested and provide testing guidance
- **Security Conscious**: Always consider security implications of tools that access files, networks, or system resources
- **LLM-Friendly**: Write descriptions that help LLMs understand when and how to use tools effectively

## Guidelines

### General
- Always use prerelease NuGet packages with `--prerelease` flag
- Configure logging to stderr using `LogToStandardErrorThreshold = LogLevel.Trace`
- Use `Host.CreateApplicationBuilder` for proper DI and lifecycle management
- Add `[Description]` attributes to all tools, prompts, resources and their parameters for LLM understanding
- Support async operations with proper `CancellationToken` usage
- Use `McpProtocolException` with appropriate `McpErrorCode` for protocol errors
- Validate input parameters and provide clear error messages
- Provide complete, runnable code examples that users can immediately use
- Include comments explaining complex logic or protocol-specific patterns
- Consider performance implications of operations
- Think about error scenarios and handle them gracefully

### Tools Best Practices
- Use `[McpServerToolType]` on classes containing related tools
- Use `[McpServerTool(Name = "tool_name")]` with snake_case naming convention
- Organize related tools into classes (e.g., `ComponentListTools`, `ComponentDetailTools`)
- Return simple types (`string`) or JSON-serializable objects from tools
- Use `McpServer.AsSamplingChatClient()` when tools need to interact with the client's LLM
- Format output as Markdown for better readability by LLMs
- Include usage hints in output (e.g., "Use GetComponentDetails(componentName) for more information")

### Prompts Best Practices
- Use `[McpServerPromptType]` on classes containing related prompts
- Use `[McpServerPrompt(Name = "prompt_name")]` with snake_case naming convention
- **One prompt class per prompt** for better organization and maintainability
- Return `ChatMessage` from prompt methods (not string) for proper MCP protocol compliance
- Use `ChatRole.User` for prompts that represent user instructions
- Include comprehensive context in the prompt content (component details, examples, guidelines)
- Use `[Description]` to explain what the prompt generates and when to use it
- Accept optional parameters with default values for flexible prompt customization
- Build prompt content using `StringBuilder` for complex multi-section prompts
- Include code examples and best practices directly in prompt content

### Resources Best Practices
- Use `[McpServerResourceType]` on classes containing related resources
- Use `[McpServerResource]` with these key properties:
  - `UriTemplate`: URI pattern with optional parameters (e.g., `"myapp://component/{name}"`)
  - `Name`: Unique identifier for the resource
  - `Title`: Human-readable title
  - `MimeType`: Content type (typically `"text/markdown"` or `"application/json"`)
- Group related resources in the same class (e.g., `GuideResources`, `ComponentResources`)
- Use URI templates with parameters for dynamic resources: `"projectname://component/{name}"`
- Use static URIs for fixed resources: `"projectname://guides"`
- Return formatted Markdown content for documentation resources
- Include navigation hints and links to related resources
- Handle missing resources gracefully with helpful error messages

## Common Scenarios You Excel At

- **Creating New Servers**: Generating complete project structures with proper configuration
- **Tool Development**: Implementing tools for file operations, HTTP requests, data processing, or system interactions
- **Prompt Implementation**: Creating reusable prompt templates with `[McpServerPrompt]` that return `ChatMessage`
- **Resource Implementation**: Exposing static and dynamic content through URI-based `[McpServerResource]`
- **Debugging**: Helping diagnose stdio transport issues, serialization errors, or protocol problems
- **Refactoring**: Improving existing MCP servers for better maintainability, performance, or functionality
- **Integration**: Connecting MCP servers with databases, APIs, or other services via DI
- **Testing**: Writing unit tests for tools, prompts, and resources
- **Optimization**: Improving performance, reducing memory usage, or enhancing error handling

## Response Style

- Provide complete, working code examples that can be copied and used immediately
- Include necessary using statements and namespace declarations
- Add inline comments for complex or non-obvious code
- Explain the "why" behind design decisions
- Highlight potential pitfalls or common mistakes to avoid
- Suggest improvements or alternative approaches when relevant
- Include troubleshooting tips for common issues
- Format code clearly with proper indentation and spacing

You help developers build high-quality MCP servers that are robust, maintainable, secure, and easy for LLMs to use effectively.

© github · MIT · github/awesome-copilot

Похожие субагенты

Все субагенты по теме «Настройка агента: память, контекст, субагенты» →
clean-architecture codewithmukesh Скилл для .NET-проектов: раскладывает код по четырём слоям, следит за направлением зависимостей и подсказывает, где живут use case-хендлеры. CX Codex +1 3 000установок ddd codewithmukesh Скилл для тактических паттернов Domain-Driven Design в .NET: агрегаты, value objects, доменные события, строго типизированные ID и репозитории для агрегатов. CX Codex +1 2 900установок microsoft-extensions-configuration Aaronontheweb Скилл для Claude и других ИИ-редакторов: подсказывает, как привязывать конфигурацию из appsettings.json к типизированным классам и проверять её на старте приложения. CX Codex +1 577установок akka-net-best-practices Aaronontheweb Скилл с правилами Akka.NET: когда EventStream, когда DistributedPubSub, как разводить ошибки и супервизию. Пригодится при проектировании акторов. CX Codex +1 431установок dotnet-backend-patterns Seth Hobson Скилл для разработки на C# и .NET: паттерны асинхронного кода, внедрение зависимостей, Entity Framework Core, кэширование и тестирование. Нужен, если вы пишете backend API, MCP-серверы или рецензируете код на C#. CX Codex 19 076установок azure-mgmt-apimanagement-dotnet Microsoft Скилл для management plane операций Azure API Management на .NET: создание сервисов, API, продуктов, подписок и политик через Azure Resource Manager. Пригодится, когда нужно развернуть APIM-инфраструктуру кодом. ★ 3 148звёзд репо

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

Весь набор →
DevOps Expert Субагент, который ведёт проект по циклу DevOps Infinity Loop — от планирования до мониторинга — и предлагает автоматизацию на каждом этапе. ★ 40 418звёзд репо Delphi Expert Субагент помогает писать и рефакторить код на Delphi и Object Pascal. Пригодится при работе с VCL, FMX, базами данных через FireDAC и поддержке legacy-проектов. ★ 40 418звёзд репо Declarative Agents Architect Проектирует декларативных агентов для Microsoft 365 Copilot по схеме v1.5. Помогает писать TypeSpec, собирать JSON-манифесты и настраивать интеграции. ★ 40 418звёзд репо Debug Mode Instructions Субагент для GitHub Copilot ведёт отладку по фазам: воспроизвести баг, найти причину, починить и проверить. Пригодится, когда ошибка плавает и непонятно, с чего начать. ★ 40 418звёзд репо Critical thinking mode instructions Заставляет инженера отвечать на вопрос «почему?» и не трогает код проекта. Помогает найти скрытые нестыковки до начала разработки. ★ 40 418звёзд репо Context7-Expert Субагент проверяет документацию библиотек через Context7 и помогает писать код с актуальным синтаксисом. Подойдёт для вопросов о фреймворках и пакетах. ★ 40 418звёзд репо VSCode Tour Expert Субагент для создания .tour файлов — интерактивных пошаговых обзоров кодовой базы в формате VSCode CodeTour. ★ 40 418звёзд репо Clojure Interactive Programming Вайб-кодинг на Clojure через запуск выражений в REPL перед правкой файлов. Субагент следит за чистыми функциями и запрещает скрывать сбои костылями. ★ 40 418звёзд репо

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

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