Skill page AI v1.1.1

MCP C# SDK for .NET

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.

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, or session resumption

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.

  1. 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.

  1. Prefer attribute discovery for straightforward servers.
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}";
}
  1. For HTTP servers, use the ASP.NET Core transport and map the endpoint directly.
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}";
}
  1. When consuming a server, use McpClient.CreateAsync(...) and stay capability-aware.
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();
}
  1. 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.

  1. 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(...).

  1. 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.

  1. 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.

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

References

Related skills

v1.0.0

Apply MCAF ML/AI delivery guidance for data exploration, feasibility, experimentation, testing, responsible AI, and operating ML systems.

AI
dotnet skills install mcaf-ml-ai-delivery

Build .NET AI agents and multi-agent workflows with Microsoft Agent Framework using the right agent type, threads, tools, workflows, hosting protocols, and enterprise guardrails.

AI
dotnet skills install microsoft-agent-framework

Build provider-agnostic .NET AI integrations with `Microsoft.Extensions.AI`, `IChatClient`, embeddings, middleware, structured output, vector search, and evaluation.

AI
dotnet skills install microsoft-extensions-ai

Related agents