How to Build an MCP Server with .NET for Enterprise AI Applications

How to Build an MCP Server with .NET for Enterprise AI Applications

As enterprise organizations deploy artificial intelligence applications, Microsoft-centric engineering teams require a scalable, type-safe architecture for connecting Large Language Models (LLMs) to enterprise backends. Building a Model Context Protocol (MCP) server with .NET and C# enables developers to expose business data, APIs, and microservice workflows to AI clients cleanly and securely.

Quick Summary: Building an enterprise MCP server using ASP.NET Core allows developers to leverage existing .NET application logic, Entity Framework Core repositories, Dependency Injection, and Azure authentication middleware. By wrapping existing service boundaries into standardized MCP tools, software architects create high-throughput, secure gateways for AI assistants.


Table of Contents

Open Table of Contents

The Case for .NET in Enterprise AI Integration

Enterprise software ecosystems heavily depend on .NET for core business applications, Microsoft SQL Server databases, ERP systems, and microservices. Implementing your MCP server infrastructure in .NET offers key advantages:

  1. Reuse of Existing Business Logic: Inject existing C# domain services, validators, and data mappers directly into MCP tool handlers without rewriting logic in Node.js or Python.
  2. Superior Performance: Benefit from .NET 9 performance enhancements, Native AOT compilation, high-throughput Minimal APIs, and low-allocation JSON parsing (System.Text.Json).
  3. Enterprise Security Standards: Native support for Microsoft Entra ID (Azure AD), OAuth 2.0 Bearer authentication, and Azure Key Vault integration.

To review basic protocol specifications before diving into C# code structures, read our overview on what Model Context Protocol (MCP) is.


.NET MCP Architecture Overview

An enterprise .NET MCP server functions as an API gateway between the external AI application (MCP Host) and your internal domain infrastructure:

[ AI Host / Client ]  
        |
        |  JSON-RPC 2.0 over HTTP-SSE / WebSockets
        v
+-------------------------------------------------------------+
|                     ASP.NET Core Web API                    |
|                                                             |
|   +-------------------+    +----------------------------+   |
|   | Auth Middleware   | -> | MCP Transport Controller   |   |
|   +-------------------+    +----------------------------+   |
|                                         |                   |
|                                         v                   |
|                            +------------------------+       |
|                            | MCP Tool Router        |       |
|                            +------------------------+       |
|                                         |                   |
+-----------------------------------------|-------------------+
                                          | (Scoped DI)
                    +---------------------+---------------------+
                    |                                           |
                    v                                           v
       +-------------------------+                 +------------------------+
       | EF Core DB Context      |                 | External REST Client   |
       | (Read-Only Azure SQL)   |                 | (Internal Microservice)|
       +-------------------------+                 +------------------------+

Designing the ASP.NET Core MCP Server Stack

1. Project Structure & Minimal API Setup

Start by creating a clean ASP.NET Core Web API project targeted for .NET 9:

dotnet new webapi -n Enterprise.McpServer

Organize your project into clear architectural layers:

Enterprise.McpServer/
├── Controllers/         # MCP Transport endpoints (JSON-RPC)
├── Services/            # Business logic wrappers
├── Tools/               # MCP Tool schemas & handlers
├── Infrastructure/      # EF Core DbContext & Azure Key Vault
└── Program.cs           # DI registration & pipeline configuration

2. Tool Registration & Reflection Engine

Expose C# methods as discoverable MCP tools using C# attributes and JSON Schema generation:

// Definition of a strongly typed MCP Tool in C#
[AttributeUsage(AttributeTargets.Method)]
public class McpToolAttribute : Attribute
{
    public string Name { get; }
    public string Description { get; }

    public McpToolAttribute(string name, string description)
    {
        Name = name;
        Description = description;
    }
}

public class CustomerMcpTools
{
    private readonly ICustomerService _customerService;

    public CustomerMcpTools(ICustomerService customerService)
    {
        _customerService = customerService;
    }

    [McpTool("get_customer_profile", "Fetches customer metadata and support tier by Customer ID.")]
    public async Task<CustomerProfileDto> GetCustomerProfileAsync(string customerId)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(customerId);
        return await _customerService.GetProfileByIdAsync(customerId);
    }
}

3. Dependency Injection (DI) Lifecycle

Register MCP tool classes and their underlying dependencies within Program.cs:

var builder = WebApplication.CreateBuilder(args);

// Add infrastructure services
builder.Services.AddDbContext<ReadOnlyDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("AzureSqlReadOnly")));

builder.Services.AddScoped<ICustomerService, CustomerService>();

// Register Tool Handlers
builder.Services.AddScoped<CustomerMcpTools>();

var app = builder.Build();

Database Integration with Entity Framework Core

When invoking database operations inside an MCP server, utilize Entity Framework Core configured with non-tracking queries for optimal read-only performance:

public class CustomerService : ICustomerService
{
    private readonly ReadOnlyDbContext _db;

    public CustomerService(ReadOnlyDbContext db)
    {
        _db = db;
    }

    public async Task<CustomerProfileDto?> GetProfileByIdAsync(string customerId)
    {
        return await _db.Customers
            .AsNoTracking() // Prevent change-tracking allocation overhead
            .Where(c => c.Id == customerId)
            .Select(c => new CustomerProfileDto(c.Id, c.Name, c.Tier, c.Status))
            .FirstOrDefaultAsync();
    }
}

To examine safety guidelines when connecting relational databases to AI tools, explore our deep dive on connecting SQL Server to AI using MCP.


Authentication & Authorization Middleware

Protecting your ASP.NET Core MCP server requires validating Microsoft Entra ID JWT tokens passed from the host:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("McpAccessPolicy", policy =>
        policy.RequireClaim("scp", "Mcp.Tools.ReadWrite"));
});

// Enforce authentication on MCP endpoints
app.MapPost("/mcp/v1/rpc", async (HttpContext context, McpRouter router) =>
{
    return await router.HandleRequestAsync(context);
}).RequireAuthorization("McpAccessPolicy");

Configuration & Azure Secret Management

Avoid placing credentials in configuration files. Utilize Azure Key Vault to load secrets dynamically into IConfiguration at application launch:

if (builder.Environment.IsProduction())
{
    var keyVaultUri = new Uri(builder.Configuration["AzureKeyVault:Endpoint"]!);
    builder.Configuration.AddAzureKeyVault(keyVaultUri, new DefaultAzureCredential());
}

For detailed cloud configuration best practices, see our tutorial on fixing Azure App Service Key Vault reference identity issues.


Production Deployment: Azure Container Apps & App Service

Deploy your .NET MCP server using containerized microservices on Azure:

# Multi-stage Dockerfile for ASP.NET Core MCP Server
FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS base
WORKDIR /app
EXPOSE 8080

FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
WORKDIR /src
COPY ["Enterprise.McpServer.csproj", "./"]
RUN dotnet restore
COPY . .
RUN dotnet publish -c Release -o /app/publish /p:UseAppHost=false

FROM base AS final
WORKDIR /app
COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "Enterprise.McpServer.dll"]

Deploying to Azure Container Apps provides auto-scaling to zero when idle, lowering cloud infrastructure costs while maintaining instant responsiveness upon receiving AI tool calls.

To learn how specialized engineering teams accelerate enterprise solutions, explore Vineforce AI Database Integration Solutions.


Frequently Asked Questions (FAQ)

Why build an MCP server using .NET and C#?

ASP.NET Core provides enterprise-grade performance, high-throughput Minimal APIs, native Dependency Injection, robust middleware for Entra ID authentication, and seamless integration with existing .NET microservices and SQL Server databases.

How does Dependency Injection (DI) work inside a .NET MCP server?

MCP tool handlers register with the standard ASP.NET Core IServiceCollection. When an MCP client invokes a tool call, the server resolves database contexts (EF Core), repositories, and HTTP clients within a scoped execution pipeline.

Can a .NET MCP server transport messages over HTTP with Server-Sent Events (SSE)?

Yes. While stdio transport is common for local desktop integrations, enterprise remote MCP servers hosted on Azure typically use HTTP with Server-Sent Events (SSE) or WebSockets over JSON-RPC 2.0.

How should configuration and database secrets be managed in a .NET MCP service?

Use standard .NET configuration providers (IConfiguration) combined with Azure Key Vault secrets and Azure App Configuration to keep connection strings and API keys out of repository source code.


Conclusion

Building an MCP server with .NET enables Microsoft-centric engineering organizations to deliver secure, high-performance gateways between LLMs and core business systems. By taking advantage of ASP.NET Core Minimal APIs, EF Core, and Azure Entra ID, developers turn complex AI data requests into maintainable, strongly typed enterprise logic.

Need help connecting your existing application or business data with AI? Vineforce can help design and implement a secure MCP architecture around your existing databases, APIs, authentication, authorization, and business rules.