Back to BlogMCP and .NET

MCP in .NET: giving AI arms and eyes to your legacy system

Igor Waterloo, CTO & FounderOct 18, 20269 min

Most AI demos I see in .NET companies die in the same place: the model is great, but it cannot see the system that actually runs the business.

The 15-year-old ERP, the WCF service nobody dares to touch, the SQL Server with business rules in stored procedures. That is where the value is. And that is where AI usually stays out, or comes in through a copy-and-paste hack.

What MCP is, without the hype

MCP (Model Context Protocol) changes this game, and the official C# SDK reduces the effort to something on the scale of an afternoon for a first prototype, not a project of months. In this article I show what it is, how to build a server in C# and where it fits in a legacy modernization.

The common reaction is to think about rewriting everything before "turning on the AI". It is expensive, it is risky and almost always unnecessary. There is a shorter path: expose the legacy system as a set of tools an agent can call, without touching the heart of the system.

MCP is an open protocol, created by Anthropic, that standardizes how an AI application talks to external systems. Think of it as a "USB-C for AI": instead of each integration being custom code for each model, you write a server once and any compatible client can use it.

There are three roles:

  • Host/client: the app where the model runs, such as Claude Desktop, Claude Code or an IDE.
  • MCP server: the process you write, which exposes capabilities of your system.
  • Capabilities: tools (actions the model can call), resources (data it can read) and prompts (reusable scripts).

In practice, most of the initial value is in tools. A tool is a C# method with a natural-language description. The model reads the description, decides when to call it, and you control what the method does.

For those with legacy systems, the value lies in three points:

  • You do not rewrite the system. The MCP server sits next to it and calls what already exists: services, repositories, procedures or old DLLs.
  • You decide what the agent can do. Each tool is a method with a name, description and typed parameters. The agent only sees what you publish.
  • You are not locked into an AI vendor. The same server serves different models and clients on the market.

The architecture

The design is simple on purpose: the agent talks only to the MCP server, and the server talks to the legacy system through a layer that translates and protects.

Agente de IA  →  Servidor MCP (C#)  →  Camada anti-corrupção  →  Sistema legado

The legacy system stays as it is. All the new logic, from tool descriptions to parameter validation and auditing, lives in the C# server, where you have full control.

In practice: an MCP server in C#

The official SDK is the ModelContextProtocol NuGet package. At the time of writing, the stable version listed on NuGet is 2.x, with support for .NET 8, 9 and 10. Check the version before copying: the SDK evolves fast and the API may change between major versions.

I will use a common legacy example: querying an order's status in an old system. The project is a console application on .NET 8 (or later) with two packages:

dotnet new console -n Legado.Mcp
cd Legado.Mcp
dotnet add package ModelContextProtocol
dotnet add package Microsoft.Extensions.Hosting

1. The entry point

The server uses the .NET generic host. The stdio transport (standard input and output) is the simplest way to start, because the AI client launches the process locally.

An important detail: logs must go to the error output, since standard output is used exclusively for protocol messages. A plain Console.WriteLine in the server corrupts the communication.

var builder = Host.CreateApplicationBuilder(args);

// Logs na saída de erro, para não corromper o canal do MCP
builder.Logging.AddConsole(o =>
    o.LogToStandardErrorThreshold = LogLevel.Trace);

builder.Services.AddSingleton<IPedidoLegadoGateway, PedidoLegadoGateway>();

builder.Services
    .AddMcpServer()
    .WithStdioServerTransport()
    .WithToolsFromAssembly();

await builder.Build().RunAsync();

2. The anti-corruption layer

The agent never talks directly to the legacy system. Between the two sits a small interface that translates the old model into a clean contract. The gateway can encapsulate a call to an old DLL, a WCF service, a SOAP API or a database view.

public record PedidoResumo(
    int Numero,
    string Status,
    DateTime DataPrevistaEntrega);

public interface IPedidoLegadoGateway
{
    Task<PedidoResumo?> ObterAsync(int numero, CancellationToken ct);
}

3. The tool

Each marked method becomes a tool the agent can call. The descriptions are not decoration: the model reads them to decide when and how to use the tool.

using System.ComponentModel;
using ModelContextProtocol.Server;

[McpServerToolType]
public class PedidosTools(IPedidoLegadoGateway legado)
{
    [McpServerTool, Description(
        "Consulta o status e a previsão de entrega de um pedido " +
        "pelo número. Somente leitura.")]
    public async Task<PedidoResumo?> ConsultarPedido(
        [Description("Número do pedido, apenas dígitos")] int numero,
        CancellationToken ct)
        => await legado.ObterAsync(numero, ct);
}

4. Connecting to the AI client

To test, register the server in the client you use, such as Claude Desktop, pointing to the project. In clients configured through a JSON file, the entry looks like this:

{
  "mcpServers": {
    "legado": {
      "command": "dotnet",
      "args": ["run", "--project", "caminho/para/Legado.Mcp", "--no-build"]
    }
  }
}

Build first with dotnet build: --no-build prevents compilation messages from reaching the protocol channel. In production, prefer pointing to the published executable.

In Claude Code, registration is a single line:

claude mcp add legado -- dotnet run --project caminho/para/Legado.Mcp --no-build

To debug before plugging into the client, use the MCP Inspector (npx @modelcontextprotocol/inspector), which lists the tools and lets you call them manually.

From there, a question like "what is the delivery forecast for order 48213?" makes the agent call ConsultarPedido, receive the typed JSON and answer in natural language.

5. Going to production

stdio is for development and local use. To serve several users or remote agents, the same server can be exposed over HTTP: add the ModelContextProtocol.AspNetCore package and configure the pipeline with WithHttpTransport() and app.MapMcp(). In that scenario, authentication and authorization become mandatory, and ASP.NET Core already provides that infrastructure.

Where this fits in legacy modernization

The real gain of MCP in C# is not a "chatbot that queries orders". It is creating a thin, governed layer between the AI and a system you do not want (or cannot) rewrite right now.

Three uses that make sense in modernization projects:

  1. Understand the legacy. Read tools that expose the database schema, dependencies between procedures and code snippets, so the model can help reverse-engineer business rules nobody documented.
  2. Validate the migration. A tool that runs the same rule on the old and the new system and returns the difference. The model becomes a comparator with context, not just a code generator.
  3. Operate with guardrails. Reuse the existing .NET services as tools, without opening the database directly to the model. The business rule stays where it has always been.

The architectural point: the MCP server calls the service layer you already trust, never the raw database. That way the AI inherits the validation, authorization and auditing that already exist.

The three scenarios above are patterns I recommend evaluating, not results measured at a specific client.

Security: start small and read-only

Giving an agent access to a system that moves money, inventory or sensitive data requires discipline. These are the rules I follow in projects of this kind:

  • Start with read tools. Queries first, writes later. Most of the initial value is in answering questions and cross-referencing data, not in executing actions.
  • Least privilege. The MCP server uses its own database or API credential, strictly limited to what the tools need. Never use administrator accounts.
  • No free-form SQL. The agent calls tools with typed parameters validated by you. Letting the AI build and run SQL opens a hole nobody audited.
  • Validate everything that arrives. To the server, arguments coming from the model are untrusted input, like any request from the internet. Limit sizes, value ranges and formats.
  • Human approval. When you reach write tools, make the AI only record an action proposal and require an operator to confirm before writing to the database.
  • Audit every call. Record who asked, which tool was called, with which parameters and what came back. In regulated sectors, this is often required.
  • Be careful with what comes back. The tool result enters the model's context. Return only the necessary properties and mask personal data, such as CPF and health data, to stay compliant with LGPD.
  • Be careful with third-party servers. Installing an MCP server of unknown origin means running third-party code on your machine.

The central point: the MCP server is your security boundary. Everything the agent can do goes through C# code you wrote, tested and versioned.

Common pitfalls

The mistakes I see most when teams start connecting agents to old systems:

  • Exposing the whole system at once. The more tools, the more the model gets confused when choosing. A few well-named, well-described tools work better than dozens of generic methods.
  • Vague descriptions. "Fetches data" does not help the model. Say what the tool does, what it receives and, if necessary, what it does not do.
  • Returning the legacy model untreated. Columns with cryptic names, such as ST_PED_VND, and internal codes make answers worse. Translate them into readable properties, such as StatusPedido, in the anti-corruption layer.
  • Ignoring performance. The legacy system was rarely designed for automated bursts of calls. Use caching, rate limiting and timeouts in the MCP server.
  • Skipping tests. The tools are ordinary C# classes and can have automated tests. Validate contracts and exception flows before exposing anything to the AI.

Where to start

Choose a query that today consumes a team's time, such as order status, balance or registration status. Expose it as a single read tool, put it in use with a small group and measure. If it works, the second and third cases become much cheaper.

Modernizing does not have to start by tearing down what sustains the operation. Often, it starts by giving the legacy system a new interface to talk to the future.

MCP does not replace modernization. It lowers the cost of making AI work with the system that exists while you decide what to rewrite, what to encapsulate and what to retire.

MCPC#.NETClaudeLegacy SystemsSecurity

Want to apply this in your operation?

Tell us about your environment and our team will assess the best path — with the pros, cons, and limits of each approach.