/ Каталог / Песочница / C# SDK
● Официальный modelcontextprotocol ⚡ Сразу

C# SDK

автор modelcontextprotocol · modelcontextprotocol/csharp-sdk

Build MCP servers and clients in .NET — official SDK co-maintained by the MCP team and Microsoft.

The official modelcontextprotocol/csharp-sdk. Write MCP servers with attributes like [McpServerToolType] and [McpServerTool], or build clients that connect to any MCP server. Integrates naturally with .NET dependency injection, logging, and hosting.

Зачем использовать

Ключевые функции

Живое демо

Как выглядит на практике

csharp-sdk.replay ▶ готово
0/0

Установка

Выберите клиент

~/Library/Application Support/Claude/claude_desktop_config.json  · Windows: %APPDATA%\Claude\claude_desktop_config.json
{
  "mcpServers": {
    "csharp-sdk": {
      "command": "dotnet",
      "args": [
        "run",
        "--project",
        "./MyMcpServer"
      ]
    }
  }
}

Откройте Claude Desktop → Settings → Developer → Edit Config. Перезапустите после сохранения.

~/.cursor/mcp.json · .cursor/mcp.json
{
  "mcpServers": {
    "csharp-sdk": {
      "command": "dotnet",
      "args": [
        "run",
        "--project",
        "./MyMcpServer"
      ]
    }
  }
}

Cursor использует ту же схему mcpServers, что и Claude Desktop. Конфиг проекта приоритетнее глобального.

VS Code → Cline → MCP Servers → Edit
{
  "mcpServers": {
    "csharp-sdk": {
      "command": "dotnet",
      "args": [
        "run",
        "--project",
        "./MyMcpServer"
      ]
    }
  }
}

Щёлкните значок MCP Servers на боковой панели Cline, затем "Edit Configuration".

~/.codeium/windsurf/mcp_config.json
{
  "mcpServers": {
    "csharp-sdk": {
      "command": "dotnet",
      "args": [
        "run",
        "--project",
        "./MyMcpServer"
      ]
    }
  }
}

Тот же формат, что и Claude Desktop. Перезапустите Windsurf для применения.

~/.continue/config.json
{
  "mcpServers": [
    {
      "name": "csharp-sdk",
      "command": "dotnet",
      "args": [
        "run",
        "--project",
        "./MyMcpServer"
      ]
    }
  ]
}

Continue использует массив объектов серверов, а не map.

~/.config/zed/settings.json
{
  "context_servers": {
    "csharp-sdk": {
      "command": {
        "path": "dotnet",
        "args": [
          "run",
          "--project",
          "./MyMcpServer"
        ]
      }
    }
  }
}

Добавьте в context_servers. Zed перезагружается автоматически.

claude mcp add csharp-sdk -- dotnet run --project ./MyMcpServer

Однострочная команда. Проверить: claude mcp list. Удалить: claude mcp remove.

Сценарии использования

Реальные сценарии: C# SDK

Build an MCP server in .NET that exposes your existing services

👤 C#/.NET engineers with internal APIs ⏱ ~45 min intermediate

Когда использовать: You're on .NET and want to expose business logic to agents without a rewrite.

Предварительные требования
  • .NET 8+ SDKdotnet --version
Поток
  1. Create the project
    dotnet new console -n MyMcpServer. Add ModelContextProtocol NuGet. Use the minimal hosting template for MCP.✓ Скопировано
    → csproj + Program.cs with MCP hosted service
  2. Add a tool
    Create a static class with [McpServerToolType]. Add a method GetOrder(string id) decorated with [McpServerTool(Description="...")] that calls my existing OrderService via DI.✓ Скопировано
    → Tool compiles, description comes from attribute
  3. Test with the inspector
    Run the server as stdio. Launch the MCP Inspector via npx @modelcontextprotocol/inspector dotnet run. Call GetOrder.✓ Скопировано
    → Tool invocation returns order JSON

Итог: A compiled, typed MCP server reusing your existing .NET services and DI container.

Подводные камни
  • Tool methods that are instance methods on a class need DI to work — Register the owning class in the ServiceCollection; the SDK resolves through DI
  • Async methods without proper cancellation tokens hang at shutdown — Accept CancellationToken ct as the last parameter on every tool — SDK injects it

Build a .NET console app that uses MCP servers

👤 C# devs building internal automation ⏱ ~30 min intermediate

Когда использовать: You want deterministic .NET code (not an LLM loop) that calls MCP servers — e.g., a scheduled job that uses github + filesystem MCPs.

Поток
  1. Add the client package
    Create a console app. Reference ModelContextProtocol client. Add a config pointing at a stdio server (e.g. npx -y @modelcontextprotocol/server-github).✓ Скопировано
    → Client builds
  2. Connect and call
    Start the client, list tools, call list_repositories with my org name. Print the result.✓ Скопировано
    → Repos printed to console
  3. Wrap as a scheduled job
    Turn this into a Worker Service that runs nightly. Log metrics via ILogger.✓ Скопировано
    → Worker runs via dotnet run and schedules cleanly

Итог: MCP as a library, not just a chat plugin — works inside any .NET process.

Подводные камни
  • Stdio servers take time to start, first call times out — Initialize the client at app startup and reuse; don't spawn per-call

Serve an MCP endpoint from an ASP.NET Core app

👤 .NET platform engineers ⏱ ~60 min advanced

Когда использовать: You want the MCP server hosted inside an existing ASP.NET Core service, behind the same auth and ingress.

Предварительные требования
  • Existing ASP.NET Core app or willingness to start onedotnet new web
Поток
  1. Add MCP services + endpoint
    In Program.cs, builder.Services.AddMcpServer().WithToolsFromAssembly(). Then app.MapMcp('/mcp').✓ Скопировано
    → /mcp endpoint responds to SSE handshake
  2. Share auth with the rest of the app
    Put the /mcp endpoint behind my existing JWT bearer auth middleware. Verify unauth'd requests get 401.✓ Скопировано
    → 401 unauth, 200 auth
  3. Deploy and connect
    Deploy. Wire a teammate's Claude Desktop via mcp-remote https://myapp.com/mcp with their JWT.✓ Скопировано
    → Team members see tools

Итог: MCP alongside your existing API in one deploy with one auth story.

Подводные камни
  • Kestrel buffers SSE responses behind a reverse proxy — Disable response buffering; ensure IIS/nginx/Cloudflare in front also disable buffering for /mcp
Сочетать с: cloud-run

Комбинации

Сочетайте с другими MCP — эффект x10

csharp-sdk + cloud-run

Deploy .NET MCP server on Cloud Run alongside other microservices

Containerize my .NET MCP server (mcr.microsoft.com/dotnet/aspnet base), deploy to Cloud Run with a min-instance=1 for cold-start mitigation.✓ Скопировано
csharp-sdk + fastmcp

Comparison for polyglot shops — different SDKs, same protocol

Our team has both Python and .NET services. Use FastMCP for Python APIs and csharp-sdk for .NET APIs — both behind one ContextForge gateway.✓ Скопировано

Инструменты

Что предоставляет этот MCP

ИнструментВходные данныеКогда вызыватьСтоимость
[McpServerToolType] attribute on a class Mark classes whose methods should be exposed free
[McpServerTool(Description)] attribute on a method Each method you want agents to call free
AddMcpServer() / WithToolsFromAssembly() fluent builder Program.cs at startup free
MapMcp('/path') ASP.NET endpoint ASP.NET hosting only free
IMcpClient stdio or SSE transport config Client-side usage free

Стоимость и лимиты

Во что обходится

Квота API
None — this is an SDK
Токенов на вызов
No framework overhead beyond MCP protocol
Деньги
Free, MIT licensed
Совет
Use .NET's built-in logging and HealthChecks to catch problems before they balloon in prod

Безопасность

Права, секреты, радиус поражения

Хранение учётных данных: Standard .NET: user-secrets for dev, environment variables or Key Vault for prod
Исходящий трафик: Whatever your tools reach

Устранение неполадок

Частые ошибки и исправления

Tool not appearing in inspector

WithToolsFromAssembly() only scans the executing assembly. For tools in referenced libraries, pass the Assembly explicitly: WithTools(typeof(MyTools).Assembly).

DI can't resolve my service in a tool method

Tool types must be registered in the container. Add builder.Services.AddScoped<OrderService>() before AddMcpServer.

ASP.NET MapMcp returns 404

You mapped after app.Run() — move MapMcp before Run. Also check the path doesn't conflict with other endpoints.

JSON serialization fails on enums

SDK uses System.Text.Json; add [JsonStringEnumConverter] on your enums or configure globally.

Альтернативы

C# SDK в сравнении

АльтернативаКогда использоватьКомпромисс
FastMCP (Python)You're OK picking up Python — richer example ecosystemDifferent language; team skill dependent
TypeScript MCP SDKNode / TS shopSimilar DX, language choice

Ещё

Ресурсы

📖 Читать официальный README на GitHub

🐙 Открытые задачи

🔍 Все 400+ MCP-серверов и Skills