Skip to content

Implement DefaultMcpEndpointRouteBuilderConfigurator for MCP endpoint configuration #691

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Metadata;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol.Protocol;

namespace ModelContextProtocol.AspNetCore;

/// <summary>
/// Default implementation that wires up the MCP Streamable HTTP transport endpoints
/// (and legacy SSE endpoints when applicable).
/// </summary>
internal sealed class DefaultMcpEndpointRouteBuilderConfigurator(
StreamableHttpHandler streamableHttpHandler
) : IMcpEndpointRouteBuilderConfigurator
{
public IEndpointConventionBuilder Configure(IEndpointRouteBuilder endpoints, string pattern)
{
var mcpGroup = endpoints.MapGroup(pattern);
var streamableHttpGroup = mcpGroup
.MapGroup("")
.WithDisplayName(b => $"MCP Streamable HTTP | {b.DisplayName}")
.WithMetadata(
new ProducesResponseTypeMetadata(
StatusCodes.Status404NotFound,
typeof(JsonRpcError),
contentTypes: ["application/json"]
)
);

streamableHttpGroup
.MapPost("", streamableHttpHandler.HandlePostRequestAsync)
.WithMetadata(new AcceptsMetadata(["application/json"]))
.WithMetadata(
new ProducesResponseTypeMetadata(
StatusCodes.Status200OK,
contentTypes: ["text/event-stream"]
)
)
.WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status202Accepted));

if (!streamableHttpHandler.HttpServerTransportOptions.Stateless)
{
// The GET and DELETE endpoints are not mapped in Stateless mode since there's no way to send unsolicited messages
// for the GET to handle, and there is no server-side state for the DELETE to clean up.
streamableHttpGroup
.MapGet("", streamableHttpHandler.HandleGetRequestAsync)
.WithMetadata(
new ProducesResponseTypeMetadata(
StatusCodes.Status200OK,
contentTypes: ["text/event-stream"]
)
);
streamableHttpGroup.MapDelete("", streamableHttpHandler.HandleDeleteRequestAsync);

// Map legacy HTTP with SSE endpoints only if not in Stateless mode, because we cannot guarantee the /message requests
// will be handled by the same process as the /sse request.
var sseHandler = endpoints.ServiceProvider.GetRequiredService<SseHandler>();
var sseGroup = mcpGroup
.MapGroup("")
.WithDisplayName(b => $"MCP HTTP with SSE | {b.DisplayName}");

sseGroup
.MapGet("/sse", sseHandler.HandleSseRequestAsync)
.WithMetadata(
new ProducesResponseTypeMetadata(
StatusCodes.Status200OK,
contentTypes: ["text/event-stream"]
)
);
sseGroup
.MapPost("/message", sseHandler.HandleMessageRequestAsync)
.WithMetadata(new AcceptsMetadata(["application/json"]))
.WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status202Accepted));
}

return mcpGroup;
}

IEndpointConventionBuilder IMcpEndpointRouteBuilderConfigurator.Configure(IEndpointRouteBuilder endpoints, string pattern)
{
throw new NotImplementedException();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ public static IMcpServerBuilder WithHttpTransport(this IMcpServerBuilder builder
builder.Services.AddHostedService<IdleTrackingBackgroundService>();
builder.Services.AddDataProtection();

builder.Services.TryAddSingleton<
IMcpEndpointRouteBuilderConfigurator,
DefaultMcpEndpointRouteBuilderConfigurator
>();

if (configureOptions is not null)
{
builder.Services.Configure(configureOptions);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Routing;

namespace ModelContextProtocol.AspNetCore;

/// <summary>
/// Abstraction for configuring MCP endpoints on an <see cref="IEndpointRouteBuilder"/>.
/// Register an implementation in DI to override the default MapMcp behavior and enable hot swapping
/// of the transport/endpoints wiring without changing application code.
/// </summary>
public interface IMcpEndpointRouteBuilderConfigurator
{
/// <summary>
/// Configures the MCP endpoints on the provided <paramref name="endpoints"/> using the given <paramref name="pattern"/>.
/// Implementations should return the <see cref="IEndpointConventionBuilder"/> representing the mapped group
/// to allow callers to apply additional endpoint conventions (e.g., authorization).
/// </summary>
/// <param name="endpoints">The endpoint route builder to attach MCP endpoints to.</param>
/// <param name="pattern">The route pattern prefix to map to.</param>
/// <returns>An <see cref="IEndpointConventionBuilder"/> that can be used to configure conventions.</returns>
IEndpointConventionBuilder Configure(IEndpointRouteBuilder endpoints, string pattern);
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Metadata;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol.AspNetCore;
using ModelContextProtocol.Protocol;
using System.Diagnostics.CodeAnalysis;

namespace Microsoft.AspNetCore.Builder;
Expand All @@ -16,47 +13,20 @@ public static class McpEndpointRouteBuilderExtensions
/// <summary>
/// Sets up endpoints for handling MCP Streamable HTTP transport.
/// See <see href="https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#streamable-http">the 2025-06-18 protocol specification</see> for details about the Streamable HTTP transport.
/// Also maps legacy SSE endpoints for backward compatibility at the path "/sse" and "/message". <see href="https://modelcontextprotocol.io/specification/2024-11-05/basic/transports#http-with-sse">the 2024-11-05 protocol specification</see> for details about the HTTP with SSE transport.
/// </summary>
/// <param name="endpoints">The web application to attach MCP HTTP endpoints.</param>
/// <param name="pattern">The route pattern prefix to map to.</param>
/// <returns>Returns a builder for configuring additional endpoint conventions like authorization policies.</returns>
public static IEndpointConventionBuilder MapMcp(this IEndpointRouteBuilder endpoints, [StringSyntax("Route")] string pattern = "")
public static IEndpointConventionBuilder MapMcp(
this IEndpointRouteBuilder endpoints,
[StringSyntax("Route")] string pattern = ""
)
{
var streamableHttpHandler = endpoints.ServiceProvider.GetService<StreamableHttpHandler>() ??
throw new InvalidOperationException("You must call WithHttpTransport(). Unable to find required services. Call builder.Services.AddMcpServer().WithHttpTransport() in application startup code.");

var mcpGroup = endpoints.MapGroup(pattern);
var streamableHttpGroup = mcpGroup.MapGroup("")
.WithDisplayName(b => $"MCP Streamable HTTP | {b.DisplayName}")
.WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status404NotFound, typeof(JsonRpcError), contentTypes: ["application/json"]));

streamableHttpGroup.MapPost("", streamableHttpHandler.HandlePostRequestAsync)
.WithMetadata(new AcceptsMetadata(["application/json"]))
.WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, contentTypes: ["text/event-stream"]))
.WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status202Accepted));

if (!streamableHttpHandler.HttpServerTransportOptions.Stateless)
{
// The GET and DELETE endpoints are not mapped in Stateless mode since there's no way to send unsolicited messages
// for the GET to handle, and there is no server-side state for the DELETE to clean up.
streamableHttpGroup.MapGet("", streamableHttpHandler.HandleGetRequestAsync)
.WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, contentTypes: ["text/event-stream"]));
streamableHttpGroup.MapDelete("", streamableHttpHandler.HandleDeleteRequestAsync);

// Map legacy HTTP with SSE endpoints only if not in Stateless mode, because we cannot guarantee the /message requests
// will be handled by the same process as the /sse request.
var sseHandler = endpoints.ServiceProvider.GetRequiredService<SseHandler>();
var sseGroup = mcpGroup.MapGroup("")
.WithDisplayName(b => $"MCP HTTP with SSE | {b.DisplayName}");

sseGroup.MapGet("/sse", sseHandler.HandleSseRequestAsync)
.WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, contentTypes: ["text/event-stream"]));
sseGroup.MapPost("/message", sseHandler.HandleMessageRequestAsync)
.WithMetadata(new AcceptsMetadata(["application/json"]))
.WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status202Accepted));
}

return mcpGroup;
var configurator =
endpoints.ServiceProvider.GetService<IMcpEndpointRouteBuilderConfigurator>()
?? throw new InvalidOperationException(
"You must call WithHttpTransport(). Unable to find required services. Call builder.Services.AddMcpServer().WithHttpTransport() in application startup code."
);
return configurator.Configure(endpoints, pattern);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we should add a hook for a service to replace the implementation of MapMcp() entirely. If you want something that behaves radically differently, you can create your own MapWhateverMcp() method.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It isn't radically different though, It is nearly exactly the same, minus the stateless behavior. Do we really want to force people to have to learn about MapWhateverMcp calls? I can guarantee you that some people will forget to change to the other MapWhatever call and will file an issue about "MapMcp" isn't working

}
Loading