Skip to content
Open
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
61 changes: 51 additions & 10 deletions src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

namespace ModelContextProtocol.AspNetCore;

internal sealed class StreamableHttpHandler(
internal sealed partial class StreamableHttpHandler(
IOptions<McpServerOptions> mcpServerOptionsSnapshot,
IOptionsFactory<McpServerOptions> mcpServerOptionsFactory,
IOptions<HttpServerTransportOptions> httpServerTransportOptions,
Expand All @@ -27,6 +27,8 @@ internal sealed class StreamableHttpHandler(
IServiceProvider applicationServices,
ILoggerFactory loggerFactory)
{
private readonly ILogger _logger = loggerFactory.CreateLogger<StreamableHttpHandler>();

private const string McpSessionIdHeaderName = McpHttpHeaders.SessionId;
private const string McpProtocolVersionHeaderName = McpHttpHeaders.ProtocolVersion;
private const string LastEventIdHeaderName = McpHttpHeaders.LastEventId;
Expand Down Expand Up @@ -118,21 +120,32 @@ await WriteJsonRpcErrorAsync(context,
return;
}

if (!ValidateProtocolVersionEnvelope(context, message, out var protocolVersionEnvelopeError))
// The body parsed successfully, but reading its values can still throw InvalidOperationException:
// System.Text.Json checks the UTF-8 in a string only when it converts the string to a .NET string,
// the first lookup in a JsonObject converts all of that object's property names, and reading a
// non-string value as a string throws too. These are malformed requests, not server errors, so
// they get a 400 that echoes the request id instead of an HTTP 500. The error is written after
// the try block, so an exception from writing the response is never caught here.
JsonRpcErrorDetail? requestValidationError;
try
{
await WriteJsonRpcErrorDetailAsync(context, protocolVersionEnvelopeError, StatusCodes.Status400BadRequest, requestId);
return;
requestValidationError = ValidateRequestEnvelopeAndHeaders(context, message, mcpServerOptionsSnapshot.Value);
}

if (!ValidateMcpHeaders(context, message, mcpServerOptionsSnapshot.Value, out var errorMessage))
catch (InvalidOperationException ex)
{
await WriteJsonRpcErrorAsync(context, errorMessage, StatusCodes.Status400BadRequest, (int)McpErrorCode.HeaderMismatch, requestId);
return;
// Server-side code that runs during validation can throw this exception type too, so the cause
// is logged and the client gets a fixed message that reveals nothing about the server.
LogRequestValueCouldNotBeRead(ex);
requestValidationError = new()
{
Code = (int)McpErrorCode.InvalidRequest,
Message = "Bad Request: The request contains a value that could not be read.",
};
}

if (!ValidateRequiredPerRequestMeta(context, message, out var requiredMetaError))
if (requestValidationError is not null)
{
await WriteJsonRpcErrorDetailAsync(context, requiredMetaError, StatusCodes.Status400BadRequest, requestId);
await WriteJsonRpcErrorDetailAsync(context, requestValidationError, StatusCodes.Status400BadRequest, requestId);
return;
}

Expand Down Expand Up @@ -1473,6 +1486,31 @@ private static SafeIntegerParse ParseSafeInteger(string text, out long value)
return SafeIntegerParse.NotNumeric;
}

/// <summary>
/// Runs the body checks that compare the JSON-RPC message with the request headers. Returns the first error,
/// or <see langword="null"/> when the request passes. Can throw <see cref="InvalidOperationException"/> when
/// the body contains a value or property name that cannot be read; the caller maps that to a 400.
/// </summary>
private static JsonRpcErrorDetail? ValidateRequestEnvelopeAndHeaders(HttpContext context, JsonRpcMessage message, McpServerOptions serverOptions)
{
if (!ValidateProtocolVersionEnvelope(context, message, out var protocolVersionEnvelopeError))
{
return protocolVersionEnvelopeError;
}

if (!ValidateMcpHeaders(context, message, serverOptions, out var errorMessage))
{
return new() { Code = (int)McpErrorCode.HeaderMismatch, Message = errorMessage };
}

if (!ValidateRequiredPerRequestMeta(context, message, out var requiredMetaError))
{
return requiredMetaError;
}

return null;
}

private static Task WriteJsonRpcErrorDetailAsync(HttpContext context, JsonRpcErrorDetail detail, int statusCode, RequestId requestId = default)
{
var jsonRpcError = new JsonRpcError { Id = requestId, Error = detail };
Expand All @@ -1484,4 +1522,7 @@ private static bool MatchesApplicationJsonMediaType(MediaTypeHeaderValue acceptH

private static bool MatchesTextEventStreamMediaType(MediaTypeHeaderValue acceptHeaderValue)
=> acceptHeaderValue.MatchesMediaType("text/event-stream");

[LoggerMessage(Level = LogLevel.Debug, Message = "Rejected a POST request with 400 Bad Request because a value in the request could not be read.")]
private partial void LogRequestValueCouldNotBeRead(Exception exception);
}
46 changes: 42 additions & 4 deletions src/ModelContextProtocol.Core/Server/McpServerImpl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -230,10 +230,9 @@ private void ReadRequestMetadata(JsonRpcRequest request)
return;
}

JsonObject? meta = request.Params is JsonObject paramsObj ? paramsObj["_meta"] as JsonObject : null;
// An unreadable value cannot select a protocol; only the modern path requires a usable version.
string? metadataProtocolVersion =
meta?[MetaKeys.ProtocolVersion] is JsonValue value && value.TryGetValue(out string? version) ? version : null;
string? metadataProtocolVersion = ReadMetadataProtocolVersion(
request, out JsonObject? meta, out bool metadataProtocolVersionUnreadable);

if (transportProtocolVersion is not null &&
metadataProtocolVersion is not null &&
Expand Down Expand Up @@ -301,12 +300,51 @@ transportProtocolVersion is not null ||
}

// With no established era, warn in case a modern peer accidentally fell back to legacy handling.
if (metadataProtocolVersion is null && meta?.ContainsKey(MetaKeys.ProtocolVersion) is true)
if (metadataProtocolVersionUnreadable)
{
LogIgnoredUnreadableProtocolVersionMetadata(_endpointName, request.Method);
}
}

/// <summary>
/// Reads the request's <c>_meta</c> object and its protocol version without throwing. Returns
/// <see langword="null"/> when the version is absent or cannot be read, and sets <paramref name="unreadable"/>
/// when it cannot be read: the value is not a readable string, or <c>params</c> or <c>_meta</c> has a property
/// name that is not valid UTF-8. System.Text.Json throws <see cref="InvalidOperationException"/> when it
/// converts a string that is not valid UTF-8, and the first lookup in an object converts all of that object's
/// property names, so the <c>_meta</c> lookup in <c>params</c> must be inside the same try block.
/// </summary>
private static string? ReadMetadataProtocolVersion(JsonRpcRequest request, out JsonObject? meta, out bool unreadable)
{
meta = null;
unreadable = false;
if (request.Params is not JsonObject paramsObj)
{
return null;
}

try
{
meta = paramsObj["_meta"] as JsonObject;
if (meta is null || !meta.TryGetPropertyValue(MetaKeys.ProtocolVersion, out JsonNode? node))
{
return null;
}

if (node is JsonValue value && value.TryGetValue(out string? version))
{
return version;
}
}
catch (InvalidOperationException)
{
// Not valid UTF-8 in the value, or in a property name of params or _meta: handled below as unreadable.
}

unreadable = true;
return null;
}

private static void ProjectModernMetadata(JsonRpcRequest request, JsonObject meta, string protocolVersion)
{
if (!meta.ContainsKey(MetaKeys.ClientCapabilities))
Expand Down
Loading