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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,11 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha

### Fixes

- HTTP server transports now return header validation errors before malformed-body errors.
On unsupported methods, validator responses with status 2xx, 304, Bearer challenge 400,
401, 403, 405, 421 or 503 take precedence over the transport's 405.
The stateful transport omits the session ID from validator responses, echoes it in
transport-owned errors only when the request carried the exact ID, and no longer logs raw IDs.
- Prompt message content blocks keep `annotations` and `meta`, and `resourceLink` blocks keep
`size`, `icons`, and `meta`.
- `Response.id` (`ID?`) represents JSON `null` distinctly from `""`, and rejects a `null` ID on a
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ public struct AcceptHeaderValidator: HTTPRequestValidator {
.invalidRequest(
"Not Acceptable: Client must accept both application/json and text/event-stream"
),
sessionID: context.sessionID
sessionID: nil
)
}
case .requiresJSON:
Expand All @@ -184,7 +184,7 @@ public struct AcceptHeaderValidator: HTTPRequestValidator {
.invalidRequest(
"Not Acceptable: Client must accept application/json"
),
sessionID: context.sessionID
sessionID: nil
)
}
}
Expand All @@ -195,7 +195,7 @@ public struct AcceptHeaderValidator: HTTPRequestValidator {
.invalidRequest(
"Not Acceptable: Client must accept text/event-stream"
),
sessionID: context.sessionID
sessionID: nil
)
}
default:
Expand Down Expand Up @@ -233,7 +233,7 @@ public struct ContentTypeValidator: HTTPRequestValidator {
.invalidRequest(
"Unsupported Media Type: Content-Type must be application/json"
),
sessionID: context.sessionID
sessionID: nil
)
}

Expand Down Expand Up @@ -287,7 +287,7 @@ public struct ProtocolVersionValidator: HTTPRequestValidator {
return .error(
statusCode: 400,
.headerMismatch("\(HTTPHeaderName.protocolVersion) appears more than once"),
sessionID: context.sessionID
sessionID: nil
)
}
}
Expand All @@ -298,7 +298,7 @@ public struct ProtocolVersionValidator: HTTPRequestValidator {
.unsupportedProtocolVersion(
supported: context.supportedProtocolVersions.sorted(by: >),
requested: version),
sessionID: context.sessionID
sessionID: nil
)
}

Expand Down Expand Up @@ -344,15 +344,15 @@ public struct SessionValidator: HTTPRequestValidator {
return .error(
statusCode: 400,
.invalidRequest("Bad Request: Missing \(HTTPHeaderName.sessionID) header"),
sessionID: expectedSessionID
sessionID: nil
)
}

guard requestSessionID == expectedSessionID else {
guard requestSessionID.isExactly(expectedSessionID) else {
return .error(
statusCode: 404,
.invalidRequest("Not Found: Invalid or expired session ID"),
sessionID: expectedSessionID
sessionID: nil
)
}

Expand Down Expand Up @@ -447,7 +447,7 @@ public struct OriginValidator: HTTPRequestValidator {
return .error(
statusCode: 421,
.invalidRequest("Misdirected Request: Host header not allowed"),
sessionID: context.sessionID
sessionID: nil
)
}
}
Expand All @@ -461,7 +461,7 @@ public struct OriginValidator: HTTPRequestValidator {
return .error(
statusCode: 403,
.invalidRequest("Forbidden: Origin not allowed"),
sessionID: context.sessionID
sessionID: nil
)
}
}
Expand Down Expand Up @@ -762,13 +762,11 @@ public struct BearerTokenValidator: HTTPRequestValidator {
return unauthorizedResponse(
challengeScope: challengeScopeProvider?(request, context),
error: nil,
errorDescription: nil,
sessionID: context.sessionID
errorDescription: nil
)
case .malformed(let message):
return invalidRequestResponse(
message: message, challengeScope: challengeScopeProvider?(request, context),
sessionID: context.sessionID)
message: message, challengeScope: challengeScopeProvider?(request, context))
}

switch await tokenVerifier(parsedToken, request, context).outcome {
Expand All @@ -778,8 +776,7 @@ public struct BearerTokenValidator: HTTPRequestValidator {
return unauthorizedResponse(
challengeScope: challengeScopeProvider?(request, context),
error: "invalid_token",
errorDescription: "Token has expired",
sessionID: context.sessionID
errorDescription: "Token has expired"
)
}
// Audience check — skipped for opaque tokens (audience == nil)
Expand All @@ -793,8 +790,7 @@ public struct BearerTokenValidator: HTTPRequestValidator {
return unauthorizedResponse(
challengeScope: challengeScopeProvider?(request, context),
error: "invalid_token",
errorDescription: "Token audience mismatch",
sessionID: context.sessionID
errorDescription: "Token audience mismatch"
)
}
}
Expand All @@ -804,28 +800,26 @@ public struct BearerTokenValidator: HTTPRequestValidator {
return unauthorizedResponse(
challengeScope: challengeScopeProvider?(request, context),
error: "invalid_token",
errorDescription: errorDescription,
sessionID: context.sessionID
errorDescription: errorDescription
)

case .insufficientScope(let requiredScopes, let errorDescription):
return forbiddenInsufficientScopeResponse(
requiredScopes: requiredScopes,
errorDescription: errorDescription,
sessionID: context.sessionID
errorDescription: errorDescription
)

case .malformedRequest(let errorDescription):
return invalidRequestResponse(
message: errorDescription ?? "Malformed authorization request",
challengeScope: challengeScopeProvider?(request, context), sessionID: context.sessionID)
challengeScope: challengeScopeProvider?(request, context))
}
}

/// 400 with a Bearer challenge carrying `error="invalid_request"`
/// (RFC 6750 §3.1), so the client still learns `resource_metadata`.
private func invalidRequestResponse(
message: String, challengeScope: Set<String>?, sessionID: String?
message: String, challengeScope: Set<String>?
) -> HTTPResponse {
let challenge = makeBearerChallenge(
resourceMetadataURL: resourceMetadataURL,
Expand All @@ -836,16 +830,14 @@ public struct BearerTokenValidator: HTTPRequestValidator {
return .error(
statusCode: 400,
.invalidRequest("Bad Request: \(message)"),
sessionID: sessionID,
extraHeaders: [HTTPHeaderName.wwwAuthenticate: challenge]
)
}

private func unauthorizedResponse(
challengeScope: Set<String>?,
error: String?,
errorDescription: String?,
sessionID: String?
errorDescription: String?
) -> HTTPResponse {
let challenge = makeBearerChallenge(
resourceMetadataURL: resourceMetadataURL,
Expand All @@ -856,15 +848,13 @@ public struct BearerTokenValidator: HTTPRequestValidator {
return .error(
statusCode: 401,
.invalidRequest("Unauthorized"),
sessionID: sessionID,
extraHeaders: [HTTPHeaderName.wwwAuthenticate: challenge]
)
}

private func forbiddenInsufficientScopeResponse(
requiredScopes: Set<String>,
errorDescription: String?,
sessionID: String?
errorDescription: String?
) -> HTTPResponse {
let challenge = makeBearerChallenge(
resourceMetadataURL: resourceMetadataURL,
Expand All @@ -875,7 +865,6 @@ public struct BearerTokenValidator: HTTPRequestValidator {
return .error(
statusCode: 403,
.invalidRequest("Forbidden: Insufficient scope"),
sessionID: sessionID,
extraHeaders: [HTTPHeaderName.wwwAuthenticate: challenge]
)
}
Expand Down
16 changes: 15 additions & 1 deletion Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,8 @@ public struct HTTPResponse: Sendable {
/// - statusCode: The HTTP status code of the response.
/// - error: The JSON-RPC error to encode in the response body.
/// - id: The JSON-RPC request ID, or `nil` when absent or unknown.
/// - sessionID: The active session ID to send in `MCP-Session-Id`, if any.
/// - sessionID: The session ID to send in `MCP-Session-Id`. Pass it only when
/// the request carried the same ID.
/// - extraHeaders: Additional response headers merged into the response.
/// - Returns: An HTTP response carrying the encoded JSON-RPC error body.
public static func error(
Expand Down Expand Up @@ -372,6 +373,19 @@ public struct HTTPResponse: Sendable {
}
}

extension HTTPResponse {
/// Whether a validator's response answers a method the transport does not
/// serve, including responder replies and authentication challenges.
var answersUnsupportedMethod: Bool {
(200..<300).contains(statusCode) || statusCode == 304
|| statusCode == 401 || statusCode == 403 || statusCode == 405
|| statusCode == 421 || statusCode == 503
|| (statusCode == 400 && headers.keys.contains {
$0.caseInsensitiveCompare(HTTPHeaderName.wwwAuthenticate) == .orderedSame
})
}
Comment on lines +376 to +386

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Blocking: BearerTokenValidator returns 400 Bad Request with WWW-Authenticate: Bearer ..., error="invalid_request" (RFC 6750 §3.1) for malformed Bearer headers and .malformedRequest verifier results (HTTPRequestValidation.swift:767-770, 812-835).

Because answersUnsupportedMethod omits those responses, an unsupported method (PUT, OPTIONS, or GET/DELETE on StatelessHTTPServerTransport) with a malformed Authorization: Bearer header discards the 400 + WWW-Authenticate challenge and falls through to 405 Method Not Allowed — and on StatefulHTTPServerTransport, because BearerTokenValidator stopped the pipeline before SessionValidator, that 405 also echoes MCP-Session-Id (echoedSessionID(for: request)) to a request that failed authentication.

Similarly, ServerCardResponder returns 405 with Allow: GET, HEAD, OPTIONS for unsupported methods on /server-card (ServerCardResponder.swift:90-94), which this check discards and overwrites with the transport's Allow header.

Suggested fix:

extension HTTPResponse {
    var answersUnsupportedMethod: Bool {
        (200..<300).contains(statusCode) || statusCode == 304
            || statusCode == 401 || statusCode == 403 || statusCode == 405 || statusCode == 421
            || headers[HTTPHeaderName.wwwAuthenticate] != nil
    }
}

}

// MARK: - HTTP Header Names

/// Standard header names used by the MCP Streamable HTTP transport.
Expand Down
Loading
Loading