Dotnet MCP Builder
GitHubOfficialFirst committed by AClerboisDistributed by GitHub
- Skill
- Tool integration
- Software development
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides guidance for developing production-ready MCP servers and clients in C#/.NET. It focuses on the official ModelContextProtocol NuGet packages, specifically targeting the stable 2.x line and the 2026-07-28 specification. It addresses common pitfalls such as stale preview versions, v2 stateless HTTP defaults, deprecated capabilities like sampling and roots, and proper transport configuration for STDIO and Streamable HTTP.
What it does
- Provides setup patterns for MCP servers using Microsoft.Extensions.Hosting.
- Explains how to implement tools, prompts, and resources using C# attributes.
- Guides the configuration of STDIO and Streamable HTTP transports.
- Offers solutions for debugging common errors like HTTP 404s, parameter binding issues, and STDIO stdout conflicts.
- Details the multi-round-trip pattern for eliciting user input mid-tool execution.
- Assists in building .NET-based MCP clients to consume and test servers.
When to use it
- When starting a new MCP project in C# or upgrading an existing one to the 2.x SDK.
- When you need to implement specific MCP primitives like tools, prompts, or resources.
- When troubleshooting transport-level issues in STDIO or HTTP implementations.
- When migrating away from deprecated features like sampling or roots to the current multi-round-trip pattern.
- When you need to integrate an MCP client into a .NET application.
Advantages
- Prevents the use of stale or incompatible preview packages.
- Ensures adherence to current protocol specifications and deprecation warnings.
- Provides clear patterns for handling complex interactions like user elicitation.
- Helps avoid common runtime errors related to transport and DI configuration.
- Promotes consistent project structure using standard .NET hosting patterns.
Usage examples
- “How do I set up a basic MCP server in .NET?”
- The agent provides a code snippet using AddMcpServer, WithStdioServerTransport, and tool registration via DI.
- “Why is my MCP tool not appearing in the client?”
- The agent checks for missing [McpServerToolType] attributes and verifies that the tool class is registered via .WithToolsFromAssembly().
- “How do I ask the user for input during a tool call in v2?”
- The agent explains the multi-round-trip InputRequiredException pattern for modern stateless HTTP.
- “How do I connect to an MCP server from a .NET client?”
- The agent provides a configuration example for StdioClientTransport or HttpClientTransport.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/github/dotnet-mcp-builder/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip dotnet-mcp-builder.zip -d .agents/skills
Documentation by AClerbois
Building MCP servers in .NET
This skill helps you write production-quality MCP servers and basic clients in C#/.NET against the official ModelContextProtocol NuGet packages, maintained by Microsoft and the MCP project. It targets the stable 2.x line and the current spec (2026-07-28).
When this skill earns its keep
The .NET MCP SDK had years of preview packages (0.x-preview) before reaching 1.0, and v2 flipped several defaults. Without help, the model tends to:
Pin a stale preview version that won't compile against current samples.
Apply 1.x-era defaults that v2 reversed (HTTP was stateful by default; in 2.x
Statelessdefaults totrue).Recommend capabilities the 2026-07-28 spec deprecates (roots, sampling, MCP-channel logging — now
[Obsolete], warningMCP9005).Miss recent spec features (multi-round-trip
input_required, discovery-first negotiation, MCP Apps/Tasks extension packages, elicitation URL mode, structured content blocks).Get HTTP transport details wrong (stateful/stateless, proxy buffering, OAuth wiring).
Forget the STDIO stdout/stderr trap.
If the task is one of those, load the matching reference and follow it. If it's truly trivial (e.g. "rename this tool method"), you don't need to read everything — the cardinal rules below are the minimum.
Mental model in 30 seconds
A .NET MCP server is an ordinary Microsoft.Extensions.Hosting (or WebApplication) app that wires an MCP server through DI:
builder.Services
.AddMcpServer()
.WithStdioServerTransport() // OR .WithHttpTransport(...)
.WithToolsFromAssembly() // discover [McpServerToolType] classes
.WithPrompts<MyPrompts>() // optional
.WithResources<MyResources>(); // optionalPrimitives are plain C# methods on classes marked with attributes ([McpServerToolType] + [McpServerTool], [McpServerPromptType] + [McpServerPrompt], [McpServerResourceType] + [McpServerResource]). Parameters bind from JSON-RPC; the SDK builds the JSON Schema from the signature plus [Description] attributes.
Server-to-client features (elicitation, progress notifications, and the now-deprecated sampling/roots/log notifications) are methods on the injected IMcpServer.
Decision tree → which references to load
Always load references/packages.md if you're creating a new project or unsure of the current package version.
| Task | Load |
|---|---|
| New STDIO server | references/transport-stdio.md |
| New HTTP (Streamable) server | references/transport-http.md |
| Add/modify a tool | references/tool-primitive.md |
| Add/modify a prompt | references/prompt-primitive.md |
| Add/modify a resource | references/resource-primitive.md |
| Ask the user a question mid-tool | references/elicitation.md |
| Call the client's LLM from a tool (deprecated in 2026-07-28) | references/sampling.md |
| Read the user's project roots (deprecated in 2026-07-28) | references/roots.md |
| Return an interactive UI | references/mcp-apps.md |
| Argument completions, log/progress notifications, filters, server instructions | references/server-features.md |
| Write a .NET program that consumes an MCP server | references/client.md |
| MCP Inspector, in-memory tests, mocks, CI | references/testing.md |
For multi-primitive tasks, load several at once. For trivial edits in an existing file, you usually don't need any.
Cardinal rules (apply always; these prevent the highest-frequency breakages)
Pin the current stable package, not a preview. Use
ModelContextProtocol/ModelContextProtocol.AspNetCore/ModelContextProtocol.Coreat the latest 2.x. If you find yourself writing0.3-previewor0.4-preview, stop and check NuGet — preview APIs have breaking differences. 1.x still works but predates the 2026-07-28 spec.STDIO servers must not write to stdout. Stdout is the JSON-RPC channel. Configure
LogToStandardErrorThreshold = LogLevel.Tracebefore anything else and neverConsole.WriteLinefrom a tool.HTTP defaults to stateless in 2.x (v1.x defaulted to stateful — the single most impactful v2 breaking change). The 2026-07-28 revision has no HTTP sessions at all: setting
Stateless = falsemakes the server refuse that revision and serve clients via the legacyinitializefallback. For "ask the user something mid-tool" on current-protocol HTTP, use the multi-round-tripInputRequiredExceptionpattern; reserve stateful HTTP (or STDIO) for the legacyElicitAsync/sampling/roots paths and pushed notifications.SSE-only is deprecated. Use Streamable HTTP. Only enable legacy SSE (
EnableLegacySse = true) for an old client you must support, and call it out.Don't design new servers around deprecated capabilities. The 2026-07-28 spec deprecates roots, sampling, and MCP-channel logging; the SDK marks them
[Obsolete](warningMCP9005). They still work against down-level clients, but for new designs prefer the multi-round-tripinput_requiredpattern andILoggerlogging. SuppressMCP9005only as a documented transition measure.Always
[Description]tools and parameters. This is what the LLM sees when picking and shaping calls. Vague descriptions are the #1 reason tools don't get used.Show the registration line every time you add a primitive. A new
[McpServerPromptType]class without.WithPrompts<...>()(or.WithPromptsFromAssembly()) is invisible.Don't invent APIs. If you're unsure a method exists, say so and check the API reference — wrong method names cause silent failures. This applies doubly to the new v2 extension packages (
ModelContextProtocol.Extensions.Tasks,ModelContextProtocol.Extensions.Apps) — check their docs before writing code against them.
Working style
Make minimal, additive changes. Add a method to the existing tool class rather than restructuring the project.
For non-trivial setups, run
dotnet build. Catches missing usings, attribute typos, and TFM mismatches before the user sees them.Confirm transport + .NET version + primitives before scaffolding if context doesn't already make them obvious. Default to .NET 10 for new projects.
When the user is stuck
Walk this checklist before guessing:
STDIO: something is writing to stdout (logger sink,
Console.WriteLine, library banner).HTTP 404: path mismatch —
app.MapMcp()is root,app.MapMcp("/mcp")puts it under/mcp.Tool not appearing: missing
[McpServerToolType]on the class, or no.WithToolsFromAssembly()/.WithTools<T>()registered.Args not bound: parameter names must match the JSON-RPC
argumentskeys; complex types bind viaSystem.Text.Json.Sampling/elicitation/roots failing: these legacy server-to-client calls can't run on current-protocol HTTP — migrate to the multi-round-trip
InputRequiredExceptionpattern, or (legacy paths only) setStateless = false, knowing that pins HTTP clients to a down-levelinitializerevision. Also check the client actually advertises the capability.MCP9005build warnings after upgrading to 2.x: the code uses deprecated roots/sampling/logging APIs. Plan the migration; suppress only temporarily.
Still stuck? Point the user at the EverythingServer sample — it exercises every feature.
Files
- ATTRIBUTION.mdAdded by AutoGineer871 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md8.4 KiB
- references/client.md6.2 KiB
- references/elicitation.md7.8 KiB
- references/mcp-apps.md9.8 KiB
- references/packages.md5.2 KiB
- references/prompt-primitive.md5.0 KiB
- references/resource-primitive.md6.1 KiB
- references/roots.md4.0 KiB
- references/sampling.md5.4 KiB
- references/server-features.md6.6 KiB
- references/testing.md6.1 KiB
- references/tool-primitive.md8.4 KiB
- references/transport-http.md8.4 KiB
- references/transport-stdio.md5.1 KiB
references/transport-http.md
Streamable HTTP transport (ASP.NET Core)
Streamable HTTP is the modern remote transport. A single endpoint accepts JSON-RPC over HTTP POST and (optionally) streams responses back as Server-Sent Events when the server has more than one message to send.
SSE-only is deprecated. The legacy "HTTP+SSE" transport (separate POST endpoint + GET SSE endpoint) is gone from new clients. Use Streamable HTTP. Only enable legacy SSE (
EnableLegacySse = true) if you must support a known-old client, and document why.
When to choose HTTP
Multi-tenant or remote-hosted server.
Auth via OAuth / API gateway in front.
Horizontally scaled deployments (with
Stateless = true).Containers, Azure Container Apps, Kubernetes, etc.
For local single-user scenarios, STDIO is simpler.
Minimal server
dotnet new web -n MyHttpServer -f net10.0
cd MyHttpServer
dotnet add package ModelContextProtocol.AspNetCore --version 2.2.0// Program.cs
using ModelContextProtocol.Server;
using System.ComponentModel;
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddMcpServer()
// Since 2.x, Stateless defaults to true: each request is independent,
// no Mcp-Session-Id tracking, no SSE session endpoints — ready for
// horizontal scaling without sticky sessions.
.WithHttpTransport()
.WithToolsFromAssembly();
var app = builder.Build();
app.MapMcp(); // mounts the MCP endpoints at "/"
// app.MapMcp("/mcp"); // or under a path prefix
app.Run("http://localhost:3001");
[McpServerToolType]
public static class EchoTool
{
[McpServerTool, Description("Echoes the message back to the client.")]
public static string Echo(string message) => $"hello {message}";
}Stateless vs. stateful — the most important decision
v2 breaking change:
HttpServerTransportOptions.Statelessnow defaults totrue(it defaulted tofalseon 1.x). A server upgraded to 2.x without touching options stops creating sessions and stops exposing SSE endpoints. SetStateless = falseexplicitly to restore the legacy behavior.
| Mode | options.Stateless | Behaviour | Use when |
|---|---|---|---|
| Stateless | true (default since 2.x) | No Mcp-Session-Id. Each POST is independent. Serves the current (2026-07-28) revision. | Horizontal scaling, simple tool servers, current-protocol clients. |
| Stateful | false | Server assigns and tracks Mcp-Session-Id. Long-lived session. Down-level compatibility mode: the server refuses the 2026-07-28 revision so dual-path clients fall back to an initialize-capable revision (2025-11-25 or earlier). | Legacy ElicitAsync/sampling/roots paths, pushed log notifications, clients that haven't adopted 2026-07-28. Requires session affinity at the load balancer. |
Rule: on the current (2026-07-28) protocol there are no HTTP sessions — "ask the user something mid-tool" uses the multi-round-trip pattern (throw InputRequiredException, handle the retried call; see elicitation.md), which works in both session modes and both revisions. Set Stateless = false only for the legacy paths — ElicitAsync, the deprecated SampleAsync/RequestRootsAsync, or pushed log/notification messages — and be aware it pins HTTP clients to a down-level, initialize-capable revision. On the stateless default those legacy calls fail at runtime with no channel to deliver them on.
Endpoint shape
MapMcp(pattern = "") creates a route group at pattern and maps:
POST — accepts JSON-RPC requests/responses/notifications. Returns either a JSON response or an SSE stream depending on
Acceptheader and whether multiple messages need to flow back.GET — used by stateful sessions for the server-to-client SSE channel.
DELETE — terminates a stateful session.
Default pattern is the root (/). To put MCP under /mcp/v1:
app.MapMcp("/mcp/v1");Match this on the client side (Endpoint = new Uri("https://host/mcp/v1")).
Version negotiation and routing (2026-07-28)
Discovery-first: v2 clients probe the
server/discovermethod to learn capabilities instead of the legacyinitializehandshake. The SDK answers both and falls back automatically for down-level peers (2025-11-25 and earlier) — you don't write any code for this, but don't be surprised to seeserver/discoverin traffic captures.Routable headers: every Streamable HTTP POST carries an
Mcp-Methodheader (e.g.tools/call), and named invocations (tools/call,prompts/get,resources/read) additionally carryMcp-Name(e.g. the tool name), so gateways and rate limiters can route/throttle per tool without parsing JSON bodies. Don't requireMcp-Nameglobally at the gateway — discovery and list requests legitimately omit it.
Per-session configuration (HttpContext access)
When you need to vary server behaviour per HTTP request (auth, tenant, headers), use the ConfigureSessionOptions callback:
builder.Services
.AddMcpServer()
.WithHttpTransport(options =>
{
options.ConfigureSessionOptions = async (httpContext, mcpOptions, ct) =>
{
var tenantId = httpContext.Request.Headers["X-Tenant"].ToString();
mcpOptions.ServerInstructions = $"Tenant: {tenantId}";
// mutate any McpServerOptions fields per-session
};
});Inside a tool, you can also inject IHttpContextAccessor if AddHttpContextAccessor() is registered. See the AspNetCoreMcpPerSessionTools sample.
Authentication
The MCP endpoint is just an ASP.NET Core endpoint — apply standard middleware:
builder.Services
.AddAuthentication("Bearer")
.AddJwtBearer(/* configure */);
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapMcp().RequireAuthorization(); // protect the endpointFor OAuth flows where the MCP server is the resource server, follow the MCP authorization spec. The ProtectedMcpServer sample shows a working setup with discovery endpoints.
For machine-to-machine, an API key middleware is fine:
app.Use(async (ctx, next) =>
{
if (ctx.Request.Headers["X-Api-Key"] != Configuration["ApiKey"])
{
ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
return;
}
await next();
});CORS (when the client is in-browser)
builder.Services.AddCors(o => o.AddDefaultPolicy(p =>
p.WithOrigins("https://my-host.example.com")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()));
// ...
app.UseCors();
app.MapMcp();Health checks and observability
Add the standard ASP.NET Core probes; the MCP endpoint shouldn't be the liveness check.
builder.Services.AddHealthChecks();
// ...
app.MapHealthChecks("/healthz");The SDK emits OpenTelemetry traces (Activity per tool call) and metrics. Wire them up if the user has an OTel pipeline:
builder.Services
.AddOpenTelemetry()
.WithTracing(t => t.AddSource("ModelContextProtocol").AddOtlpExporter())
.WithMetrics(m => m.AddMeter("ModelContextProtocol").AddOtlpExporter());Deployment notes
Containerise normally. No special MCP-specific Dockerfile — it's just an ASP.NET Core app.
Behind a reverse proxy (nginx, Azure Front Door, AWS ALB), make sure SSE buffering is disabled for the MCP path. nginx:
proxy_buffering off;. Without this, streaming responses are batched into one slow blob.Timeouts. The client may keep an SSE connection open for a long time. Set proxy idle timeout high (e.g. 5+ minutes) for stateful deployments; less critical for stateless.
Azure Container Apps / App Service work out of the box; both support long-lived HTTP responses.
Enabling legacy SSE (compatibility only)
builder.Services
.AddMcpServer()
.WithHttpTransport(options =>
{
options.EnableLegacySse = true;
#pragma warning disable MCP9004
options.Stateless = false; // SSE requires stateful mode
#pragma warning restore MCP9004
})
.WithToolsFromAssembly();Only do this if the user has a documented client that hasn't migrated. New deployments should not enable it.
Requirements and compatibility
Written for: GitHub Copilot
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs an MCP server
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- First committed by
AClerbois
- Publisher
- GitHub (Official)
- Distributed by
- GitHub
- Source
- github/awesome-copilot · skills/dotnet-mcp-builder · commit 797337f
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
- Contributors
- AClerbois, jeanpaulhassane-225
AutoGineer is not affiliated with or endorsed by AClerbois or GitHub.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download dotnet-mcp-builder.zip