Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/modelcontextprotocol/csharp-sdk/llms.txt

Use this file to discover all available pages before exploring further.

Overview

The IMcpServerBuilder interface provides a fluent API for configuring Model Context Protocol (MCP) servers when using dependency injection. It exposes methods for registering tools, prompts, resources, custom request handlers, and server transports through a chain of method calls.

Interface Definition

public interface IMcpServerBuilder
{
    IServiceCollection Services { get; }
}
Services
IServiceCollection
Gets the associated service collection for registering additional services and dependencies.

Obtaining the Builder

The builder is obtained from the AddMcpServer extension method:
var builder = services.AddMcpServer(options =>
{
    options.ServerInfo = new Implementation
    {
        Name = "My MCP Server",
        Version = "1.0.0"
    };
});

Builder Extension Methods

Tool Registration

WithTools<TToolType>
IMcpServerBuilder
Discovers and registers all methods on TToolType marked with [McpServerTool] attribute.Parameters:
  • serializerOptions (optional): JSON serializer options for parameter marshalling
Behavior:
  • For instance methods, a new instance is created for each tool invocation
  • For static methods, no instance is created
  • Supports both public and non-public methods
builder.WithTools<WeatherTools>();
WithTools<TToolType>(TToolType target)
IMcpServerBuilder
Registers tools from a specific instance. Methods are invoked on the provided target.Special Case: If TToolType is IEnumerable<McpServerTool>, tools are registered directly without method scanning.
var toolInstance = new WeatherTools(apiKey);
builder.WithTools(toolInstance);
WithTools(IEnumerable<McpServerTool> tools)
IMcpServerBuilder
Registers pre-created McpServerTool instances directly.
builder.WithTools([
    McpServerTool.Create(
        typeof(EchoTool).GetMethod(nameof(EchoTool.Echo))!,
        options: new McpServerToolCreateOptions
        {
            Icons = [
                new Icon
                {
                    Source = "https://example.com/icon.svg",
                    MimeType = "image/svg+xml"
                }
            ]
        })
]);
WithTools(IEnumerable<Type> toolTypes)
IMcpServerBuilder
Registers tools from multiple types. Each type’s [McpServerTool] attributed methods are discovered.
Requires unreferenced code. Not compatible with Native AOT. Use generic WithTools<T> instead for AOT scenarios.
WithToolsFromAssembly(Assembly? toolAssembly = null)
IMcpServerBuilder
Scans an assembly for types marked with [McpServerToolType] and registers all their [McpServerTool] methods.Parameters:
  • toolAssembly: Assembly to scan. If null, uses calling assembly.
  • serializerOptions (optional): JSON serializer options
Requires unreferenced code. Not compatible with Native AOT.

Prompt Registration

WithPrompts<TPromptType>
IMcpServerBuilder
Discovers and registers all methods on TPromptType marked with [McpServerPrompt] attribute.
builder.WithPrompts<SimplePromptType>();
WithPrompts<TPromptType>(TPromptType target)
IMcpServerBuilder
Registers prompts from a specific instance.Special Case: If TPromptType is IEnumerable<McpServerPrompt>, prompts are registered directly.
WithPrompts(IEnumerable<McpServerPrompt> prompts)
IMcpServerBuilder
Registers pre-created McpServerPrompt instances.
WithPrompts(IEnumerable<Type> promptTypes)
IMcpServerBuilder
Registers prompts from multiple types.
Requires unreferenced code. Not compatible with Native AOT.
WithPromptsFromAssembly(Assembly? promptAssembly = null)
IMcpServerBuilder
Scans assembly for [McpServerPromptType] classes and registers their [McpServerPrompt] methods.
Requires unreferenced code. Not compatible with Native AOT.

Resource Registration

WithResources<TResourceType>
IMcpServerBuilder
Discovers and registers all methods on TResourceType marked with [McpServerResource] attribute.
builder.WithResources<SimpleResourceType>();
WithResources<TResourceType>(TResourceType target)
IMcpServerBuilder
Registers resources from a specific instance.Special Case: If TResourceType is IEnumerable<McpServerResource>, resources are registered directly.
WithResources(IEnumerable<McpServerResource> resourceTemplates)
IMcpServerBuilder
Registers pre-created McpServerResource instances.
WithResources(IEnumerable<Type> resourceTemplateTypes)
IMcpServerBuilder
Registers resources from multiple types.
Requires unreferenced code. Not compatible with Native AOT.
WithResourcesFromAssembly(Assembly? resourceAssembly = null)
IMcpServerBuilder
Scans assembly for [McpServerResourceType] classes and registers their [McpServerResource] methods.
Requires unreferenced code. Not compatible with Native AOT.

Request Handlers

WithListToolsHandler
IMcpServerBuilder
Configures a handler for listing available tools.
builder.WithListToolsHandler(async (ctx, ct) =>
{
    return new ListToolsResult
    {
        Tools = dynamicTools
    };
});
Typically paired with WithCallToolHandler for complete tool implementation.
WithCallToolHandler
IMcpServerBuilder
Configures a handler for executing tool calls.
WithListPromptsHandler
IMcpServerBuilder
Configures a handler for listing available prompts.
Typically paired with WithGetPromptHandler.
WithGetPromptHandler
IMcpServerBuilder
Configures a handler for retrieving prompt content.
WithListResourcesHandler
IMcpServerBuilder
Configures a handler for listing available resources.
Typically paired with WithReadResourceHandler.
WithReadResourceHandler
IMcpServerBuilder
Configures a handler for reading resource content.
WithListResourceTemplatesHandler
IMcpServerBuilder
Configures a handler for listing resource templates (URI patterns).
WithCompleteHandler
IMcpServerBuilder
Configures a handler for auto-completion suggestions for prompt arguments or resource references.
builder.WithCompleteHandler(async (ctx, ct) =>
{
    var values = suggestionList.Where(v => v.StartsWith(ctx.Params.Argument.Value));
    return new CompleteResult
    {
        Completion = new Completion { Values = [..values] }
    };
});
WithSubscribeToResourcesHandler
IMcpServerBuilder
Configures a handler for resource subscription requests.
Typically paired with WithUnsubscribeFromResourcesHandler.
WithUnsubscribeFromResourcesHandler
IMcpServerBuilder
Configures a handler for resource unsubscription requests.
WithSetLoggingLevelHandler
IMcpServerBuilder
Configures a handler for logging level change requests from clients.

Filters

WithMessageFilters
IMcpServerBuilder
Configures message-level filters for the MCP server.
builder.WithMessageFilters(filters =>
{
    filters.AddFilter(async (context, next) =>
    {
        // Pre-processing
        var result = await next(context);
        // Post-processing
        return result;
    });
});
WithRequestFilters
IMcpServerBuilder
Configures request-specific filters for the MCP server.
builder.WithRequestFilters(filters =>
{
    filters.AddFilter(async (context, next) =>
    {
        // Request filtering logic
        return await next(context);
    });
});

Transport Configuration

WithStdioServerTransport
IMcpServerBuilder
Adds a server transport using standard input/output streams.
builder.WithStdioServerTransport();
Use Cases:
  • Local server launched by a client process
  • Command-line MCP servers
  • Server exits when stdin is closed
WithStreamServerTransport
IMcpServerBuilder
Adds a server transport using custom input/output streams.
builder.WithStreamServerTransport(inputStream, outputStream);
Parameters:
  • inputStream: Stream to use as standard input
  • outputStream: Stream to use as standard output

Complete Example

using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol.Server;

var services = new ServiceCollection();

services.AddMcpServer(options =>
{
    options.ServerInfo = new Implementation
    {
        Name = "Everything Server",
        Version = "1.0.0"
    };
})
.WithTools<AddTool>()
.WithTools<WeatherTools>()
.WithPrompts<SimplePromptType>()
.WithResources<SimpleResourceType>()
.WithStdioServerTransport();

var serviceProvider = services.BuildServiceProvider();
var server = serviceProvider.GetRequiredService<McpServer>();
await server.RunAsync();

See Also

Build docs developers (and LLMs) love