Model Context Protocol MCP in .NET and C# with Visual Studio

 

Introduction

Model Context Protocol (MCP) is an open protocol that standardizes how applications expose tools and context to large language models and other AI clients. In the .NET ecosystem you can implement MCP servers and clients using an official C# SDK, enabling your applications to surface commands, data connectors, and interactive tools to LLM-driven agents and IDE integrations.


Why MCP matters for .NET developers

  • Unifies how external tools and data sources are discovered and invoked by LLM agents.
  • Lets you expose small reusable “tools” (functions, connectors, workflows) from a .NET service that AI clients can enumerate and call.
  • Integrates with common .NET hosting, dependency injection, and ASP.NET Core patterns, making adoption straightforward for existing projects.

Prerequisites

  • .NET SDK (recommended latest preview/stable that supports the MCP packages). Microsoft documentation and templates may require .NET 10 preview in some quickstarts.
  • Visual Studio 2022/2025 or Visual Studio Code with C# tooling; Visual Studio gives tight integration for building, debugging and packaging NuGet artifacts.
  • NuGet account if you plan to publish packages or tools.
  • The ModelContextProtocol NuGet packages (preview channel) from the official C# SDK.

Key packages and resources

  • ModelContextProtocol (main hosting & DI extensions) — good for most server implementations.
  • ModelContextProtocol.AspNetCore — for HTTP-hosted MCP servers.
  • ModelContextProtocol.Core — minimal client or low-level server needs.
  • Official docs and quickstarts from Microsoft and the C# SDK GitHub repo provide sample templates and a dotnet new template to scaffold MCP servers.

Quick workflow (create a simple MCP server using Visual Studio)

  1. Create the project
    • In Visual Studio, choose “Create a new project” → Console App (.NET) or ASP.NET Core Web API (if you want HTTP transport). Name it e.g., McpSampleServer.
  2. Add MCP NuGet package(s)
    • In Solution Explorer right-click Dependencies → Manage NuGet Packages → Browse → install ModelContextProtocol (use prerelease if needed) and ModelContextProtocol.AspNetCore for HTTP hosting.
  3. Configure hosting and services
    • Use generic host builder and add MCP server services via extension methods provided by the SDK (AddMcpServer, WithStdioServerTransport or WithHttpServerTransport).
  4. Implement tools
    • Create static or instance methods annotated or configured as MCP tools (the SDK supports automatic tool discovery patterns or explicit registration). Tools should be designed to accept and return serializable payloads (simple types, DTOs) to make invocation and result passing straightforward.
  5. Run and test
    • Launch the app from Visual Studio. For stdio transport you can connect with editor integrations (e.g., GitHub Copilot in agent mode) or test client code that creates an McpClient to connect locally; for HTTP transport, call the server endpoints with a compliant MCP client or the SDK’s client helper APIs.

Minimal example (Program.cs for a console MCP server)

using Microsoft.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using ModelContextProtocol.Server; var builder = Host.CreateApplicationBuilder(args); builder.Logging.AddConsole(); builder.Services .AddMcpServer() .WithStdioServerTransport() // or .WithHttpServerTransport() for HTTP .WithToolsFromAssembly(); await builder.Build().RunAsync(); 

This pattern wires the MCP server into the generic host pipeline, enables a stdio transport, and auto-registers tools found in the assembly.


Example tool implementation

using ModelContextProtocol.Server; public static class DemoTools { [McpServerTool(Description = "Return input uppercased")] public static string Uppercase(string text) => text?.ToUpperInvariant() jQuery152009994888188936357_1762593257266 string.Empty; [McpServerTool(Description = "Get a random number in range")] public static int GetRandomNumber(int min, int max) => Random.Shared.Next(min, max + 1); } 

Registering tools via attributes or SDK registration APIs makes them discoverable by MCP clients and IDE agent integrations.


Testing with clients and editor integrations

  • Visual Studio and Visual Studio Code can be configured to run/consume MCP servers. Microsoft’s quickstart shows how to create an mcp.json workspace configuration so editor agents (like GitHub Copilot in agent mode) can call your server tools via stdio transport.
  • You can also write a small McpClient in .NET to connect to your server programmatically using the SDK’s client APIs (McpClient.CreateAsync and client transport implementations).

Packaging and publishing

  • If you intend to share tools or server packages, set a unique PackageId in your .csproj and publish to NuGet. Microsoft’s quickstart demonstrates publishing a sample MCP server package to NuGet for reuse by others.

Tips and best practices

  • Design tools to be idempotent and safe; callers (LLM agents) may retry tool invocations.
  • Keep inputs and outputs small and well-typed (JSON-serializable DTOs) to simplify schema validation and versioning.
  • Use dependency injection for tool implementations so you can test logic independently and swap implementations (e.g., mock data connectors).
  • Consider using HTTP transport (ModelContextProtocol.AspNetCore) for remote or production deployments, and stdio for local editor/tooling integrations and debugging.

 

 

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

Topics Highlights

About @ridife

This blog will be dedicated to integrate a knowledge between academic and industry need in the Software Engineering, DevOps, Cloud Computing and Microsoft 365 platform. Enjoy this blog and let's get in touch in any social media.

Month List

Visitor