Build an MCP server in .NET that exposes your existing services
Когда использовать: You're on .NET and want to expose business logic to agents without a rewrite.
Предварительные требования
- .NET 8+ SDK —
dotnet --version
Поток
-
Create the projectdotnet new console -n MyMcpServer. Add
ModelContextProtocolNuGet. Use the minimal hosting template for MCP.✓ Скопировано→ 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.✓ Скопировано→ 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.✓ Скопировано→ Tool invocation returns order JSON
Итог: A compiled, typed MCP server reusing your existing .NET services and DI container.
Подводные камни
- 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