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
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,9 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha
`UnsubscribeFromResource.Parameters.init(uri:meta:)` are public, and
`Client.subscribedResourceURIs` lists active handshake subscriptions in addition to 2026-07-28
listen streams.
- `StatefulHTTPServerTransport(sessionPrincipal:)` binds a session to the principal of the
`initialize` request that created it; requests from another principal get the 404 of an unknown
session.
- `DataURL`: explicit RFC 2397 `data:` URL value type (`Codable`, `Hashable`, `Sendable`) with
strict RFC 2045 token header validation and MIME type normalization.
- From `main` after 0.12.1: `Implementation` carries `description`, `websiteURL` and `icons`, sent
Expand All @@ -400,6 +403,13 @@ 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.
- A refused `initialize` on the stateful transport closes the dropped session's streams and
forgets its stored events, so a session created next on the transport receives none of them.
- 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
})
}
}

// MARK: - HTTP Header Names

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