Build an MCP server in .NET that exposes your existing services
Quando usar: You're on .NET and want to expose business logic to agents without a rewrite.
Pré-requisitos
- .NET 8+ SDK —
dotnet --version
Fluxo
-
Create the projectdotnet new console -n MyMcpServer. Add
ModelContextProtocolNuGet. Use the minimal hosting template for MCP.✓ Copiado→ csproj + Program.cs with MCP hosted service -
Add a toolCreate a static class with
[McpServerToolType]. Add a methodGetOrder(string id)decorated with[McpServerTool(Description="...")]that calls my existing OrderService via DI.✓ Copiado→ Tool compiles, description comes from attribute -
Test with the inspectorRun the server as stdio. Launch the MCP Inspector via
npx @modelcontextprotocol/inspector dotnet run. Call GetOrder.✓ Copiado→ Tool invocation returns order JSON
Resultado: A compiled, typed MCP server reusing your existing .NET services and DI container.
Armadilhas
- Tool methods that are instance methods on a class need DI to work — Register the owning class in the ServiceCollection; the SDK resolves through DI
- Async methods without proper cancellation tokens hang at shutdown — Accept
CancellationToken ctas the last parameter on every tool — SDK injects it