Introduction
In the previous article we called OpenAI from an ASP.NET Core app. This time we turn it around: we let AI assistants call into our app. The standard way to do that is the Model Context Protocol (MCP), an open protocol that lets any compatible AI host (GitHub Copilot in VS Code, Claude, ChatGPT, Cursor, your own agents) discover and call your code.
Think of MCP as "OpenAPI for AI agents". You write the integration once, as an MCP server, and every MCP-aware assistant can use it. No plugin per vendor.
We will build Contoso.Mcp, an MCP server for the fictional Contoso Outdoor Gear store, that:
Exposes tools to search products and check the signed-in customer's orders
Exposes resources (store policies) the assistant can read for context
Exposes a reusable prompt for drafting support replies
Runs over Streamable HTTP inside ASP.NET Core, protected with JWT authentication and per-tool authorisation
Is tested with MCP Inspector and VS Code, and consumed from a .NET app through IChatClient
Stack used in this article (November 2026):
Component | Version |
|---|
.NET SDK | .NET 10 (LTS) or .NET 11 (STS) |
ModelContextProtocol.AspNetCore
| 2.4.x (official MCP C# SDK) |
MCP specification | 2026-07-28 revision |
Microsoft.Extensions.AI.OpenAI
| latest stable (client section only) |
The C# SDK reached v2.0 in July 2026 and moves fast, so check the SDK documentation if an API name below has changed.
How MCP works
MCP has three roles. The host is the AI application the user talks to (VS Code with Copilot, Claude Desktop, your own app). Inside it, an MCP client keeps a connection to each MCP server. A server is your code: it advertises capabilities and runs them when asked.
[embed: node/0462280a-a4eb]
You write the server once; VS Code, Claude and your own agents all reach the same tools through the same /mcp endpoint.
A server can offer three kinds of capability:
Capability | Who decides to use it | Example in Contoso.Mcp |
|---|
Tools | The model, during a conversation | search_products, get_order_status
|
Resources | The host or user attaches them as context | contoso://policies/returns
|
Prompts | The user picks them, like a slash command | draft_support_reply
|
Messages are JSON-RPC 2.0. There are two transports:
stdio: the host starts your server as a local process and talks over standard input/output. Good for developer tools that work on local files.
Streamable HTTP: your server is a normal web endpoint. This is what you want for business APIs, because it can be deployed once, shared by many users, and protected with standard authentication.
The 2026-07-28 revision of the spec made HTTP stateless: the initialize handshake and the Mcp-Session-Id header are gone, and each request carries what it needs. For ASP.NET Core developers this is good news, because an MCP endpoint now scales like any other stateless API behind a load balancer. Version 2.0 of the C# SDK follows the spec and runs the HTTP transport statelessly by default.
Step 1: Create the project
You have two starting points.
Option A: the project template. Since .NET 11, the mcpserver template ships inside the SDK. On .NET 10, install it first with dotnet new install Microsoft.McpServer.ProjectTemplates.
dotnet new mcpserver -o Contoso.Mcp
Run dotnet new mcpserver --help to choose stdio or HTTP transport and other options.
Option B: add MCP to an ASP.NET Core app. This is the better choice when you already have a Web API and want to expose part of it to AI agents. It is the path we follow here:
dotnet new web -o Contoso.Mcp
cd Contoso.Mcp
dotnet add package ModelContextProtocol.AspNetCore
ModelContextProtocol.AspNetCore references the core ModelContextProtocol package and adds the Streamable HTTP transport.
The whole server is a few lines in Program.cs:
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// Your existing application services
builder.Services.AddSingleton<IProductCatalog, InMemoryProductCatalog>();
builder.Services.AddSingleton<IOrderRepository, InMemoryOrderRepository>();
builder.Services
.AddMcpServer(options =>
{
options.ServerInfo = new() { Name = "contoso-store", Version = "1.0.0" };
})
.WithHttpTransport() // Streamable HTTP, stateless by default in SDK v2
.WithToolsFromAssembly() // [McpServerToolType] classes
.WithResourcesFromAssembly() // [McpServerResourceType] classes
.WithPromptsFromAssembly(); // [McpServerPromptType] classes
var app = builder.Build();
app.MapMcp("/mcp");
app.Run();
MapMcp("/mcp") maps the MCP endpoint at /mcp. Without a route it maps to the site root. Because it is ordinary endpoint routing, it sits next to your existing controllers and Minimal APIs and goes through the same middleware pipeline: authentication, CORS, rate limiting, logging.
Step 2: Write your tools
A tool is a C# method marked with [McpServerTool] inside a class marked with [McpServerToolType]. The SDK builds the JSON schema from the method signature and the [Description] attributes. Those descriptions are what the model reads when deciding whether and how to call your tool, so treat them as part of your API contract.
First, the domain types the tools use (in a real app these already exist):
public sealed record Product(string Sku, string Name, string Category, decimal Price, int StockQuantity);
public sealed record Order(string Number, string CustomerId, string Status, DateOnly ExpectedDelivery, decimal Total);
public interface IProductCatalog
{
Task<IReadOnlyList<Product>> SearchAsync(string query, string? category, decimal? maxPrice, int take, CancellationToken ct);
}
public interface IOrderRepository
{
Task<Order?> FindAsync(string orderNumber, CancellationToken ct);
Task<IReadOnlyList<Order>> GetRecentAsync(string customerId, int take, CancellationToken ct);
}
A simple tool with dependency injection
Tool classes can be non-static. Constructor parameters, and any method parameter that is a registered service, are resolved from DI for each call:
// Tools/ProductTools.cs
using System.ComponentModel;
using ModelContextProtocol.Server;
[McpServerToolType]
public sealed class ProductTools(IProductCatalog catalog)
{
[McpServerTool(Name = "search_products", ReadOnly = true)]
[Description("Searches the Contoso Outdoor Gear catalog. Returns up to 10 matching products with SKU, price and stock.")]
public async Task<IReadOnlyList<Product>> SearchProducts(
[Description("Free-text search, e.g. 'waterproof 2-person tent'")] string query,
[Description("Optional category: Tents, SleepingBags, Backpacks, Footwear")] string? category = null,
[Description("Optional maximum price in USD")] decimal? maxPrice = null,
CancellationToken cancellationToken = default)
{
return await catalog.SearchAsync(query, category, maxPrice, take: 10, cancellationToken);
}
}
Returning a typed object rather than a string is fine: the SDK serializes it to JSON for the model. Keep results small, because everything you return is consumed as model input tokens. ReadOnly = true is a hint to hosts that the tool has no side effects, so they can skip asking the user for confirmation.
A tool that knows who is calling
Order data is private, so the tool needs the caller's identity. Declare a ClaimsPrincipal parameter and the SDK passes in the authenticated user of the HTTP request (we set up authentication in Step 6):
// Tools/OrderTools.cs
using System.ComponentModel;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using ModelContextProtocol.Server;
[McpServerToolType]
[Authorize] // requires an authenticated caller for every tool in this class
public sealed class OrderTools(IOrderRepository orders)
{
[McpServerTool(Name = "get_order_status", ReadOnly = true)]
[Description("Gets the status and expected delivery date of one of the signed-in customer's orders.")]
public async Task<string> GetOrderStatus(
ClaimsPrincipal user,
[Description("Order number, e.g. ORD-10421")] string orderNumber,
CancellationToken cancellationToken)
{
var customerId = user.FindFirstValue(ClaimTypes.NameIdentifier);
var order = await orders.FindAsync(orderNumber, cancellationToken);
// Never trust the model to enforce ownership; check it in code
if (order is null || order.CustomerId != customerId)
return $"No order {orderNumber} was found for this customer.";
return $"Order {order.Number} is {order.Status}. Expected delivery: {order.ExpectedDelivery:yyyy-MM-dd}.";
}
[McpServerTool(Name = "list_recent_orders", ReadOnly = true)]
[Description("Lists the signed-in customer's five most recent orders.")]
public async Task<IReadOnlyList<Order>> ListRecentOrders(ClaimsPrincipal user, CancellationToken cancellationToken)
{
var customerId = user.FindFirstValue(ClaimTypes.NameIdentifier)!;
return await orders.GetRecentAsync(customerId, take: 5, cancellationToken);
}
}
Note that ClaimsPrincipal and CancellationToken do not appear in the tool's schema. The model only sees orderNumber.
Naming and description tips
Use snake_case verb-noun names (get_order_status). They are what most hosts and models expect.
Say what the tool returns and when to use it, not how it is implemented.
Give an example value for every non-obvious parameter.
Prefer a few focused tools over one generic execute_query tool. Focused tools are easier for the model to pick correctly and much easier to secure.
When something is not found, return a clear sentence instead of throwing. The model can relay it to the user and recover.
Step 3: Add resources and prompts
Tools are the headline feature, but resources and prompts make a server feel complete inside a host.
Resources: read-only context
A resource is a piece of content identified by a URI. Hosts show them in a picker so the user can attach, say, the returns policy to the conversation. A URI template with {placeholders} exposes a whole family of resources from one method:
// Resources/PolicyResources.cs
using System.ComponentModel;
using ModelContextProtocol.Server;
[McpServerResourceType]
public sealed class PolicyResources(IWebHostEnvironment env)
{
[McpServerResource(UriTemplate = "contoso://policies/{name}", Name = "Store policy", MimeType = "text/markdown")]
[Description("Contoso store policies: returns, shipping, warranty.")]
public async Task<string> GetPolicy(string name)
{
// Allow-list the names: never build a file path straight from client input
string[] allowed = ["returns", "shipping", "warranty"];
if (!allowed.Contains(name))
throw new ArgumentException($"Unknown policy '{name}'.");
var path = Path.Combine(env.ContentRootPath, "Policies", $"{name}.md");
return await File.ReadAllTextAsync(path);
}
}
Prompts: reusable instructions
A prompt is a template the user invokes on purpose, typically as a slash command such as /draft_support_reply in the host. It returns one or more chat messages, and its parameters become a small form:
// Prompts/SupportPrompts.cs
using System.ComponentModel;
using Microsoft.Extensions.AI;
using ModelContextProtocol.Server;
[McpServerPromptType]
public static class SupportPrompts
{
[McpServerPrompt(Name = "draft_support_reply")]
[Description("Drafts a friendly, policy-compliant reply to a customer support email.")]
public static ChatMessage DraftSupportReply(
[Description("The customer's email text")] string customerEmail,
[Description("Tone: friendly, formal or apologetic")] string tone = "friendly") =>
new(ChatRole.User, $"""
You are a Contoso Outdoor Gear support agent. Write a {tone} reply to the email below.
Use the get_order_status tool if an order number is mentioned, and the
contoso://policies/returns resource for any return question.
Keep it under 150 words and do not promise refunds.
Customer email:
{customerEmail}
""");
}
Prompts are a good place to package your team's best practices. Notice how this one points the model at the server's own tool and resource, so a single slash command gives the user a well-grounded result.
Step 4: Try it with MCP Inspector and VS Code
Run the server with dotnet run and note the URL (for example http://localhost:5000). The MCP endpoint is at /mcp.
Until you add authentication in Step 6, comment out the [Authorize] attribute on OrderTools, or the order tools will reject every call. Fake a customer ID while testing.
MCP Inspector
The official MCP Inspector is a browser UI for poking at any server. It needs Node.js:
npx @modelcontextprotocol/inspector
Choose the Streamable HTTP transport, enter http://localhost:5000/mcp and connect. You can then:
open Tools, see the generated JSON schema for search_products, fill in query and run it;
open Resources, and read contoso://policies/returns;
open Prompts, fill in draft_support_reply, and see the exact messages it produces.
If a description reads awkwardly here, it will confuse the model too. Fix it before going further.
VS Code with GitHub Copilot
Add a .vscode/mcp.json file to any workspace:
{
"servers": {
"contoso-store": {
"type": "http",
"url": "http://localhost:5000/mcp"
}
}
}
Start the server from the CodeLens link VS Code shows above the entry, open Copilot Chat in Agent mode, and ask:
Find me a waterproof two-person tent under $300 that's in stock.
Copilot calls search_products, asks you to approve the call the first time, and answers from your real catalog data. Your prompt also shows up as /mcp.contoso-store.draft_support_reply.
Claude and other hosts
Any MCP host that supports remote servers can connect to the same URL. Claude, for example, lets you add a remote MCP server as a custom connector. Remote hosts need a public HTTPS URL, so deploy the server (Step 7) or use a dev tunnel during development:
devtunnel host -p 5000 --allow-anonymous
Use anonymous tunnel access only with test data, or once the server's own authentication (Step 6) is switched on.
Step 5: Use the server from your own .NET app
MCP is not only for off-the-shelf assistants. Your own agents can consume the same server, and it plugs straight into the IChatClient pipeline from the previous article. Add the client package to a console app or another web app:
dotnet add package ModelContextProtocol
dotnet add package Microsoft.Extensions.AI
dotnet add package Microsoft.Extensions.AI.OpenAI
using Microsoft.Extensions.AI;
using ModelContextProtocol.Client;
using OpenAI;
// 1. Connect to the MCP server over Streamable HTTP
var transport = new HttpClientTransport(new HttpClientTransportOptions
{
Endpoint = new Uri("https://localhost:5001/mcp"),
AdditionalHeaders = new Dictionary<string, string>
{
["Authorization"] = $"Bearer {accessToken}" // see Step 6
}
});
await using var mcp = await McpClient.CreateAsync(transport);
// 2. Discover the tools
IList<McpClientTool> tools = await mcp.ListToolsAsync();
foreach (var tool in tools)
Console.WriteLine($"{tool.Name}: {tool.Description}");
// 3. Give them to any IChatClient
IChatClient chat = new OpenAIClient(Environment.GetEnvironmentVariable("OPENAI_API_KEY"))
.GetChatClient("gpt-5.4-mini")
.AsIChatClient()
.AsBuilder()
.UseFunctionInvocation()
.Build();
var response = await chat.GetResponseAsync(
"Where is my order ORD-10421, and can I still return it?",
new ChatOptions { Tools = [.. tools] });
Console.WriteLine(response.Text);
This works because McpClientTool derives from MEAI's AIFunction. The function-invocation middleware sees an ordinary tool; when the model calls it, the call is forwarded over HTTP to the MCP server, which runs your C# method and returns the result. Swap in a different model provider and nothing else changes.
You can also call a tool directly, with no model involved, which is handy in integration tests:
var result = await mcp.CallToolAsync(
"search_products",
new Dictionary<string, object?> { ["query"] = "tent", ["maxPrice"] = 300 });
Step 6: Secure the server
An MCP server is an API that an AI can drive, so secure it at least as carefully as any public API. Remote MCP uses standard OAuth 2.1: the MCP server is a protected resource, and an identity provider you already use (Microsoft Entra ID, Auth0, Keycloak, Duende IdentityServer) issues the tokens.
Authentication
Add the JWT bearer handler as usual, plus the SDK's MCP authentication handler. The MCP handler publishes protected resource metadata, which tells MCP clients which authorization server to send the user to and which scopes to request; compliant clients then run the sign-in flow on their own.
using Microsoft.AspNetCore.Authentication.JwtBearer;
using ModelContextProtocol.AspNetCore.Authentication;
var authority = builder.Configuration["Auth:Authority"]!; // e.g. https://login.contoso.com
var serverUrl = builder.Configuration["Mcp:PublicUrl"]!; // e.g. https://mcp.contoso.com/mcp
builder.Services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Authority = authority;
options.Audience = serverUrl; // tokens must be issued for THIS server
})
.AddMcp(options =>
{
options.ResourceMetadata = new()
{
Resource = new Uri(serverUrl),
AuthorizationServers = { new Uri(authority) },
ScopesSupported = ["mcp:tools"]
};
});
builder.Services.AddAuthorization();
Authorization
Call AddAuthorizationFilters() on the MCP builder so the SDK honours standard [Authorize] and [AllowAnonymous] attributes on tool, resource and prompt classes and methods, and require authentication on the endpoint itself:
builder.Services
.AddMcpServer()
.WithHttpTransport()
.AddAuthorizationFilters()
.WithToolsFromAssembly()
.WithResourcesFromAssembly()
.WithPromptsFromAssembly();
// ...
app.UseAuthentication();
app.UseAuthorization();
app.MapMcp("/mcp").RequireAuthorization();
Role-based rules work exactly as they do in controllers. A tool that only support staff may use:
[McpServerToolType]
[Authorize(Roles = "SupportAgent")]
public sealed class AgentTools(IOrderRepository orders)
{
[McpServerTool(Name = "lookup_any_order", ReadOnly = true)]
[Description("Support staff only: looks up any customer's order by number.")]
public async Task<Order?> LookupAnyOrder(string orderNumber, CancellationToken ct) =>
await orders.FindAsync(orderNumber, ct);
}
Tools the caller is not allowed to use are hidden from their tool list, so the model never even sees them.
Checklist for production MCP servers
Validate the audience. Only accept tokens issued for your MCP server. Never accept a token meant for another API.
Don't pass the user's token through. If a tool calls a downstream API, get a separate token for that API (for example with the on-behalf-of flow) instead of forwarding the one the MCP client sent.
Authorise inside the tool, too. [Authorize] decides who may call a tool; the ownership check in GetOrderStatus decides which data they may see.
Mark side effects. Set Destructive = true on tools that change or delete data, so hosts ask the user before running them, and keep refunds or cancellations behind an explicit confirmation step.
Treat returned data as untrusted. Product reviews or customer emails your tools return can contain text such as "ignore previous instructions". Return only the fields the task needs.
Rate-limit /mcp. Agents can call tools in tight loops. Use RequireRateLimiting(...) on the endpoint just as you would for a public API.
Restrict origins. For browser-based clients, configure CORS to the hosts you trust.
Step 7: Deploy and run it in production
An HTTP MCP server is just an ASP.NET Core app, so it deploys anywhere your APIs do: Azure App Service, Azure Container Apps, Kubernetes, AWS, or a plain VM. A minimal container build:
dotnet publish -c Release /t:PublishContainer -p ContainerRepository=contoso-mcp
Things to get right:
Topic | Recommendation |
|---|
Scaling | Stay stateless (the SDK v2 default). Any instance can serve any request, so no sticky sessions are needed. Only set Stateless = false if you rely on server-to-client features that need a session. |
HTTPS | Required for remote hosts. Terminate TLS at your gateway or in Kestrel. |
Timeouts | Long tool calls tie up agents. Keep tools fast; for work that takes minutes, look at the SDK's Tasks extension (ModelContextProtocol.Extensions.Tasks). |
Observability | Use your normal ASP.NET Core logging and OpenTelemetry. Log tool name, caller and duration for every call; this is your audit trail of what agents did on users' behalf. |
Versioning | Treat tool names and parameters as a public contract. Add new tools or optional parameters; avoid renaming or removing existing ones without a deprecation period. |
Health checks | Map /health separately from /mcp so your load balancer does not need an MCP token. |
For local developer tools that need file-system access, ship a stdio server instead. Use the mcpserver template with stdio transport and publish it as a .NET tool on NuGet, so users can run it with dnx without cloning your repository.
Conclusion
With a single NuGet package and a few attributes, an existing ASP.NET Core app becomes something every MCP-aware assistant can use. Contoso.Mcp now:
exposes catalog and order tools with DI and per-user data access,
serves store policies as resources and a support-reply prompt,
runs statelessly over Streamable HTTP, ready to scale behind a load balancer,
is protected with OAuth tokens, [Authorize] attributes and in-tool ownership checks,
and is consumed by VS Code, Claude, MCP Inspector and our own IChatClient agent alike.
The key mindset: an MCP server is a public API whose caller is a model. Design focused tools, describe them well, and keep every security decision in C#.
Where to go next:
Combine this with the first article: point SupportDesk AI at Contoso.Mcp instead of in-process tools.
Explore multi-round-trip requests in the 2026-07-28 spec, so a tool can ask the user to confirm before acting.
Try MCP Apps (ModelContextProtocol.Extensions.Apps) to return small interactive UIs inside the chat.
Build agents that orchestrate several MCP servers with the Microsoft Agent Framework.
Happy coding! Share the MCP servers you build in the comments.
References
Join the conversation! Your thoughts help the community grow.