MCP C# SDK

repository·main·Indexed 26 days ago

https://github.com/modelcontextprotocol/csharp-sdk

The official .NET implementation of the Model Context Protocol (MCP), enabling developers to build MCP clients and servers for integration between LLMs and data sources. The SDK provides multiple packages including ModelContextProtocol.Core for low-level APIs, ModelContextProtocol for standard hosting and DI, ModelContextProtocol.AspNetCore for HTTP-based servers, and extensions for interactive UI apps (Apps) and asynchronous long-running tool invocations (Tasks). It supports Identity Assertion Authorization Grant and OAuth 2.0 flows for secure cross-application access.

Tokens
56.6K
Snippets
115
Records
198
Agent score
88%

What's inside MCP C# SDK

  1. Overview of the Model Context Protocol (MCP)

    main

    The Model Context Protocol (MCP) is an open protocol designed to standardize how applications provide context to Large Language Models (LLMs). It facilitates secure integration between LLMs and various data sources and tools.

    Developers can use the C# SDK to build implementations that adhere to this protocol, allowing for interoperability between different MCP-compliant clients and servers.

  2. Understand Multi Round-Trip Requests (MRTR)

    main
    Multi Round-Trip Requests (MRTR) allow a server tool to request client input (such as elicitation, sampling, or roots) as part of a single tool call. Instead of returning a final result, the server returns an incomplete result containing input requests. The client fulfills these requests and retries the original tools/call with the responses attached. This is ideal for stateless servers that need to orchestrate multi-step flows without maintaining in-memory handler state between rounds.
  3. Extend MCP with Apps, Tasks, and Identity

    main

    The SDK provides extension points for advanced functionality:

    • MCP Apps: Deliver interactive UIs directly from MCP servers.
    • Tasks: Use task-based execution for long-running operations that support status polling and result retrieval.
    • Identity and Roles: Access caller identity and roles within tool, prompt, and resource handlers.
  4. Implement MCP Server features

    main

    Servers can expose various capabilities to clients:

    • Tools: Implement tools that return text, images, audio, and embedded resources.
    • Resources: Expose data via resources, including templates and subscriptions.
    • Prompts: Implement reusable prompt templates with rich content types.
    • Completions: Provide argument auto-completion for prompts and resource templates.
    • Logging: Implement server-side logging that clients can consume.
    • Pagination: Use cursor-based pagination when listing tools, prompts, and resources.
    • HTTP Context: Access the underlying HttpContext for specific requests.
    • MCP Server Handler Filters: Add filters to the handler pipeline to wrap original handlers with custom functionality.
  5. Understand MCP Base Protocol concepts

    main

    The Model Context Protocol SDK implements several core protocol mechanisms:

    • Capabilities: Negotiation of client and server capabilities and protocol versions during initialization.
    • Transports: Configuration of communication channels including stdio, Streamable HTTP, and SSE.
    • Stateless vs Stateful: Configuration of HTTP server modes and session management.
    • Ping: Connection health verification.
    • Progress tracking: Monitoring long-running operations via notification messages.
    • Cancellation: Using cancellation tokens and notifications to abort in-flight requests.
    • Multi Round-Trip Requests (MRTR): Allowing servers to request client input during tool execution via input-required results and retries.
  6. Understand Streamable HTTP message delivery

    main

    Streamable HTTP uses two distinct channels for message flow between client and server:

    1. POST response streams (Solicited messages): Every JSON-RPC request from the client arrives via an HTTP POST. The server holds the response body open as an SSE stream. This stream carries the JSON-RPC response and any messages produced during the execution of that specific handler (e.g., progress notifications, logs, or server-to-client requests like sampling or elicitation).

    2. The GET stream (Unsolicited messages): An optional long-lived HTTP GET request used for messages initiated by the server outside of an active request handler (e.g., background resource changes or asynchronous logs).

    Warning: If a client does not open a GET stream, the server will silently drop all unsolicited messages.

  7. Understand Request Backpressure in MCP Session Modes

    main

    The MCP C# SDK provides different levels of protection against request flooding depending on the session mode and enabled features.

    Default Behavior (Stateless and Stateful)

    In both Stateless and Default Stateful modes, the server provides HTTP-level backpressure. The POST response is held open while the handler runs. This means concurrency is naturally limited by the HTTP/2 MaxStreamsPerConnection setting (which defaults to 100 in Kestrel). Each in-flight handler occupies one HTTP/2 stream.

    Unbounded Modes (No Built-in Backpressure)

    The following configurations do not provide built-in HTTP-level backpressure and can lead to unbounded handler concurrency. If using these in production, you must apply HTTP rate-limiting middleware or reverse proxy limits:

    1. Legacy SSE (Opt-in): The POST endpoint returns 202 Accepted immediately after queuing the message. The request/response channels are separated via a GET stream.
    2. Stateful + EventStreamStore: If a handler calls EnablePollingAsync(), the POST response completes before the handler finishes, freeing the HTTP/2 stream slot.
    3. Stateful + Tasks: For long-running tool calls, the server returns a task ID immediately. The POST response completes before the actual work begins, meaning there is no built-in limit on how many background handlers can be spawned.
  8. Request LLM completions from a client using Sampling

    main

    Deprecation Warning

    Sampling is deprecated as of MCP specification revision 2026-07-28 and may be removed in a future version. For stateless-compatible alternatives, use Multi round-trip requests (MRTR) by throwing InputRequiredException.

    Overview

    Sampling allows an MCP server to request LLM completions from the connected client. This enables agentic behaviors where a tool delegates reasoning (like summarization or decision-making) back to the client's model.

    Requirements

    • Sampling is a server-to-client request.
    • It requires stateful mode or stdio. It is not available in stateless mode.
    • The client must advertise the sampling capability (this happens automatically when a SamplingHandler is configured).
  9. Subscribe to resource updates on the client

    main

    Clients can subscribe to resource updates to be notified when content changes. The server must support subscriptions.

    You can subscribe with an inline handler that is called when a notification is received, or subscribe without a handler and use a global notification handler.

    // Subscribe with an inline handler
    IAsyncDisposable subscription = await client.SubscribeToResourceAsync(
        "config://app/settings",
        async (notification, cancellationToken) =>
        {
            Console.WriteLine($"Resource updated: {notification.Uri}");
            var updated = await client.ReadResourceAsync(notification.Uri, cancellationToken: cancellationToken);
        });
    
    // Unsubscribe
    await subscription.DisposeAsync();
    
    // Alternative: Subscribe without a handler
    await client.SubscribeToResourceAsync("config://app/settings");
    await client.UnsubscribeFromResourceAsync("config://app/settings");