How to Build an MCP Client in ASP.NET Core 10 Using C# and Model Context Protocol – Complete Guide (2026)
How to Build an MCP Client in ASP.NET Core 10 Using C# and Model Context Protocol – Complete Guide (2026)
Suppose your support application needs to look up a product by SKU. Today the lookup runs in a local process. Tomorrow another team hosts the same capability behind HTTPS. An MCP client lets the application discover and invoke the tool using the same C# API while the transport changes underneath.
This guide builds a two-project catalog demo. Catalog.Server exposes a read-only product tool, a resource and a prompt. Catalog.Gateway connects over stdio or Streamable HTTP and exposes a small, protected ASP.NET Core API for Postman. Both projects target .NET 10 and pin the official MCP C# SDK to 2.3.1. The core demo runs without an LLM account or API key.
How do you build an MCP client in ASP.NET Core 10? Install ModelContextProtocol.Core, create an SDK transport for a trusted server, connect with McpClient.CreateAsync, and discover tools with ListToolsAsync. Validate the caller, the tool name and the arguments before using CallToolAsync. Dispose the client according to the lifetime of its connection.
What is an MCP client?
The Model Context Protocol standardizes the way applications interact with external capabilities. A host owns the application workflow and policy. It creates a client to communicate with each MCP server it uses. The server advertises the capabilities it implements and handles requests. In this example, the gateway is the host, an SDK McpClient handles each upstream interaction, and the catalog is the server. An LLM is optional.
A traditional REST API usually has endpoints and payloads defined by that application. MCP defines a shared set of JSON-RPC operations for discovery and invocation. You can keep REST at your user-facing boundary while using MCP between the gateway and upstream services. The HTTP transport carries MCP operations over HTTP. A GET to a conventional REST route and a tools/list RPC sent through the MCP endpoint are different interactions.
| Server feature | Protocol operations | Example |
|---|---|---|
| Tools | tools/list, tools/call |
Look up a SKU and return structured product data. |
| Resources | resources/list, resources/read |
Read help text at catalog://help/sku. |
| Prompts | prompts/list, prompts/get |
Retrieve a reusable message template. |
Resources can also be exposed through URI templates and discovered separately. A resource URI is an identifier sent to the MCP server. The gateway does not dereference it with an arbitrary HTTP client. Prompts are messages returned by the server. The application decides whether to display, adapt or send them to a model. See the MCP specification and tool requirements.
How initialization changed in the July 2026 specification
The 2026-07-28 revision declares the protocol version and client information per request. It supports server/discover for fetching capability information. The specification does not require this discovery call before other operations. SDK 2.3.1 uses it by default when creating a client and can fall back to the legacy handshake when the server requires an older protocol.
With 2025-11-25 and earlier, the sequence starts with initialize. The peers exchange version and capability information. The client then sends the notifications/initialized notification before ordinary operations. Earlier Streamable HTTP servers may issue an Mcp-Session-Id. Modern Streamable HTTP removes the protocol session header, which allows requests to be routed independently. The stdio child process still has a lifecycle and can hold application state.
The sample leaves McpClientOptions.ProtocolVersion unset for the SDK’s compatible path. Pinning 2026-07-28 requires that revision and disables downgrade. Pinning an older supported revision forces the older path. Choose a pin only when the interoperability contract warrants it. Version dates describe the wire protocol. The NuGet version describes the implementation you compile against. See versioning and compatibility, legacy lifecycle and the SDK client options.
Choose stdio or Streamable HTTP
Use stdio for a trusted local executable. The gateway starts the catalog DLL as a child process and exchanges protocol messages on standard input and output. The sample sends host logs to standard error. A banner or a plain Console.WriteLine in a stdio handler can corrupt the JSON-RPC stream. Build the DLL first and pass its path and --stdio as separate arguments.
Use Streamable HTTP for a server that is already listening. The sample targets http://127.0.0.1:5081/mcp to make both projects runnable on one machine. Point the gateway at the trusted server’s HTTPS MCP endpoint for a remote deployment and configure its authentication. The modern transport uses POST requests and can return JSON or stream responses with SSE. MCP routing metadata includes Mcp-Method and, for named operations where required, Mcp-Name. Let the SDK construct the protocol messages.
The older HTTP+SSE transport is deprecated and still available for compatibility in the SDK. This is separate from SSE response streaming within Streamable HTTP. The example explicitly uses HttpTransportMode.StreamableHttp to make endpoint mistakes visible. AutoDetect may try legacy SSE after an unsuccessful Streamable HTTP attempt. Transport fallback and protocol revision fallback are separate decisions. See transport bindings and SDK transport guidance.
Create the .NET 10 projects
Install a .NET 10 SDK, a C# editor and Postman or curl. The projects are siblings. Use the command sequence below from an empty working directory. The sample uses the debug output path created by dotnet build.
| Package | Role in this guide |
|---|---|
ModelContextProtocol.Core |
Client transport, client API and protocol models used by the gateway. |
ModelContextProtocol |
Hosting and registration extensions. It brings Core transitively. |
ModelContextProtocol.AspNetCore |
Server-side HTTP integration including MapMcp. It brings the other two packages transitively. |
The pinned versions are compatible with net10.0 and the two project files below are the ones used in the build. The gateway does not need the ASP.NET Core MCP server package to consume a remote MCP endpoint. ASP.NET Core hosting itself comes from the Web SDK. See the Core package, ASP.NET Core package and 2.3.1 release notes.
Implement a reproducible catalog MCP server
Replace Catalog.Server/Program.cs. The project starts an ASP.NET Core server when launched with the HTTP command shown later. When the gateway supplies --stdio, the same executable starts the stdio host instead. Both expose the same three capabilities.
UseStructuredContent supplies machine-readable output for the product record. A missing product is a normal catalog response with found: false. A tool execution error is a different condition. The sample defines a fixed resource URI so the gateway can safely expose it through a named route. The prompt returns a user-role message that the host can review.
The HTTP example is a loopback test fixture. Use authentication and authorization on an upstream server before exposing it remotely. If you’re extending the server side, start with the ASP.NET PB C# MCP server tutorial, the SDK resources and prompts guides, or the official reference servers.
Configure server aliases and implement the client
Set Catalog.Gateway/appsettings.json as shown. The route accepts only local or http. The caller cannot supply an executable, arguments, a URL, credentials or a resource URI. Keep the server DLL in a directory the application trusts. If you build Release or publish the server, update the configured DLL path.
Add CatalogConnections.cs. It uses dependency injection for configuration, host paths, logging and the named HTTP client factory. A fresh MCP client is created per gateway operation and disposed asynchronously. HTTP handlers can still be pooled by IHttpClientFactory. The HTTP wrapper remains alive until the MCP client is disposed.
The per-request lifetime is easy to reason about. Starting a process for each stdio call has a real startup cost. For high traffic, consider a supervised long-lived client per configured server and identity, or use Streamable HTTP. Use explicit ownership, bounded concurrency, cleanup on shutdown, and reconnect handling. Do not share an authenticated client between users with different authorization.
The sample links the HTTP request’s cancellation token to a 12-second operation budget. HTTP connection handling also has its own transport settings. Client disposal and child process shutdown can add time beyond the operation budget. Cancellation is cooperative. A timeout after sending a write does not tell you whether the server committed the action. Retry connection establishment or known safe reads with bounded backoff only when the operation semantics and failure allow it.
Discover tools, validate arguments and call the server
ListToolsAsync yields McpClientTool objects. Inspect Name, Description and JsonSchema before wiring an operation. The convenience list method can follow pagination. This small server has one tool. For large or untrusted catalogs, use the paged overload and enforce a maximum page count. Cache by endpoint and identity when appropriate and respect applicable cache metadata and invalidation. A tool may disappear between listing and execution.
A tool’s input schema describes expected JSON arguments. It cannot decide whether a caller has permission, whether a SKU exists, or whether invoking a tool is safe. The gateway permits one exact tool name and checks the catalog’s SKU format. The server still owns data authorization and business rules. For a larger allowlist, pin or review schema changes and validate against the expected schema using a suitable validator in addition to business rules. Treat upstream descriptions and annotations as untrusted data.
CallToolAsync returns a CallToolResult. The gateway checks IsError and projects StructuredContent and TextContentBlock entries into an ordinary JSON response. A generic client should preserve content types and handle images, embedded resources or resource links explicitly. Never fetch an unfamiliar resource link automatically. An MCP protocol error, a tool-level error and a normal business result such as found: false need separate handling. See the McpClient API reference and tools specification.
Expose the ASP.NET Core endpoints
Replace Catalog.Gateway/Program.cs. The gateway checks a local demo secret before any route runs. It limits request size and concurrent upstream work. It uses a fixed allowlist for the one supported tool, resource and prompt.
Gateway route under /api/mcp/{server} |
What it does |
|---|---|
GET /tools |
Discovers the permitted tool and projects its schema. |
POST /tools/catalog_lookup |
Validates the SKU, checks tool availability and calls it. |
GET /resources |
Reads the first page and exposes the known resource. |
GET /resources/sku-help |
Reads the fixed SKU help resource. |
GET /prompts |
Reads the first page and exposes the known prompt. |
GET /prompts/catalog-help |
Retrieves the fixed prompt. |
The first-page resource and prompt calls are deliberate for the one-item fixture. For arbitrary MCP servers, check advertised capabilities after discovery and implement pagination or return an explicit unsupported status. In this sample both servers are expected to support all three features, and a protocol failure is mapped to a gateway error.
The shared demo key is a local access gate. Keep it in User Secrets or a local environment variable, use loopback for the exercise, and replace the gate with authenticated users or service identities in production. Use the same authenticated principal and scopes when deciding which server, tool and arguments are permitted. See the ASP.NET PB JWT guide and ASP.NET Core development secrets guidance.
Test both transports with Postman
From the parent directory, build both projects. In terminal one, start the HTTP MCP server. The local alias launches its own child process, so the HTTP server is only needed for the HTTP alias.
In terminal two, initialize User Secrets for the gateway and set a randomly generated 32–128 character value. Replace the placeholder with your own value. Launch in the Development environment so the gateway loads User Secrets.
Set X-Demo-Key in Postman. First send GET http://127.0.0.1:5080/api/mcp/local/tools. The JSON array should include catalog_lookup and an input schema with a string sku. Next send this POST request. Select raw JSON and use the same secret header.
The response below was captured from the running demo and formatted for readability. Both aliases returned the same data.
Switch local to http in the gateway route and repeat. Keep using port 5080 in Postman. Port 5081 is the MCP endpoint, which expects protocol requests rather than the gateway’s REST payload. Then test GET requests for the resource and prompt routes on each alias. A successful resource read includes text describing the SKU format. A successful prompt read returns the catalog help message.
| Check | Expected result |
|---|---|
Valid but absent SKU such as XYZ-999 |
200 with found: false. |
| Missing or incorrect gateway key | 401. |
Invalid SKU such as bad |
400 before an upstream call. |
| A different tool name | 403 before an upstream call. |
| Unknown alias | 404 for an otherwise valid operation. |
| HTTP server stopped | 502 on the HTTP alias. |
| More than four concurrent admitted operations | Excess work is rejected with 429. |
Tool result with IsError=true |
422 for the demo tool route. |
| Operation cancellation from the linked deadline | 504 when the deadline surfaces as cancellation. |
Execution record. Both projects built with .NET SDK 10.0.100 and MCP SDK 2.3.1. I ran seven HTTP checks per alias for tool listing, a product match, a product miss, resource list and read, and prompt list and get. Five additional checks verified a missing key, invalid SKU, disallowed tool, unknown alias, and connection failure after stopping the HTTP fixture. The timeout, overload, and tool-error rows describe the implemented behavior and were not part of that run. The demo used a loopback HTTP server. Remote HTTPS and OAuth require separate environment-specific testing.
Integrate an MCP tool with Microsoft.Extensions.AI
A chat model is optional. The simplest controlled integration takes a validated SKU from your application, invokes the approved catalog tool, and asks an IChatClient to explain the returned evidence. Add this helper to the gateway if you already have an authenticated chat service. Pass your configured model adapter, an authorized live MCP client and a cancellation token. Keep the MCP client alive until the helper completes. This example does not add a public chat route or require a model key for Postman.
The C# SDK also exposes discovered McpClientTool instances as AIFunction objects for hosts that want model-selected tools. A tool-capable IChatClient can receive declarations in ChatOptions.Tools, and Microsoft’s function-invoking middleware can execute functions. If you enable automatic invocation, expose only scoped, approved functions. A policy wrapper should check the caller, server, function name, arguments and approval state on every actual invocation. Cap the number of model/tool rounds and require confirmation for sensitive operations. Approval should bind the actor and exact action, with expiry and replay prevention.
The helper was compiled. It was not run against a live chat provider. See IChatClient, Microsoft’s MCP client quickstart and our ASP.NET Core OpenAI integration guide.
Production security, diagnostics and retries
Separate ingress identity from upstream identity. The gateway’s HTTP credential and an MCP server’s OAuth credential serve different audiences. For protected HTTP servers, follow the MCP authorization specification and the provider’s supported flow, validate issuer and audience, and request least-privilege scopes. Keep tokens on the server side and avoid forwarding arbitrary caller tokens. Local processes should run under a constrained account and receive only the environment and filesystem access needed for their job. Review what child processes inherit. See MCP authorization.
Treat server selection as an outbound security boundary. Use an operator-managed catalog and explicit network egress controls. The sample accepts only configured addresses, rejects URL user information and disables HTTP redirects and cookies. Production DNS and proxy policy still matter, even for an operator-configured hostname. Keep separate credentials and permission policies per server. For an HTTP server bound locally, follow MCP host and Origin validation guidance and keep the bind address narrow.
Keep useful logs without keeping secrets. Record server alias, operation name, outcome, latency, negotiated revision where available and a request correlation ID. Redact tokens, sensitive arguments, prompts and results. Stdio errors belong on stderr. When debugging an HTTP failure, start with upstream status and the response content type. A login page or HTML proxy error commonly points to the wrong endpoint or authentication issue.
Plan for cancellation and ambiguous outcomes. A network timeout after an upstream action is sent can leave the result unknown. For an idempotent read, consider a small retry budget with backoff and jitter. For a write, use an upstream idempotency mechanism and reconciliation before repeating it. Reconnecting a client and replaying a tool action are separate decisions. Use the current specification and the SDK’s stateless and stateful mode guide when debugging a proxy or a legacy session.
Troubleshooting common MCP client errors
| Symptom | What to inspect |
|---|---|
| Local client exits during connect | Verify dotnet on PATH, absolute DLL path and --stdio. Read stderr. |
| Unexpected JSON parse failure on stdio | Look for logging or startup text written to stdout. |
| HTTP 404 or 405 | Check the exact /mcp route, method, reverse proxy path and transport selection. Modern servers can reject legacy GET or DELETE. |
| Protocol mismatch | Check SDK version, server revision and any explicit version pin. Inspect discovery versus legacy initialization. |
| Missing tool | Check allowlist, server permissions and returned tool catalog. Names are case-sensitive in this gateway. |
| Invalid tool arguments | Compare the JSON object against the tool input schema and application validation. |
| HTTP 401/403 from upstream | Check token audience, issuer, scopes and expiry. The demo gateway key does not authenticate to the MCP server. |
| Stream stalls behind a proxy | Check buffering and connection timeouts when the server streams responses. |
| Request times out during discovery | Inspect server startup and the SDK probe budget before raising deadlines. A slow or incompatible peer can trigger legacy fallback. |
Frequently asked questions
Can an MCP client work without an LLM?
Yes. A C# service can list tools and call them directly. The demo uses no model for its tool, resource or prompt routes.
Is SSE removed from MCP?
Legacy HTTP+SSE is deprecated and remains a compatibility option in the SDK. Streamable HTTP can still use SSE for streamed responses. Choose the transport based on what the server implements.
Does every MCP client send initialize first?
Only the older handshake-based revisions use the initialize exchange. With the July 2026 revision, requests carry version and client information. The SDK may first call server/discover and fall back if compatibility requires it.
Is a tool’s JSON Schema enough to permit execution?
No. It describes argument structure. The gateway and MCP server still need authorization, business validation, and approval controls for sensitive operations.
Can one ASP.NET Core application connect to multiple MCP servers?
Yes. Give each server a stable alias and maintain separate transport settings, credentials and allowed capabilities. Scope caches and reusable clients to the relevant identity. If two servers expose the same tool name, the pair of server alias and tool name identifies the target.
Should I publish the demo gateway as-is?
Keep the exercise on loopback. For production, replace the shared demo key with your identity system, add policy checks to the upstream server, and supervise processes or use a managed HTTPS endpoint.
Conclusion and further reading
Start by calling one read-only tool over both transports. Compare the tool list and structured result, then verify rejection of invalid input before extending the gateway. When you introduce a chat model, keep the same server and tool permissions in the actual invocation path.
Future topics for this series include MCP OAuth discovery and token audience validation, a bounded tool-catalog cache that respects server hints, and human approval for multi-round tool requests.
- MCP 2026-07-28 specification
- Versioning and compatibility
- 2025-11-25 lifecycle
- Transport bindings
- MCP authorization
- MCP tools
- C# SDK 2.3.1 release
- McpClient API and client options
- SDK transport guidance and HTTP session modes
- NuGet Core and NuGet ASP.NET Core
- SDK resources and SDK prompts
- Official reference servers
- Microsoft.Extensions.AI source and IChatClient
- Microsoft MCP client quickstart
- ASP.NET Core User Secrets
Comments
Post a Comment