К основному содержанию
скилл CX Codex

mcp · managedcode — скилл для Claude Code: что делает и как установить

Помогает создавать и подключать MCP-серверы и клиенты на C# в среде .NET 8+, настраивая stdio, Streamable HTTP и обмен инструментами.

MIT ★ 521 обновлён 2026-10-29

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add managedcode/dotnet-skills --skill mcp -a claude-code
Открыть на GitHub

Что делает mcp

Скилл содержит правила архитектуры и примеры кода для официального MCP C# SDK версии v2.2. Он помогает выбрать подходящий пакет (ModelContextProtocol, ModelContextProtocol.Core или ModelContextProtocol.AspNetCore) в зависимости от роли приложения: локальный процесс или удалённый сервис.

Внутри разобрана работа с транспортами stdio и Streamable HTTP, регистрация инструментов через атрибуты, чтение ресурсов, передача промптов и согласование возможностей протокола редакции 2026-07-28. Также даны инструкции по пробросу найденных инструментов в IChatClient и управлению сессиями в ASP.NET Core.

Без рантайма .NET 8+ запустить этот стек не получится: официальный SDK жёстко завязан на современные версии платформы.

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

  • настроить stdio или Streamable HTTP транспорт для MCP в .NET
  • реализовать инструменты, промпты и ресурсы через официальный C# SDK
  • подключить .NET-клиент к внешнему MCP-серверу и связать вызовы с IChatClient
  • сконфигурировать сессии и авторизацию для удалённого сервера на ASP.NET Core

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

  • Настрой локальный MCP-сервер на C# со stdio транспортом и зарегистрируй инструмент
  • Подключи ASP.NET Core к MCP через Streamable HTTP с поддержкой возобновления сессий
  • Добавь клиент MCP на .NET и пробрось полученные инструменты в IChatClient

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

1Через Skills CLI (Vercel)

npx skills add managedcode/dotnet-skills --skill mcp -a claude-code

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

~/.claude/skills/mcp/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/mcp/

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

Вопросы о mcp

Как установить mcp в Claude Code?

Выполните в терминале команду npx skills add managedcode/dotnet-skills --skill mcp -a claude-code.

Что делает этот скилл?

Он направляет ИИ-агента при написании кода клиентов и серверов Model Context Protocol на .NET, подсказывая корректные API официального C# SDK.

Какие пакеты и версии рантайма требуются для работы?

Нужен .NET 8 или новее. Скилл ориентирован на SDK v2.2 и пакеты ModelContextProtocol, ModelContextProtocol.Core либо ModelContextProtocol.AspNetCore.

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

SKILL.md · MIT
---
name: mcp
description: "Build or consume Model Context Protocol (MCP) servers and clients in .NET using the official MCP C# SDK, including stdio, Streamable HTTP, tools, prompts, resources, and capability negotiation. USE FOR: .NET MCP servers or clients; stdio versus HTTP transport choices; tools, resources, prompts, completions, and capability negotiation. DO NOT USE FOR: unrelated stacks; generic tasks that do not need this specific guidance. INVOKES: inspect the repository context, edit targeted files, and run relevant build, test, lint, or validation commands when changes are made."
compatibility: "Requires the official MCP C# SDK packages (`ModelContextProtocol.Core`, `ModelContextProtocol`, or `ModelContextProtocol.AspNetCore`) on .NET 8+; current guidance targets the v2.2 SDK and MCP 2026-07-28."
---

# MCP C# SDK for .NET

## Trigger On

- building or consuming MCP servers from a .NET application or library
- choosing between stdio and HTTP transport for MCP
- exposing tools, resources, prompts, completions, or logging to an MCP host
- connecting a .NET app to an existing MCP server and passing discovered tools into `IChatClient`
- bootstrapping a minimal MCP client/server from the `.NET AI` quickstarts or publishing a server to the MCP Registry
- implementing capability-aware flows such as roots, sampling, elicitation, subscriptions, session resumption, or enterprise managed authorization

## Use This Skill Instead Of

- Use `mcp` when **protocol interoperability** is the requirement.
- Use `microsoft-extensions-ai` when you only need model/provider abstraction or local tool orchestration without the MCP wire protocol.
- Use `microsoft-agent-framework` when the main problem is agent orchestration; combine it with `mcp` only when those agents must consume or expose MCP endpoints.
- Use the `.NET AI` quickstarts for the very first vertical slice, then come back here to harden transport, capability negotiation, publishing, and host interoperability.

## Documentation

- [MCP C# SDK overview](https://csharp.sdk.modelcontextprotocol.io/)
- [Getting Started](https://csharp.sdk.modelcontextprotocol.io/concepts/getting-started.html)
- [API reference](https://csharp.sdk.modelcontextprotocol.io/api/ModelContextProtocol.html)
- [Conceptual docs](https://csharp.sdk.modelcontextprotocol.io/concepts/index.html)
- [Versioning policy](https://csharp.sdk.modelcontextprotocol.io/versioning.html)
- [Experimental APIs](https://csharp.sdk.modelcontextprotocol.io/experimental.html)
- [MCP C# SDK repository](https://github.com/modelcontextprotocol/csharp-sdk)
- [Model Context Protocol specification](https://modelcontextprotocol.io/specification/)

## References

Load only what the task needs:

- [references/patterns.md](references/patterns.md) - current server/client patterns, transports, capabilities, filters, and chat-client integration
- [references/security.md](references/security.md) - safe error handling, auth boundaries, stdio logging hygiene, and defensive tool/resource patterns

## Package Selection

| Package | Choose when |
|---------|-------------|
| `ModelContextProtocol.Core` | You only need a client or low-level server APIs and want the smallest dependency set. |
| `ModelContextProtocol` | You want the main SDK package with hosting, DI, attribute discovery, and stdio server support. Start here for most projects. |
| `ModelContextProtocol.AspNetCore` | You are hosting a remote MCP server in ASP.NET Core over HTTP. This includes the main package. |

## Transport Selection

| Transport | Use when | Notes |
|-----------|----------|-------|
| `StdioClientTransport` / `WithStdioServerTransport()` | The MCP server should run as a local child process. | Best for local tooling and editor/agent integrations. |
| `HttpClientTransport` + `HttpTransportMode.StreamableHttp` | The server is remote or should be reachable over HTTP. | Recommended HTTP transport; supports streaming and session resumption. |
| `HttpTransportMode.Sse` | You must connect to an older SSE-only server. | Legacy compatibility only; do not choose this for new servers. |

## Current v2.2 Notes

- The August 2026 `.NET AI` MCP documentation separates a getting-started hub, client and server quickstarts, MCP Registry publishing, and a server-resource index. Use those pages to bootstrap a vertical slice, then return to the C# SDK docs here for exact transport, capability, authorization, and lifecycle behavior.
- SDK `v2.0.0` aligns with MCP `2026-07-28`: HTTP is stateless by default, clients negotiate with `server/discover` before falling back to legacy `initialize`, Tasks move to `ModelContextProtocol.Extensions.Tasks`, and Roots, Sampling, and Logging are deprecated for the new protocol. Set `HttpServerTransportOptions.Stateless = false` only for an intentional stateful compatibility requirement.
- SDK `v2.1.0` adds an opt-in `subscriptions/listen` server handler, keeps AutoDetect usable after a provisional SSE failure, preserves HTTP status codes across target frameworks, and falls back to `initialize` when `server/discover` fails at the HTTP layer. Add custom notification streams only when both peers negotiate the extension.
- SDK `v2.2.0` adds `HttpServerSessionMode` so one ASP.NET Core endpoint can serve stateful and stateless clients across the MCP `2025-11-25` and `2026-07-28` protocol versions. Choose the mode explicitly, test both negotiated paths when compatibility matters, and upgrade before working around malformed percent-encoded request headers because the release fixes that decoding failure.
- Before moving from `v1.4.x`, update structured-result consumers to accept non-object values directly, require `Tool.inputSchema` in custom payloads, move Tasks to the extension package, and test PKCE S256 plus issuer validation in OAuth metadata.
- Enterprise managed authorization now has an SDK surface through `IdentityAssertionGrantProvider` for the Identity Assertion Authorization Grant flow. Use it only when the enterprise SSO and MCP authorization-server contract is part of the actual scenario.
- `StdioClientTransportOptions.InheritEnvironmentVariables` controls whether child-process MCP servers inherit the parent environment. Set it intentionally when launching untrusted or third-party servers.
- Streamable HTTP session `DELETE` is hardened to require the same authenticated user that opened the session. Do not build custom session cleanup paths that bypass that authorization check.
- Stdio transport no longer logs child-process environment variables at trace level, but server authors should still treat environment variables as secrets.

```mermaid
flowchart LR
    A["Need MCP interoperability in .NET"] --> B{"Role?"}
    B -->|"Expose MCP surface"| C{"Where will it run?"}
    B -->|"Consume an MCP server"| D{"Transport?"}
    C -->|"Local child process"| E["ModelContextProtocol\nAddMcpServer()\nWithStdioServerTransport()"]
    C -->|"Remote HTTP endpoint"| F["ModelContextProtocol.AspNetCore\nAddMcpServer()\nWithHttpTransport()\nMapMcp()"]
    D -->|"stdio"| G["StdioClientTransport\nMcpClient.CreateAsync()"]
    D -->|"HTTP"| H["HttpClientTransport\nAutoDetect or StreamableHttp"]
    E --> I["Register tools/resources/prompts"]
    F --> I
    G --> J["Check ServerCapabilities\nbefore optional features"]
    H --> J
```

## Workflow

1. Pick the package and transport first.
   - Local child-process server: `ModelContextProtocol` + `WithStdioServerTransport()`.
   - Remote server: `ModelContextProtocol.AspNetCore` + `WithHttpTransport()` + `MapMcp()`.
   - Client-only app: start with `ModelContextProtocol` or `ModelContextProtocol.Core`.
   - Registry distribution: pair a minimal server with the MCP Registry publishing flow only after the server contract is stable.

2. Model the MCP surface explicitly.
   - Tools: `[McpServerToolType]` + `[McpServerTool]`
   - Resources: `[McpServerResourceType]` + `[McpServerResource]`
   - Prompts: `[McpServerPromptType]` + `[McpServerPrompt]`
   - Use custom handlers or filters only for cross-cutting behavior, protocol extensions, or advanced routing.

3. Prefer attribute discovery for straightforward servers.

```csharp
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;
using System.ComponentModel;

var builder = Host.CreateApplicationBuilder(args);
builder.Logging.AddConsole(options =>
{
    options.LogToStandardErrorThreshold = LogLevel.Trace;
});

builder.Services
    .AddMcpServer()
    .WithStdioServerTransport()
    .WithToolsFromAssembly();

await builder.Build().RunAsync();

[McpServerToolType]
public static class EchoTool
{
    [McpServerTool, Description("Echoes the message back to the client.")]
    public static string Echo(string message) => $"hello {message}";
}
```

4. For HTTP servers, use the ASP.NET Core transport and map the endpoint directly.

```csharp
using ModelContextProtocol.Server;
using System.ComponentModel;

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddMcpServer()
    .WithHttpTransport()
    .WithToolsFromAssembly();

var app = builder.Build();
app.MapMcp("/mcp");
app.Run();

[McpServerToolType]
public static class EchoTool
{
    [McpServerTool, Description("Echoes the message back to the client.")]
    public static string Echo(string message) => $"hello {message}";
}
```

5. When consuming a server, use `McpClient.CreateAsync(...)` and stay capability-aware.

```csharp
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;

var transport = new StdioClientTransport(new StdioClientTransportOptions
{
    Name = "Everything",
    Command = "npx",
    Arguments = ["-y", "@modelcontextprotocol/server-everything"],
});

await using var client = await McpClient.CreateAsync(transport);

IList<McpClientTool> tools = await client.ListToolsAsync();

if (client.ServerCapabilities.Prompts is not null)
{
    var prompts = await client.ListPromptsAsync();
}
```

6. Treat optional features as negotiated capabilities, not assumptions.
   - Client capabilities: configure `McpClientOptions.Capabilities` for roots, sampling, and elicitation.
   - Server capabilities are inferred from registered features.
   - Check `client.ServerCapabilities` before using completions, logging, prompt list-change notifications, or resource subscriptions.
   - Use `client.NegotiatedProtocolVersion` or `server.NegotiatedProtocolVersion` only when version-specific behavior matters.

7. Keep HTTP guidance current.
   - Streamable HTTP is the recommended transport for remote servers.
   - `MapMcp()` also serves SSE compatibility endpoints for older clients.
   - HTTP clients can use `AutoDetect` by default, or force `StreamableHttp` / `Sse`.
   - Session resumption is available for Streamable HTTP through `McpClient.ResumeSessionAsync(...)`.
   - For authenticated Streamable HTTP sessions, cleanup and resume operations must preserve the same user boundary.

8. Treat the `.NET AI` MCP quickstarts as bootstrap examples.
   - `build-mcp-client` and `build-mcp-server` are good starting points when the surrounding app is still MEAI-centric.
   - `publish-mcp-registry` is the distribution step, not the design step. Stabilize the protocol surface before publishing.

9. Respect current error and serialization rules.
   - Tool exceptions normally come back as `CallToolResult.IsError == true`.
   - Throw `McpProtocolException` only for protocol-level JSON-RPC failures.
   - `McpClientTool` inherits from `AIFunction`, so discovered tools can be passed directly into `IChatClient`.
   - Experimental APIs use `MCPEXP...` diagnostics; suppress them intentionally, not globally by accident.
   - If you use a custom `JsonSerializerContext`, prepend `McpJsonUtilities.DefaultOptions.TypeInfoResolver` so MCP protocol types keep the SDK's contract.

## Anti-Patterns To Avoid

| Anti-pattern | Why it causes trouble | Better approach |
|--------------|-----------------------|-----------------|
| Picking HTTP transport for a purely local child-process scenario | Adds unnecessary hosting, auth, and deployment surface | Use stdio for local/editor-hosted integrations |
| Treating SSE as the default remote transport | Locks new work to legacy behavior | Prefer Streamable HTTP and keep SSE only for backward compatibility |
| Writing tools without `[Description]` metadata | Hosts and models lose schema clarity | Describe tool purpose and parameters explicitly |
| Returning huge binary/text payloads from every tool call | Bloats context and slows hosts | Return focused content and move large data to resources |
| Logging to stdout on stdio servers | Corrupts the protocol stream | Send logs to stderr |
| Assuming prompts/resources/logging/completions exist | Breaks against partial implementations | Check negotiated capabilities first |
| Using filters for normal business logic | Makes handlers opaque and hard to reason about | Keep filters for cross-cutting policy, audit, or protocol plumbing |

## Deliver

- a correctly packaged MCP server or client that matches the deployment topology
- explicit tool/resource/prompt definitions with descriptions and bounded payloads
- capability-aware handling for optional MCP features
- validation notes for transport, auth boundary, and host/client interoperability

## Validate

- chosen package matches the topology: `Core`, `ModelContextProtocol`, or `AspNetCore`
- stdio servers do not write logs or diagnostics to stdout
- HTTP servers use `MapMcp()` and are tested at the final route, for example `/mcp`
- tools, resources, and prompts use current `[McpServer*]` attributes or documented handler/filter alternatives
- client code checks `ServerCapabilities` before using subscriptions, completions, logging, or prompt/resource list-change flows
- Streamable HTTP is the default for new remote servers; SSE is used only for legacy compatibility
- experimental APIs and custom serialization settings are reviewed intentionally rather than copied blindly

© managedcode · MIT · managedcode/dotnet-skills

Похожие скиллы

Все скиллы по теме «Настройка агента: память, контекст, субагенты» →

Сначала — mcp от других авторов.

mcp vercel-labs Скилл помогает собирать MCP-серверы с интерактивными json-render UI для Claude, ChatGPT, Cursor и VS Code. CX Codex +1 5 900установок csharp-mcp-server официальный github Правило csharp-mcp-server задаёт практики разработки MCP-серверов на C# и подключается к файлам .cs и .csproj. Оно пригодится при создании серверов на SDK Model Context Protocol. CX Codex +1 ★ 41 430звёзд репо configure-auth dotnet Скилл configure-auth настраивает аутентификацию и авторизацию в Blazor Web App с учётом режимов рендеринга. Помогает подружить интерактивные компоненты с ASP.NET Core Identity. CX Codex +1 4 200установок api-versioning codewithmukesh Скилл api-versioning направляет агента при версионировании ASP.NET Core API через библиотеку Asp.Versioning. Помогает настроить пути, заголовки и мягкую депрекацию устаревших версий. CX Codex +1 4 000установок create-datadriven-aspnetcore dotnet Скилл create-datadriven-aspnetcore генерирует CRUD-код для ASP.NET Core без CLI-генераторов. Создаёт Razor Pages, Blazor-компоненты, контроллеры или Minimal API под стиль проекта и схему EF Core. CX Codex +1 3 900установок dotnet-security-owasp wshaddix Скилл dotnet-security-owasp находит уязвимости OWASP Top 10 в проектах на .NET и подсказывает безопасные паттерны кода. Пригодится при аудите API и контроллеров ASP.NET Core. CX Codex +1 175установок ASP.NET Core Debugger — MCP Server for AI Agents magna-nz ASP.NET Core Debugger — MCP Server for AI Agents — MCP-сервер для интерактивной отладки .NET и ASP.NET Core через netcoredbg и DAP. Позволяет ставить точки останова, менять переменные в памяти и находить дедлоки. CX Codex +1 ★ 16звёзд репо

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

Весь набор →
signalr Помогает проектировать хабы SignalR, настраивать стриминг, группы и обработку разрывов связи в ASP.NET Core. CX Codex +1 ★ 521звёзд репо code-testing-implementer Субагент code-testing-implementer реализует один этап плана тестирования: добавляет тесты и проверяет, что они собираются и проходят. Подключайте его для выполнения этапа или цикла сборки и исправления тестов. CX Codex ★ 521звёзд репо microsoft-extensions-ai Скилл для работы с Microsoft.Extensions.AI в .NET: чат-клиенты, эмбеддинги, инструменты, структурированный вывод и оценка без привязки к одному провайдеру. CX Codex +1 ★ 521звёзд репо unit-test-generation Промпт unit-test-generation для Claude Code помогает писать компактные модульные тесты, проверяющие поведение и выявляющие правдоподобные ошибки. Тестирует новый код и расширяет существующий набор. CX Codex +1 ★ 521звёзд репо wpf Готовые правила и паттерны для WPF-приложений: биндинги, команды, потоки, стили. Пригодится при работе с UI, MVVM или переносе проекта с .NET Framework на .NET. CX Codex +1 ★ 521звёзд репо worker-services Скилл worker-services помогает создавать фоновые службы .NET на базе BackgroundService и Generic Host с корректным graceful shutdown и скоупами зависимостей. CX Codex +1 ★ 521звёзд репо aspire Скилл помогает создавать и обновлять AppHost для распределённых приложений на C# или TypeScript. Он пригодится для подключения сервисов, интеграций и тестов Aspire. CX Codex +1 ★ 521звёзд репо improve-skill-quality Скилл improve-skill-quality для Claude Code, диагностирующий и исправляющий скиллы dotnet/skills репозитория, которые теряют к собственному базелайну, не активируются, зависают или возвращают «нет улучшения». CX Codex +1 ★ 521звёзд репо

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

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