The Model Context Protocol (MCP) is an open standard that lets AI assistants discover and call tools provided by other systems. If you already have an ASP.NET Core API, an MCP server is a thin layer that makes a chosen part of it available to assistants, under your own authentication and authorisation rules. This article walks through a small orders example and the controls we consider essential.

The SDK

The official C# SDK is maintained by the Model Context Protocol project in collaboration with Microsoft. It reached version 1.0 in March 2026 (announcement) and has had further releases since. It ships as three NuGet packages:

  • ModelContextProtocol.Core: client and low-level server APIs with minimal dependencies.
  • ModelContextProtocol: hosting, dependency injection and attribute-based tool discovery.
  • ModelContextProtocol.AspNetCore: HTTP-based servers hosted in ASP.NET Core. This is the one you need here, and it brings in the other two.
dotnet add package ModelContextProtocol.AspNetCore

The code below follows the SDK's current documentation. APIs can change between major versions, so check the documentation for the version you install.

Decide what the assistant should be able to do

Do not mirror every API endpoint as a tool. Assistants choose tools from their names and descriptions, so a small set of task-shaped tools works better than a large set of thin CRUD wrappers, and it is much easier to secure. For an order system, a reasonable first set is:

  • Read-only: get one order; list recent orders for a customer.
  • Write, with a human in the loop: request a cancellation, which a member of staff then approves.

Note what is missing: no tool cancels an order directly, edits prices or exposes payment data. Start read-only, run it for a while, and add write tools one at a time.

Where the MCP server runs

There are two reasonable designs:

  • Inside the existing API, calling your application services directly. Simple to deploy, but the MCP endpoint shares the API's process, scaling and release cycle.
  • As a separate ASP.NET Core application that calls your API over HTTP with its own narrowly scoped credentials. More moving parts, but the existing API's own authorisation rules apply to every call the assistant makes, and you can switch the MCP server off without touching the API.

For a first production deployment we lean towards the separate application. The example below is written so the tool class works either way: it depends on an IOrderService interface that you implement with direct calls or an HTTP client.

Program.cs

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.RateLimiting;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = builder.Configuration["Auth:Authority"];
        options.Audience = builder.Configuration["Auth:Audience"];
    });
builder.Services.AddAuthorization();

builder.Services.AddRateLimiter(options =>
{
    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
    options.AddFixedWindowLimiter("mcp", limiter =>
    {
        limiter.PermitLimit = 60;
        limiter.Window = TimeSpan.FromMinutes(1);
    });
});

builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddScoped<IAuditLog, AuditLog>();

builder.Services.AddMcpServer()
    .WithHttpTransport()
    .AddAuthorizationFilters()   // enables [Authorize] on tools
    .WithTools<OrderTools>();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();

app.MapMcp("/mcp")
   .RequireAuthorization()
   .RequireRateLimiting("mcp");

app.Run();

Minimal illustrative example. In production, partition the rate limiter per user and load authentication settings from configuration you control.

WithToolsFromAssembly() is an alternative to WithTools<T>() that registers every class marked [McpServerToolType]. Listing tool types explicitly makes it harder to publish a tool by accident.

The tools

using System.ComponentModel;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using ModelContextProtocol;
using ModelContextProtocol.Server;

[McpServerToolType]
public sealed class OrderTools(IOrderService orders, IAuditLog audit)
{
    [McpServerTool(Name = "get_order", ReadOnly = true, OpenWorld = false)]
    [Description("Gets status, dates and line totals for one order. Never returns payment details.")]
    [Authorize(Roles = "Orders.Read")]
    public async Task<OrderSummary> GetOrder(
        [Description("Order number in the form SO-123456")] string orderNumber,
        ClaimsPrincipal? user,
        CancellationToken cancellationToken)
    {
        if (!OrderNumber.IsValid(orderNumber))
            throw new McpException("Order number must be in the form SO-123456.");

        var order = await orders.GetSummaryAsync(orderNumber, cancellationToken)
            ?? throw new McpException($"Order {orderNumber} was not found.");

        await audit.RecordAsync(user, "get_order", orderNumber, cancellationToken);
        return order;
    }

    [McpServerTool(Name = "list_customer_orders", ReadOnly = true, OpenWorld = false)]
    [Description("Lists up to 20 recent orders for one customer account, newest first.")]
    [Authorize(Roles = "Orders.Read")]
    public async Task<IReadOnlyList<OrderSummary>> ListCustomerOrders(
        [Description("Customer account number in the form C-10045")] string customerAccount,
        [Description("Optional status filter")] OrderStatus? status,
        ClaimsPrincipal? user,
        CancellationToken cancellationToken)
    {
        if (!CustomerAccount.IsValid(customerAccount))
            throw new McpException("Customer account must be in the form C-10045.");

        var result = await orders.ListRecentAsync(customerAccount, status, take: 20, cancellationToken);
        await audit.RecordAsync(user, "list_customer_orders", customerAccount, cancellationToken);
        return result;
    }

    [McpServerTool(Name = "request_order_cancellation", ReadOnly = false,
        Destructive = false, Idempotent = true, OpenWorld = false)]
    [Description("Creates a cancellation request that a staff member must approve. " +
                 "Does not cancel the order.")]
    [Authorize(Roles = "Orders.RequestCancellation")]
    public async Task<CancellationRequestResult> RequestOrderCancellation(
        [Description("Order number in the form SO-123456")] string orderNumber,
        [Description("Reason given by the customer, maximum 500 characters")] string reason,
        ClaimsPrincipal? user,
        CancellationToken cancellationToken)
    {
        if (!OrderNumber.IsValid(orderNumber))
            throw new McpException("Order number must be in the form SO-123456.");
        if (string.IsNullOrWhiteSpace(reason) || reason.Length > 500)
            throw new McpException("Reason is required and must be 500 characters or fewer.");

        // Returns the existing pending request if there is one, so repeated calls are safe.
        var request = await orders.CreatePendingCancellationAsync(
            orderNumber, reason, requestedBy: user, cancellationToken);

        await audit.RecordAsync(user, "request_order_cancellation", orderNumber, cancellationToken);

        return new CancellationRequestResult(
            request.Reference,
            Status: "PendingApproval",
            Message: $"Request {request.Reference} must be approved in the order system before anything changes.");
    }
}

Minimal illustrative example. IOrderService, IAuditLog, the validators and the result types are your own code.

A few details are worth pointing out:

  • [Description] text is part of the interface. The assistant reads it to decide which tool to call and what to pass. Be precise, and say what the tool does not do.
  • ClaimsPrincipal parameters are filled in by the SDK from the authenticated request and are not shown to the assistant as inputs.
  • McpException messages are returned to the client as a tool error the assistant can read and correct. Other exceptions are reported with a generic message, so internal details do not leak.
  • ReadOnly, Destructive and Idempotent are annotations: hints that help a client decide how much to ask the user. They are not enforced, and a client may ignore them. Enforcement belongs on the server.

Human confirmation for writes

The cancellation tool never cancels anything. It records a pending request that a member of staff approves in the existing back-office system. This pattern does not depend on the assistant or the MCP client behaving well, and the approval sits in the same place, with the same audit trail, as approvals that come from any other channel.

MCP also defines elicitation, where the server asks the user a question through the client during a tool call. It is useful for confirmations inside the conversation, but its availability depends on the client and on the transport and session mode, so check the SDK documentation before relying on it. For anything that moves money, stock or customer data, we still prefer an out-of-band approval.

Security checklist

  • Authentication. Require it on the MCP endpoint (RequireAuthorization()). The MCP specification defines an OAuth-based authorisation flow, and the SDK can publish the protected resource metadata that compliant clients use to find your authorisation server.
  • Least privilege. Give each tool its own role or scope. If the MCP server calls your API, give it credentials that can reach only the endpoints its tools need. Never reuse an administrative API key.
  • Input validation. Arguments are generated by a language model and must be treated like any untrusted input: validate formats, lengths and ranges, use parameterised queries, and cap result sizes.
  • Audit logging. Record who called which tool, with which arguments, from which client, and the outcome. Keep personal data out of the log where you can.
  • Treat tool output as untrusted. Free-text fields such as order notes or customer messages can contain instructions aimed at the assistant (prompt injection). Return only the fields the task needs, trim long text, and do not let a read tool's output be the sole trigger for a write.
  • Rate limits. Assistants can call tools in loops. Limit per user and per tool, and alert on unusual volumes.
  • Transport. HTTPS only. Keep the endpoint off the public internet if your clients do not need it there.

Testing

Unit-test the tool methods like any other code: they are ordinary C# methods. For end-to-end checks, the MCP Inspector connects to a server, lists its tools and lets you call them by hand, which is the quickest way to see what an assistant will see. Before release, test the failure cases deliberately: an unauthenticated call, a user without the write role, malformed arguments and a request that exceeds the rate limit.

Connecting AI assistants to your systems?

We design and build MCP servers and other AI integrations on top of existing .NET applications, with the security controls in place from the start.

AI automation