Building a Model Context Protocol server in .NET 10 with the ModelContextProtocol SDK: the three primitives (tools, resources, prompts), stdio vs Streamable HTTP transports, tool annotations, DI, authorisation with MapMcp, and keeping tools narrow and validated.
MCP (Model Context Protocol) is an open JSON-RPC protocol that lets any AI host (Copilot, Claude, VS Code, your own agent) discover and call capabilities on a server. A server exposes three primitives: tools (actions the model decides to call), resources (data the application reads into context) and prompts (templates the user picks). In .NET you use the official ModelContextProtocol SDK (1.0 in March 2026, 2.0 in July 2026): AddMcpServer().WithHttpTransport().WithTools<T>() plus app.MapMcp() for remote Streamable HTTP, or WithStdioServerTransport() for a local process. Tools are plain C# methods marked [McpServerTool], resolved through DI. To keep it safe, wrap use cases, not raw endpoints, validate every argument, mark tools read-only or destructive, and require authorisation so each call runs as the signed-in user. The trade-off: one server serves every AI host, but it is a new public attack surface.
"MCP is a protocol, not a library: a host like VS Code or Claude connects to my server over JSON-RPC, asks what it offers, and then calls it. The server offers three things. Tools are actions the model can choose to invoke, like
search_ordersorcreate_return. Resources are read-only data the host application can pull into context, addressed by URI, likeorders://ORD-12345. Prompts are reusable templates the user selects, like 'summarise this customer's open tickets'. The point is that I write the integration once and every MCP-capable host can use it.In .NET 10 I use the official ModelContextProtocol SDK. For a remote server I add
ModelContextProtocol.AspNetCore, callAddMcpServer().WithHttpTransport().WithTools<OrderTools>()andapp.MapMcp("/mcp"). Tools are methods on a class marked[McpServerToolType], each with[McpServerTool]and[Description]attributes, and their parameters become the JSON schema the model sees. They are resolved from DI, so they call my existing MediatR handlers or services. For a developer tool that runs on someone's laptop, I'd useWithStdioServerTransport()and ship it as adotnet tool. The SDK reached 1.0 in March 2026 and 2.0 in July 2026, which follows the 2026-07-28 spec and makes HTTP stateless by default, so it scales out behind a load balancer without sticky sessions.The mistake I see is wrapping the REST API one-to-one, or worse, giving the model a 'run SQL' tool. I design tools around tasks with narrow, validated parameters, mark them with
ReadOnlyorDestructiveannotations so hosts can ask for confirmation, and putRequireAuthorization()onMapMcpso the tool runs with the caller's identity and my existing authorisation rules. An MCP server is a public API whose client is a model, so I design it with the same care and less trust."
| Primitive | Who decides to use it | Example | .NET attribute |
|---|---|---|---|
| Tool | The model | get_order_status(orderNumber) |
[McpServerTool] on a method in a [McpServerToolType] class |
| Resource | The host application / user | orders://ORD-12345 as JSON |
[McpServerResource] in a [McpServerResourceType] class |
| Prompt | The user (slash command, picker) | summarise_customer(customerId) |
[McpServerPrompt] in a [McpServerPromptType] class |
| Transport | Use when | Notes |
|---|---|---|
| stdio | Local tool per user, e.g. a CLI for your dev team | Host launches the process; identity is the local user; ship as a dotnet tool |
| Streamable HTTP | Shared, remote server for many users | MapMcp() in ASP.NET Core; OAuth 2.1 bearer tokens; stateless by default in SDK 2.0 |
| Do | Don't |
|---|---|
One tool per user task (create_return) |
Mirror every REST endpoint |
| Typed, narrow parameters with descriptions | Free-form query or sql strings |
| Compact results with the fields the model needs | Return whole entities or 5 MB JSON |
| Clear error text the model can recover from | Stack traces |
Annotations: ReadOnly, Destructive, Idempotent |
Leave hosts guessing which tools change data |
We exposed [an internal order-management API] through an MCP server with 6 tools instead of the 40 REST endpoints. Tool-selection errors in our evaluation set dropped from about 18% to 4% because the descriptions were task-shaped, and since the server reused the existing MediatR handlers and authorisation policies, the security review took [two days] instead of a new design.
Checks whether the candidate can build an MCP server with the real .NET SDK and design its tools as a safe, narrow API.
Green flags
AddMcpServer, WithHttpTransport/WithStdioServerTransport, MapMcp, [McpServerTool] correctlyRed flags
run_sql or generic HTTP toolMCP is JSON-RPC 2.0 messages between a client (inside a host such as VS Code, Claude or your own agent) and a server. The client discovers capabilities (tools/list, resources/list, prompts/list) and invokes them (tools/call, resources/read, prompts/get).
┌────────────── Host (IDE, chat app, your agent) ─────────────┐
│ LLM ◄──► MCP client ──────────────┐ │
└───────────────────────────────────────┼──────────────────────┘
│ JSON-RPC over stdio or
│ Streamable HTTP (+ OAuth bearer)
┌──────────────▼───────────────┐
│ MCP server (.NET) │
│ tools / resources / prompts │
│ ↓ DI │
│ MediatR handlers, services │
└──────────────────────────────┘
The SDK is maintained in the modelcontextprotocol/csharp-sdk repository with Microsoft. As of late 2026:
Mcp-Session-Id session pinning), negotiation is discovery-first instead of the old initialize handshake, and Roots, Sampling and Logging capability APIs are deprecated (diagnostic MCP9005). Stable, non-deprecated 1.x APIs such as AddMcpServer() keep working.Check the SDK release notes before you copy older blog code; samples from 2025 often use preview APIs that were renamed.
The SDK reflects over methods marked [McpServerTool]. The method name (snake-cased) or Name property becomes the tool name; [Description] on the method and parameters becomes the descriptions; parameter types become the JSON schema. Parameters of types it recognises, such as CancellationToken, IServiceProvider, McpServer or services registered in DI, are injected and not shown to the model. The return value is serialised into the tool result content. The same tools are AIFunctions, so on the client side McpClientTool plugs straight into ChatOptions.Tools for an IChatClient.
Tool annotations (ReadOnly, Destructive, Idempotent, OpenWorld, Title) are hints in the tool list. Hosts use them to auto-approve read-only tools and ask the user before destructive ones. They are hints, not enforcement: a malicious or careless host can ignore them, so enforcement stays in your server.
For Streamable HTTP, the MCP authorisation spec uses OAuth 2.1: the server is a protected resource, publishes protected resource metadata pointing to your authorisation server (for example Microsoft Entra ID), and validates bearer tokens. In ASP.NET Core that is ordinary JWT bearer authentication plus MapMcp().RequireAuthorization(...). Inside the tool, IHttpContextAccessor or the injected ClaimsPrincipal gives you the user, so your existing authorisation policies decide what they can see.
A tool result is content (text, structured JSON, images, resource links). Errors should come back as a tool result flagged as an error with a short message, so the model can retry with better arguments; protocol errors are for broken requests. Keep results small: the host puts them into the model's context window.
ModelContextProtocol.AspNetCore, expose one read-only tool and connect from VS Code's MCP configuration.npx @modelcontextprotocol/inspector) against it and look at the generated tool schema.Destructive = true and observe the host asking for confirmation.RequireAuthorization(); confirm unauthenticated calls get 401.McpClient to the server through WebApplicationFactory and calls ListToolsAsync.A remote MCP server that reuses application use cases, requires authorisation and marks tool behaviour.
// Program.cs (.NET 10, ModelContextProtocol.AspNetCore)
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Orders.Mcp;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
o.Authority = builder.Configuration["Auth:Authority"]; // e.g. Entra ID tenant
o.Audience = builder.Configuration["Auth:McpAudience"]; // token must be issued for THIS server
});
builder.Services.AddAuthorizationBuilder()
.AddPolicy("mcp.orders", p => p.RequireAuthenticatedUser().RequireClaim("scp", "orders.mcp"));
builder.Services.AddHttpContextAccessor();
builder.Services
.AddMcpServer()
.WithHttpTransport() // Streamable HTTP; stateless by default in SDK 2.x
.WithTools<OrderTools>();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapMcp("/mcp").RequireAuthorization("mcp.orders");
app.Run();
using System.ComponentModel;
using MediatR;
using ModelContextProtocol.Server;
namespace Orders.Mcp;
[McpServerToolType]
public sealed class OrderTools(ISender mediator)
{
[McpServerTool(Name = "get_order_status", ReadOnly = true, Idempotent = true)]
[Description("Gets the status and last update of one of the signed-in customer's orders.")]
public async Task<string> GetOrderStatus(
[Description("Order number in the form ORD-nnnnn")] string orderNumber,
CancellationToken ct)
{
if (!OrderNumber.TryParse(orderNumber, out var id))
return "Invalid order number. Expected ORD-nnnnn.";
// The handler applies the same ownership checks as the REST API.
var result = await mediator.Send(new GetOrderStatusQuery(id), ct);
return result is null ? "Order not found." : $"{result.Status} (updated {result.UpdatedUtc:u})";
}
[McpServerTool(Name = "request_return", Destructive = true, Idempotent = false)]
[Description("Starts a return for one order line. Hosts should confirm with the user first.")]
public async Task<string> RequestReturn(
[Description("Order number in the form ORD-nnnnn")] string orderNumber,
[Description("Line number on the order, starting at 1")] int lineNumber,
[Description("Short reason given by the customer")] string reason,
CancellationToken ct)
{
if (!OrderNumber.TryParse(orderNumber, out var id) || lineNumber is < 1 or > 200)
return "Invalid order or line number.";
var outcome = await mediator.Send(new RequestReturnCommand(id, lineNumber, reason[..Math.Min(reason.Length, 500)]), ct);
return outcome.Succeeded ? $"Return {outcome.ReturnId} created." : outcome.Error!;
}
}
run_sql or call_api(url) tool. Why it is wrong: It hands the model, and anyone who can inject into it, unrestricted access. Instead: Narrow, typed parameters behind your existing use cases.RequireAuthorization(), with per-user checks in handlers.Destructive/ReadOnly annotations for safety. Why it is wrong: They are hints that hosts may ignore. Instead: Enforce permissions, limits and confirmations server-side.An MCP server is an API whose consumer is a model acting for a user, so I apply the normal API rules (versioning, authorisation, rate limits, audit) and then distrust the caller a bit more. The best design reuses the application layer: tools call the same handlers as the REST API, so the business rules and ownership checks are not duplicated. I measure success with an evaluation set of user tasks (did the model pick the right tool with valid arguments), plus per-tool error rates and latency in Application Insights.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| MCP server (Streamable HTTP) | Many AI hosts or teams need the same capabilities | New public surface, OAuth setup | Only your own app's agent uses the tools |
In-process AIFunction tools |
One agent inside your own service | Lowest latency, no protocol | Other hosts need the capability too |
MCP server (stdio, dotnet tool) |
Developer tooling on laptops | Distribution and updates | Shared data needing central authorisation |
Unit-test the tool classes directly as ordinary C# (they are plain methods with DI dependencies), including edge cases: invalid formats, out-of-range numbers, missing records, over-long strings, and inputs that look like instructions. For the protocol, host the server in WebApplicationFactory and connect an McpClient over the test server's HTTP handler, then snapshot ListToolsAsync (names, descriptions, schemas, annotations) so accidental schema changes fail CI, and call tools to assert on result content and error messages, not just shape. Add authorisation tests (no token → 401, wrong scope → 403, another user's data → refused). Load-test the HTTP endpoint (for example with k6 or NBomber) against a latency target, since hosts call tools inside a user's wait. Finally run an evaluation set of user tasks against a real model to check tool selection, because a description change can break the model's choices without breaking any code.
With tool calling, you describe functions (name, description, JSON schema of parameters) in the request. The model can reply with a tool-call request instead of text; your app executes it and sends the result back, and the model continues. In Microsoft.Extensions.AI, AIFunctionFactory.Create turns a C# method into a tool, you pass it in ChatOptions.Tools, and UseFunctionInvocation() runs the loop.
The model chooses the arguments, so treat them as untrusted input: validate them, authorise against the signed-in user inside the tool, expose only least-privilege tools, require approval for side effects and cap iterations. The trade-off: tools make the model useful, but every tool widens what a confused or manipulated model can do.
Activity is .NET's span type and ActivitySource is the factory that creates them, the equivalent of an OpenTelemetry Tracer. They live in System.Diagnostics, so libraries can emit spans without referencing OpenTelemetry at all. You call source.StartActivity("name", ActivityKind.Internal) inside a using, add tags (attributes), events and a status, and disposing it records the duration.
StartActivity returns null when nothing is listening or the sampler drops the span, which is why you write activity?.SetTag(...). The OpenTelemetry SDK only listens to sources registered with AddSource("MyCompany.Orders"). Activity.Current is stored in an AsyncLocal, flows across await, and becomes the parent of the next activity.
The trade-off: the API is free when tracing is off, but you must name sources consistently or your spans silently go nowhere.
How to tell it (STAR)
**S:** We had an MCP server used by [about 200] support staff, and after a release people said the assistant kept losing track of the conversation. **T:** I was asked to find out why and fix it without taking the tool away. **A:** I looked at the GenAI traces and saw input tokens jump every time `search_customers` ran; the tool was returning whole EF entities, [180 KB] at a time, including fields support didn't need. I capped results that day, then replaced the payload with a small DTO and split out a single-customer summary tool behind the existing ownership checks. I added a result-size metric with an alert and snapshot tests for tool outputs. **R:** Average tool result fell to [3 KB], context-length errors went to zero and cost per conversation dropped by [about 70%].
Last updated 23 Nov 2026.