Use ML.NET to train, evaluate, or integrate machine-learning models into .NET applications with realistic data preparation, inference, and deployment expectations.
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 AIquickstarts or publishing a server to the MCP Registry - implementing capability-aware flows such as roots, sampling, elicitation, subscriptions, or session resumption
Workflow
- 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.
- 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.
- 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}";
}
- 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}";
}
- 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();
}
- 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.
- 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(...).
- Treat the
.NET AIMCP 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.
- 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, orAspNetCore - 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
ServerCapabilitiesbefore 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
- `references/patterns.md` - current server/client patterns, transports, capabilities, filters, and chat-client integration
- `references/security.md` - safe error handling, auth boundaries, stdio logging hygiene, and defensive tool/resource patterns
Related skills
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.
Build AI-enabled .NET applications with Semantic Kernel using services, plugins, prompts, and function-calling patterns that remain testable and maintainable.
Related agents
Microsoft Agent Framework Router
Microsoft Agent Framework routing agent for agent-vs-workflow decisions, agent types, AgentThread or AgentSession state, tools, workflows, hosting…
Also works: dotnet agents install agent-framework-router
.NET AI
AI-focused orchestration agent for Microsoft Agent Framework, Microsoft.Extensions.AI, Semantic Kernel, MCP, and ML.NET.
Also works: dotnet agents install ai