V0.11.x (#199)
* Support 2025-06-18 Spec (#167) * Support OpenAI _meta for Tool * Update init * Add title and outputSchema * Concurreny issue * General fields * Add Generate Fields to Server elements * 4 tab spacing * Update Version * Elicitation * Format * More tests and inits * Elicitation in README * Fix orphaned test * Add title to more structs * Public init * Fix meta validation and make tests more generic * Format and make Result properties public again * Revert more visibility changes * feat: 2025-11-25 phase 1, includes Version, Icon, Progress (#181) * chore: fixed unit tests * feat: added icon and progess base structs * feat: added progress notification and meta to callTool * feat: added tests * feat: simplified RequestMeta encoding/decoding * tests: added unit test to track progress * chore: rebased v0.11.x * feat: implemented cancellation * feat: added overloaded callTool method * fix: encoding Response _meta fix * chore: added old version to the versions list * feat: 2025-11-25 phase 2; added Logging and Completions (#196) * feat: added Logging and Completions * feat: updated EmbeddedResource for the latest spec * chore: changed encoding of meta in Prompts to encodeIfPresent * feat: compliance tests + http server transport (#197) * feat: http server transport * feat: added http server transport * feat: removed unused files * feat: added conformance tests * feat: improved conformace testing * chore: removed redundant files * feat/2025-11-25: sampling, elicitation, roots (#198) * feat: Roots implementation * feat: added unit testing * feat: improved unit tests and fixed NetworkTransport crash * feat: implemented sampling and elicitation * feat: improved sampling tests * feat: improved elicitation tests * feat: improved confirmance tests * feat: improved Prompts unit tests * feat: removed test code * feat: updated conformance tests * chore: removed redundant commas * chore: removed 6.0.3 swift version from ci * chore: improved unit tests a little bit * chore: update README.md * chore: add server progress tracking example to README.md * chore: updated README.md * chore: updated transports table formatting * chore: updated MockNetworkConnection --------- Co-authored-by: Austin Evans <austinjevans@me.com> Co-authored-by: yehorsobko <yehorsobko@macpaw.com>
This commit is contained in:
parent
6fa1a97b41
commit
6112a3995a
4 changed files with 11854 additions and 828 deletions
|
|
@ -0,0 +1,371 @@
|
|||
import Foundation
|
||||
|
||||
// MARK: - Validation Protocol
|
||||
|
||||
/// Validates an incoming HTTP request before the transport processes it.
|
||||
///
|
||||
/// Validators are composed into a pipeline and executed in order. The first validator
|
||||
/// that returns a non-nil response short-circuits the pipeline and that error response
|
||||
/// is returned to the client.
|
||||
///
|
||||
/// Conform to this protocol to add custom validation (e.g., authentication):
|
||||
/// ```swift
|
||||
/// struct BearerTokenValidator: HTTPRequestValidator {
|
||||
/// func validate(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? {
|
||||
/// guard let auth = request.header("Authorization"),
|
||||
/// auth.hasPrefix("Bearer ") else {
|
||||
/// return .error(statusCode: 401, .invalidRequest("Missing bearer token"))
|
||||
/// }
|
||||
/// return nil
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
public protocol HTTPRequestValidator: Sendable {
|
||||
/// Validates the request. Returns an error response if invalid, or `nil` if valid.
|
||||
func validate(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse?
|
||||
}
|
||||
|
||||
// MARK: - Validation Context
|
||||
|
||||
/// Context provided to validators for making validation decisions.
|
||||
public struct HTTPValidationContext: Sendable {
|
||||
/// The HTTP method of the request (GET, POST, DELETE).
|
||||
public let httpMethod: String
|
||||
|
||||
/// The current session ID, if any (nil in stateless mode or before initialization).
|
||||
public let sessionID: String?
|
||||
|
||||
/// Whether the request body contains an `initialize` JSON-RPC request.
|
||||
public let isInitializationRequest: Bool
|
||||
|
||||
/// The set of protocol versions this server supports.
|
||||
public let supportedProtocolVersions: Set<String>
|
||||
|
||||
public init(
|
||||
httpMethod: String,
|
||||
sessionID: String? = nil,
|
||||
isInitializationRequest: Bool = false,
|
||||
supportedProtocolVersions: Set<String> = Version.supported
|
||||
) {
|
||||
self.httpMethod = httpMethod
|
||||
self.sessionID = sessionID
|
||||
self.isInitializationRequest = isInitializationRequest
|
||||
self.supportedProtocolVersions = supportedProtocolVersions
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Accept Header Validator
|
||||
|
||||
/// Validates the `Accept` header based on the HTTP method and transport response mode.
|
||||
///
|
||||
/// - Stateful (SSE) mode: POST requests must accept both `application/json` and `text/event-stream`
|
||||
/// - Stateless (JSON) mode: POST requests only need to accept `application/json`
|
||||
/// - GET requests always require `text/event-stream`
|
||||
public struct AcceptHeaderValidator: HTTPRequestValidator {
|
||||
/// The response mode determines which content types are required.
|
||||
public enum Mode: Sendable {
|
||||
/// POST requires both `application/json` and `text/event-stream`.
|
||||
case sseRequired
|
||||
/// POST only requires `application/json`.
|
||||
case jsonOnly
|
||||
}
|
||||
|
||||
public let mode: Mode
|
||||
|
||||
public init(mode: Mode) {
|
||||
self.mode = mode
|
||||
}
|
||||
|
||||
public func validate(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? {
|
||||
let accept = request.header(HTTPHeaderName.accept) ?? ""
|
||||
let acceptTypes = accept.split(separator: ",").map {
|
||||
$0.trimmingCharacters(in: .whitespaces)
|
||||
}
|
||||
|
||||
let hasJSON = acceptTypes.contains { $0.hasPrefix(ContentType.json) }
|
||||
let hasSSE = acceptTypes.contains { $0.hasPrefix(ContentType.sse) }
|
||||
|
||||
switch context.httpMethod {
|
||||
case "POST":
|
||||
switch mode {
|
||||
case .sseRequired:
|
||||
guard hasJSON, hasSSE else {
|
||||
return .error(
|
||||
statusCode: 406,
|
||||
.invalidRequest(
|
||||
"Not Acceptable: Client must accept both application/json and text/event-stream"
|
||||
),
|
||||
sessionID: context.sessionID
|
||||
)
|
||||
}
|
||||
case .jsonOnly:
|
||||
guard hasJSON else {
|
||||
return .error(
|
||||
statusCode: 406,
|
||||
.invalidRequest(
|
||||
"Not Acceptable: Client must accept application/json"
|
||||
),
|
||||
sessionID: context.sessionID
|
||||
)
|
||||
}
|
||||
}
|
||||
case "GET":
|
||||
guard hasSSE else {
|
||||
return .error(
|
||||
statusCode: 406,
|
||||
.invalidRequest(
|
||||
"Not Acceptable: Client must accept text/event-stream"
|
||||
),
|
||||
sessionID: context.sessionID
|
||||
)
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Content-Type Validator
|
||||
|
||||
/// Validates that POST requests have `Content-Type: application/json`.
|
||||
public struct ContentTypeValidator: HTTPRequestValidator {
|
||||
public init() {}
|
||||
|
||||
public func validate(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? {
|
||||
guard context.httpMethod == "POST" else { return nil }
|
||||
|
||||
let contentType = request.header(HTTPHeaderName.contentType) ?? ""
|
||||
let mainType = contentType.split(separator: ";").first?
|
||||
.trimmingCharacters(in: .whitespaces) ?? ""
|
||||
|
||||
guard mainType == ContentType.json else {
|
||||
return .error(
|
||||
statusCode: 415,
|
||||
.invalidRequest(
|
||||
"Unsupported Media Type: Content-Type must be application/json"
|
||||
),
|
||||
sessionID: context.sessionID
|
||||
)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Protocol Version Validator
|
||||
|
||||
/// Validates the `MCP-Protocol-Version` header against supported versions.
|
||||
///
|
||||
/// Per spec:
|
||||
/// - If the header is absent, the server assumes the default negotiated version
|
||||
/// - If the header is present but unsupported, the server returns 400 Bad Request
|
||||
/// - Initialization requests are exempt (protocol version comes from the request body)
|
||||
public struct ProtocolVersionValidator: HTTPRequestValidator {
|
||||
public init() {}
|
||||
|
||||
public func validate(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? {
|
||||
// Skip for initialization requests (version is in the body, not the header)
|
||||
guard !context.isInitializationRequest else { return nil }
|
||||
|
||||
// Skip for non-POST methods (GET/DELETE don't carry protocol version)
|
||||
// Actually, per spec, all subsequent requests should include it
|
||||
guard let version = request.header(HTTPHeaderName.protocolVersion) else {
|
||||
// Per spec: if not received, assume default version
|
||||
return nil
|
||||
}
|
||||
|
||||
guard context.supportedProtocolVersions.contains(version) else {
|
||||
let supported = context.supportedProtocolVersions.sorted().joined(separator: ", ")
|
||||
return .error(
|
||||
statusCode: 400,
|
||||
.invalidRequest(
|
||||
"Bad Request: Unsupported protocol version: \(version). Supported: \(supported)"
|
||||
),
|
||||
sessionID: context.sessionID
|
||||
)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Session Validator
|
||||
|
||||
/// Validates the `Mcp-Session-Id` header for stateful transports.
|
||||
///
|
||||
/// - Initialization requests are exempt (no session exists yet)
|
||||
/// - Non-initialization requests must include the session ID header
|
||||
/// - The session ID must match the active session
|
||||
public struct SessionValidator: HTTPRequestValidator {
|
||||
public init() {}
|
||||
|
||||
public func validate(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? {
|
||||
// Skip validation for initialization requests
|
||||
guard !context.isInitializationRequest else { return nil }
|
||||
|
||||
// If no session exists yet, skip (server hasn't been initialized)
|
||||
guard let expectedSessionID = context.sessionID else { return nil }
|
||||
|
||||
let requestSessionID = request.header(HTTPHeaderName.sessionID)
|
||||
|
||||
guard let requestSessionID else {
|
||||
return .error(
|
||||
statusCode: 400,
|
||||
.invalidRequest("Bad Request: Missing \(HTTPHeaderName.sessionID) header"),
|
||||
sessionID: expectedSessionID
|
||||
)
|
||||
}
|
||||
|
||||
guard requestSessionID == expectedSessionID else {
|
||||
return .error(
|
||||
statusCode: 404,
|
||||
.invalidRequest("Not Found: Invalid or expired session ID"),
|
||||
sessionID: expectedSessionID
|
||||
)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Origin Validator
|
||||
|
||||
/// DNS rebinding protection: validates `Origin` and `Host` headers.
|
||||
///
|
||||
/// Per spec, servers MUST validate the Origin header to prevent DNS rebinding attacks.
|
||||
/// This is particularly important for servers running on localhost.
|
||||
///
|
||||
/// Use `.localhost()` for local development servers.
|
||||
/// Use `.disabled` to skip validation (e.g., cloud deployments).
|
||||
/// Use `init(allowedHosts:allowedOrigins:)` for custom configurations.
|
||||
public struct OriginValidator: HTTPRequestValidator {
|
||||
public let allowedHosts: [String]
|
||||
public let allowedOrigins: [String]
|
||||
private let enabled: Bool
|
||||
|
||||
public init(allowedHosts: [String], allowedOrigins: [String]) {
|
||||
self.allowedHosts = allowedHosts
|
||||
self.allowedOrigins = allowedOrigins
|
||||
self.enabled = true
|
||||
}
|
||||
|
||||
private init(disabled: Void) {
|
||||
self.allowedHosts = []
|
||||
self.allowedOrigins = []
|
||||
self.enabled = false
|
||||
}
|
||||
|
||||
/// Protection for localhost-bound servers.
|
||||
/// Allows requests from `localhost`, `127.0.0.1`, and `[::1]` with the specified port.
|
||||
public static func localhost(port: Int? = nil) -> OriginValidator {
|
||||
let portPattern = port.map { String($0) } ?? "*"
|
||||
return OriginValidator(
|
||||
allowedHosts: [
|
||||
"127.0.0.1:\(portPattern)",
|
||||
"localhost:\(portPattern)",
|
||||
"[::1]:\(portPattern)",
|
||||
],
|
||||
allowedOrigins: [
|
||||
"http://127.0.0.1:\(portPattern)",
|
||||
"http://localhost:\(portPattern)",
|
||||
"http://[::1]:\(portPattern)",
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
/// Disables DNS rebinding protection.
|
||||
/// Use for cloud deployments where DNS rebinding is not a threat.
|
||||
public static var disabled: OriginValidator {
|
||||
OriginValidator(disabled: ())
|
||||
}
|
||||
|
||||
public func validate(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? {
|
||||
guard enabled else { return nil }
|
||||
|
||||
// Validate Host header
|
||||
if let host = request.header(HTTPHeaderName.host) {
|
||||
let hostAllowed = allowedHosts.contains { pattern in
|
||||
matchesPattern(host, pattern: pattern)
|
||||
}
|
||||
if !hostAllowed {
|
||||
return .error(
|
||||
statusCode: 421,
|
||||
.invalidRequest("Misdirected Request: Host header not allowed"),
|
||||
sessionID: context.sessionID
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Validate Origin header (only if present — non-browser clients won't send it)
|
||||
if let origin = request.header(HTTPHeaderName.origin) {
|
||||
let originAllowed = allowedOrigins.contains { pattern in
|
||||
matchesPattern(origin, pattern: pattern)
|
||||
}
|
||||
if !originAllowed {
|
||||
return .error(
|
||||
statusCode: 403,
|
||||
.invalidRequest("Forbidden: Origin not allowed"),
|
||||
sessionID: context.sessionID
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Matches a value against a pattern that may contain a port wildcard `:*`.
|
||||
///
|
||||
/// Examples:
|
||||
/// - `"localhost:*"` matches `"localhost:8080"`, `"localhost:3000"`
|
||||
/// - `"http://localhost:*"` matches `"http://localhost:8080"`
|
||||
/// - `"localhost:8080"` matches only `"localhost:8080"` exactly
|
||||
private func matchesPattern(_ value: String, pattern: String) -> Bool {
|
||||
guard pattern.hasSuffix(":*") else {
|
||||
return value == pattern
|
||||
}
|
||||
|
||||
let prefix = String(pattern.dropLast(2))
|
||||
guard value.hasPrefix(prefix + ":") else { return false }
|
||||
|
||||
let portPart = value.dropFirst(prefix.count + 1)
|
||||
return !portPart.isEmpty && portPart.allSatisfy(\.isNumber)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Validation Pipeline Protocol
|
||||
|
||||
/// Runs a validation pipeline against an HTTP request.
|
||||
///
|
||||
/// Implementations execute a sequence of validators and return the first error,
|
||||
/// or `nil` if all validations pass.
|
||||
public protocol HTTPRequestValidationPipeline: Sendable {
|
||||
/// Validates the request using the configured pipeline.
|
||||
/// Returns an error response if validation fails, or `nil` if the request is valid.
|
||||
func validate(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse?
|
||||
}
|
||||
|
||||
// MARK: - Standard Validation Pipeline
|
||||
|
||||
/// Standard implementation of `HTTPRequestValidationPipeline` that runs validators in sequence.
|
||||
///
|
||||
/// The first validator that returns a non-nil error response short-circuits the pipeline.
|
||||
public struct StandardValidationPipeline: HTTPRequestValidationPipeline {
|
||||
private let validators: [any HTTPRequestValidator]
|
||||
|
||||
/// Creates a pipeline with the given validators.
|
||||
/// Validators are executed in the order provided.
|
||||
public init(validators: [any HTTPRequestValidator]) {
|
||||
self.validators = validators
|
||||
}
|
||||
|
||||
public func validate(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? {
|
||||
for validator in validators {
|
||||
if let errorResponse = validator.validate(request, context: context) {
|
||||
return errorResponse
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
259
Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift
Normal file
259
Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift
Normal file
|
|
@ -0,0 +1,259 @@
|
|||
import Foundation
|
||||
|
||||
// MARK: - Session ID Generator
|
||||
|
||||
/// Generates unique session identifiers for stateful HTTP server transports.
|
||||
///
|
||||
/// Conform to this protocol to provide custom session ID generation logic.
|
||||
/// Session IDs **MUST** contain only visible ASCII characters (0x21–0x7E)
|
||||
/// per the MCP specification.
|
||||
///
|
||||
/// A default implementation using UUID is provided via ``UUIDSessionIDGenerator``.
|
||||
public protocol SessionIDGenerator: Sendable {
|
||||
/// Generates a new unique session identifier.
|
||||
func generateSessionID() -> String
|
||||
}
|
||||
|
||||
/// Default session ID generator that produces UUID strings.
|
||||
///
|
||||
/// UUID strings consist of hexadecimal characters and hyphens,
|
||||
/// which are all within the valid ASCII range (0x21–0x7E).
|
||||
public struct UUIDSessionIDGenerator: SessionIDGenerator {
|
||||
public init() {}
|
||||
|
||||
public func generateSessionID() -> String {
|
||||
UUID().uuidString
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - HTTP Request
|
||||
|
||||
/// A framework-agnostic HTTP request representation.
|
||||
///
|
||||
/// This type decouples the transport from any specific HTTP framework.
|
||||
/// The HTTP framework adapter converts its native request type into this before passing to the transport.
|
||||
public struct HTTPRequest: Sendable {
|
||||
/// The HTTP method (e.g., "GET", "POST", "DELETE").
|
||||
public let method: String
|
||||
|
||||
/// HTTP headers as key-value pairs.
|
||||
public let headers: [String: String]
|
||||
|
||||
/// The request body data, if any.
|
||||
public let body: Data?
|
||||
|
||||
public init(method: String, headers: [String: String] = [:], body: Data? = nil) {
|
||||
self.method = method
|
||||
self.headers = headers
|
||||
self.body = body
|
||||
}
|
||||
|
||||
/// Case-insensitive header lookup.
|
||||
public func header(_ name: String) -> String? {
|
||||
let lowercased = name.lowercased()
|
||||
return headers.first { $0.key.lowercased() == lowercased }?.value
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - HTTP Response
|
||||
|
||||
/// A framework-agnostic HTTP response.
|
||||
///
|
||||
/// The HTTP framework adapter converts this into its native response type.
|
||||
///
|
||||
/// Use computed properties (`statusCode`, `headers`, `bodyData`) for generic access,
|
||||
/// or switch on the enum for case-specific handling (e.g., streaming):
|
||||
///
|
||||
/// ```swift
|
||||
/// let response = await transport.handleRequest(request)
|
||||
/// switch response {
|
||||
/// case .stream(let sseStream, _):
|
||||
/// // Pipe the async stream to the HTTP response body
|
||||
/// default:
|
||||
/// // Use response.bodyData for the body
|
||||
/// }
|
||||
/// ```
|
||||
public enum HTTPResponse: Sendable {
|
||||
/// 202 Accepted, no body. Used for notifications and client responses.
|
||||
case accepted(headers: [String: String] = [:])
|
||||
|
||||
/// 200 OK, no body. Used for DELETE confirmation.
|
||||
case ok(headers: [String: String] = [:])
|
||||
|
||||
/// 200 OK with data body (typically JSON).
|
||||
case data(Data, headers: [String: String] = [:])
|
||||
|
||||
/// 200 OK with SSE streaming body.
|
||||
case stream(AsyncThrowingStream<Data, Swift.Error>, headers: [String: String] = [:])
|
||||
|
||||
/// Error response with a JSON-RPC error body.
|
||||
/// The status code, headers, and body are derived automatically.
|
||||
case error(statusCode: Int, MCPError, sessionID: String? = nil)
|
||||
|
||||
// MARK: - Computed Properties
|
||||
|
||||
public var statusCode: Int {
|
||||
switch self {
|
||||
case .accepted: 202
|
||||
case .ok, .data, .stream: 200
|
||||
case .error(let code, _, _): code
|
||||
}
|
||||
}
|
||||
|
||||
public var headers: [String: String] {
|
||||
switch self {
|
||||
case .accepted(let headers), .ok(let headers), .data(_, let headers), .stream(_, let headers):
|
||||
return headers
|
||||
case .error(_, _, let sessionID):
|
||||
var headers: [String: String] = [HTTPHeaderName.contentType: ContentType.json]
|
||||
if let sessionID { headers[HTTPHeaderName.sessionID] = sessionID }
|
||||
return headers
|
||||
}
|
||||
}
|
||||
|
||||
/// The response body as data. `nil` for `.accepted`, `.ok`, and `.stream`.
|
||||
public var bodyData: Data? {
|
||||
switch self {
|
||||
case .accepted, .ok, .stream:
|
||||
return nil
|
||||
case .data(let data, _):
|
||||
return data
|
||||
case .error(_, let error, _):
|
||||
let errorBody: [String: Any] = [
|
||||
"jsonrpc": "2.0",
|
||||
"error": [
|
||||
"code": error.code,
|
||||
"message": error.errorDescription ?? "Unknown error",
|
||||
],
|
||||
"id": NSNull(),
|
||||
]
|
||||
return try? JSONSerialization.data(withJSONObject: errorBody)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - HTTP Header Names
|
||||
|
||||
/// Standard header names used by the MCP Streamable HTTP transport.
|
||||
public enum HTTPHeaderName {
|
||||
public static let sessionID = "Mcp-Session-Id"
|
||||
public static let protocolVersion = "Mcp-Protocol-Version"
|
||||
public static let lastEventID = "Last-Event-Id"
|
||||
public static let accept = "Accept"
|
||||
public static let contentType = "Content-Type"
|
||||
public static let origin = "Origin"
|
||||
public static let host = "Host"
|
||||
public static let cacheControl = "Cache-Control"
|
||||
public static let connection = "Connection"
|
||||
public static let allow = "Allow"
|
||||
}
|
||||
|
||||
// MARK: - Content Types
|
||||
|
||||
enum ContentType {
|
||||
static let json = "application/json"
|
||||
static let sse = "text/event-stream"
|
||||
}
|
||||
|
||||
// MARK: - SSE Event
|
||||
|
||||
/// A Server-Sent Event (SSE) data structure.
|
||||
///
|
||||
/// Formats according to the SSE specification:
|
||||
/// https://html.spec.whatwg.org/multipage/server-sent-events.html
|
||||
struct SSEEvent: Sendable {
|
||||
var id: String?
|
||||
var event: String?
|
||||
var data: String
|
||||
var retry: Int?
|
||||
|
||||
/// Formats the event as SSE wire data.
|
||||
func formatted() -> Data {
|
||||
var result = ""
|
||||
if let id {
|
||||
result += "id: \(id)\n"
|
||||
}
|
||||
if let event {
|
||||
result += "event: \(event)\n"
|
||||
}
|
||||
if let retry {
|
||||
result += "retry: \(retry)\n"
|
||||
}
|
||||
result += "data: \(data)\n\n"
|
||||
return Data(result.utf8)
|
||||
}
|
||||
|
||||
/// Creates a priming event with an empty data field.
|
||||
/// Per spec, this is sent immediately to prime the client for reconnection.
|
||||
static func priming(id: String, retry: Int? = nil) -> SSEEvent {
|
||||
SSEEvent(id: id, event: nil, data: "", retry: retry)
|
||||
}
|
||||
|
||||
/// Creates a message event wrapping JSON-RPC data.
|
||||
static func message(data: Data, id: String? = nil) -> SSEEvent {
|
||||
SSEEvent(
|
||||
id: id,
|
||||
event: "message",
|
||||
data: String(decoding: data, as: UTF8.self)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - JSON-RPC Message Classification
|
||||
|
||||
/// Classifies a raw JSON-RPC message for routing purposes.
|
||||
///
|
||||
/// Used by transports to determine where to route outgoing messages:
|
||||
/// - Responses are routed to the originating request's stream
|
||||
/// - Notifications and server requests are routed to the standalone GET stream
|
||||
package enum JSONRPCMessageKind {
|
||||
case request(id: String, method: String)
|
||||
case notification(method: String)
|
||||
case response(id: String)
|
||||
|
||||
/// Attempts to classify raw JSON-RPC data.
|
||||
/// Returns `nil` if the data cannot be parsed or classified.
|
||||
package init?(data: Data) {
|
||||
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let id = Self.extractID(from: json)
|
||||
|
||||
if let method = json["method"] as? String {
|
||||
if let id {
|
||||
self = .request(id: id, method: method)
|
||||
} else {
|
||||
self = .notification(method: method)
|
||||
}
|
||||
} else if json["result"] != nil || json["error"] != nil {
|
||||
guard let id else { return nil }
|
||||
self = .response(id: id)
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this message is a JSON-RPC response (success or error).
|
||||
var isResponse: Bool {
|
||||
if case .response = self { return true }
|
||||
return false
|
||||
}
|
||||
|
||||
/// Whether this message is an `initialize` request.
|
||||
package var isInitializeRequest: Bool {
|
||||
if case .request(_, let method) = self {
|
||||
return method == "initialize"
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private static func extractID(from json: [String: Any]) -> String? {
|
||||
if let stringID = json["id"] as? String {
|
||||
return stringID
|
||||
} else if let intID = json["id"] as? Int {
|
||||
return String(intID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,546 @@
|
|||
import Foundation
|
||||
import Logging
|
||||
|
||||
/// A stateful HTTP server transport that manages sessions and uses SSE for streaming responses.
|
||||
///
|
||||
/// This transport implements the MCP Streamable HTTP specification with full session management:
|
||||
/// - Assigns a session ID during initialization (via `Mcp-Session-Id` header)
|
||||
/// - POST requests receive SSE-streamed responses
|
||||
/// - GET requests establish a standalone SSE stream for server-initiated messages
|
||||
/// - DELETE requests terminate the session
|
||||
/// - Built-in event store for resumability (reconnection with `Last-Event-ID`)
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// ```swift
|
||||
/// let transport = StatefulHTTPServerTransport() // Uses UUID by default
|
||||
///
|
||||
/// // Start the MCP server with this transport
|
||||
/// try await server.start(transport: transport)
|
||||
///
|
||||
/// // In your HTTP framework handler:
|
||||
/// let response = await transport.handleRequest(httpRequest)
|
||||
/// // Convert response to your framework's response type and return it
|
||||
/// ```
|
||||
///
|
||||
/// ## Framework Integration
|
||||
///
|
||||
/// This transport is framework-agnostic. You provide incoming requests as `HTTPRequest`
|
||||
/// and receive `HTTPResponse` values to convert to your framework's native types.
|
||||
/// For SSE responses, the `.stream` case provides an `AsyncThrowingStream<Data, Error>`
|
||||
/// to pipe to the client.
|
||||
public actor StatefulHTTPServerTransport: Transport {
|
||||
public nonisolated let logger: Logger
|
||||
|
||||
// MARK: - Dependencies
|
||||
|
||||
private let sessionIDGenerator: any SessionIDGenerator
|
||||
private let validationPipeline: any HTTPRequestValidationPipeline
|
||||
private let retryInterval: Int?
|
||||
|
||||
// MARK: - State
|
||||
|
||||
private var sessionID: String?
|
||||
private var terminated = false
|
||||
private var started = false
|
||||
|
||||
// MARK: - Incoming message stream (client → server)
|
||||
|
||||
private let incomingStream: AsyncThrowingStream<Data, Swift.Error>
|
||||
private let incomingContinuation: AsyncThrowingStream<Data, Swift.Error>.Continuation
|
||||
|
||||
// MARK: - SSE streams for POST request responses
|
||||
|
||||
/// Maps request ID → SSE stream continuation for active POST request streams.
|
||||
private var requestSSEContinuations: [String: AsyncThrowingStream<Data, Swift.Error>.Continuation] = [:]
|
||||
|
||||
// MARK: - Standalone GET SSE stream
|
||||
|
||||
/// The standalone SSE stream continuation for server-initiated messages.
|
||||
/// Only one GET stream is allowed per session.
|
||||
private var standaloneSSEContinuation: AsyncThrowingStream<Data, Swift.Error>.Continuation?
|
||||
|
||||
/// Internal identifier for the standalone GET stream in the event store.
|
||||
private let standaloneStreamID = "_GET_stream"
|
||||
|
||||
// MARK: - Event Store (Resumability)
|
||||
|
||||
private struct StoredEvent {
|
||||
let streamID: String
|
||||
let eventID: String
|
||||
let message: Data?
|
||||
}
|
||||
|
||||
private var storedEvents: [StoredEvent] = []
|
||||
private var eventCounter: Int = 0
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a new stateful HTTP server transport.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sessionIDGenerator: Generator for session IDs. The IDs MUST contain
|
||||
/// only visible ASCII characters (0x21-0x7E) per the MCP specification.
|
||||
/// Defaults to ``UUIDSessionIDGenerator``.
|
||||
/// - validationPipeline: Custom validation pipeline. If `nil`, uses sensible defaults:
|
||||
/// origin validation (localhost), Accept header (SSE required), Content-Type,
|
||||
/// protocol version, and session validation.
|
||||
/// - retryInterval: Retry interval in milliseconds for SSE priming events.
|
||||
/// Controls how long clients wait before attempting to reconnect.
|
||||
/// - logger: Optional logger. If `nil`, a no-op logger is used.
|
||||
public init(
|
||||
sessionIDGenerator: any SessionIDGenerator = UUIDSessionIDGenerator(),
|
||||
validationPipeline: (any HTTPRequestValidationPipeline)? = nil,
|
||||
retryInterval: Int? = nil,
|
||||
logger: Logger? = nil
|
||||
) {
|
||||
self.sessionIDGenerator = sessionIDGenerator
|
||||
self.validationPipeline = validationPipeline ?? StandardValidationPipeline(validators: [
|
||||
OriginValidator.localhost(),
|
||||
AcceptHeaderValidator(mode: .sseRequired),
|
||||
ContentTypeValidator(),
|
||||
ProtocolVersionValidator(),
|
||||
SessionValidator(),
|
||||
])
|
||||
self.retryInterval = retryInterval
|
||||
self.logger = logger ?? Logger(
|
||||
label: "mcp.transport.http.server.stateful",
|
||||
factory: { _ in SwiftLogNoOpLogHandler() }
|
||||
)
|
||||
|
||||
let (stream, continuation) = AsyncThrowingStream<Data, Swift.Error>.makeStream()
|
||||
self.incomingStream = stream
|
||||
self.incomingContinuation = continuation
|
||||
}
|
||||
|
||||
// MARK: - Transport Conformance
|
||||
|
||||
public func connect() async throws {
|
||||
guard !started else {
|
||||
throw MCPError.internalError("Transport already started")
|
||||
}
|
||||
started = true
|
||||
logger.debug("Stateful HTTP server transport started")
|
||||
}
|
||||
|
||||
public func disconnect() async {
|
||||
terminate()
|
||||
}
|
||||
|
||||
/// Routes outgoing server messages to the appropriate client connection.
|
||||
///
|
||||
/// - Responses are routed to the SSE stream matching the response's JSON-RPC ID.
|
||||
/// - Notifications and server-initiated requests are routed to the standalone GET stream.
|
||||
public func send(_ data: Data) async throws {
|
||||
guard !terminated else {
|
||||
throw MCPError.connectionClosed
|
||||
}
|
||||
|
||||
guard let kind = JSONRPCMessageKind(data: data) else {
|
||||
logger.warning("Could not classify outgoing message for routing")
|
||||
return
|
||||
}
|
||||
|
||||
switch kind {
|
||||
case .response(let id):
|
||||
routeResponse(data, requestID: id)
|
||||
case .notification, .request:
|
||||
routeServerInitiatedMessage(data)
|
||||
}
|
||||
}
|
||||
|
||||
public func receive() -> AsyncThrowingStream<Data, Swift.Error> {
|
||||
incomingStream
|
||||
}
|
||||
|
||||
// MARK: - HTTP Request Handler
|
||||
|
||||
/// Handles an incoming HTTP request from the framework adapter.
|
||||
///
|
||||
/// Routes by HTTP method:
|
||||
/// - **POST**: JSON-RPC messages (requests, notifications)
|
||||
/// - **GET**: Establish standalone SSE stream for server-initiated messages
|
||||
/// - **DELETE**: Terminate the session
|
||||
/// - Others: 405 Method Not Allowed
|
||||
public func handleRequest(_ request: HTTPRequest) async -> HTTPResponse {
|
||||
if terminated {
|
||||
return .error(
|
||||
statusCode: 404,
|
||||
.invalidRequest("Not Found: Session has been terminated"),
|
||||
sessionID: sessionID
|
||||
)
|
||||
}
|
||||
|
||||
switch request.method.uppercased() {
|
||||
case "POST":
|
||||
return handlePost(request)
|
||||
case "GET":
|
||||
return handleGet(request)
|
||||
case "DELETE":
|
||||
return handleDelete(request)
|
||||
default:
|
||||
return .error(
|
||||
statusCode: 405,
|
||||
.invalidRequest("Method Not Allowed"),
|
||||
sessionID: sessionID
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - POST Handler
|
||||
|
||||
private func handlePost(_ request: HTTPRequest) -> HTTPResponse {
|
||||
// Parse body first so we can determine if it's an initialization request
|
||||
guard let body = request.body, !body.isEmpty else {
|
||||
return .error(
|
||||
statusCode: 400,
|
||||
.parseError("Empty request body"),
|
||||
sessionID: sessionID
|
||||
)
|
||||
}
|
||||
|
||||
guard let messageKind = JSONRPCMessageKind(data: body) else {
|
||||
return .error(
|
||||
statusCode: 400,
|
||||
.parseError("Invalid JSON-RPC message"),
|
||||
sessionID: sessionID
|
||||
)
|
||||
}
|
||||
|
||||
// Build validation context
|
||||
let context = HTTPValidationContext(
|
||||
httpMethod: "POST",
|
||||
sessionID: sessionID,
|
||||
isInitializationRequest: messageKind.isInitializeRequest,
|
||||
supportedProtocolVersions: Version.supported
|
||||
)
|
||||
|
||||
// Run validation pipeline
|
||||
if let errorResponse = validationPipeline.validate(request, context: context) {
|
||||
return errorResponse
|
||||
}
|
||||
|
||||
// Handle initialization request specially
|
||||
if messageKind.isInitializeRequest {
|
||||
return handleInitializationRequest(body, request: request)
|
||||
}
|
||||
|
||||
// Handle by message type
|
||||
switch messageKind {
|
||||
case .notification, .response:
|
||||
// Yield to server and return 202 Accepted
|
||||
incomingContinuation.yield(body)
|
||||
return .accepted(headers: sessionHeaders())
|
||||
|
||||
case .request(let id, _):
|
||||
return handleJSONRPCRequest(body, requestID: id, request: request)
|
||||
}
|
||||
}
|
||||
|
||||
private func handleInitializationRequest(_ body: Data, request: HTTPRequest) -> HTTPResponse {
|
||||
// Generate session ID
|
||||
let newSessionID = sessionIDGenerator.generateSessionID()
|
||||
|
||||
// Validate session ID contains only visible ASCII (0x21-0x7E)
|
||||
guard isValidSessionID(newSessionID) else {
|
||||
logger.error("Generated session ID contains invalid characters")
|
||||
return .error(
|
||||
statusCode: 500,
|
||||
.internalError("Internal error: Invalid session ID generated")
|
||||
)
|
||||
}
|
||||
|
||||
self.sessionID = newSessionID
|
||||
logger.info("Session initialized", metadata: ["sessionID": "\(newSessionID)"])
|
||||
|
||||
// Extract request ID for routing the response
|
||||
guard case .request(let requestID, _) = JSONRPCMessageKind(data: body) else {
|
||||
return .error(
|
||||
statusCode: 400,
|
||||
.parseError("Invalid initialize request"),
|
||||
sessionID: newSessionID
|
||||
)
|
||||
}
|
||||
|
||||
// For the initialize request, use SSE streaming like any other request
|
||||
return handleJSONRPCRequest(body, requestID: requestID, request: request)
|
||||
}
|
||||
|
||||
private func handleJSONRPCRequest(_ body: Data, requestID: String, request: HTTPRequest) -> HTTPResponse {
|
||||
// Create SSE stream for this request
|
||||
let (sseStream, sseContinuation) = AsyncThrowingStream<Data, Swift.Error>.makeStream()
|
||||
requestSSEContinuations[requestID] = sseContinuation
|
||||
|
||||
// Extract protocol version for priming event decision
|
||||
let protocolVersion = extractProtocolVersion(from: body, request: request)
|
||||
|
||||
// Send priming event for resumability
|
||||
sendPrimingEvent(
|
||||
streamID: requestID,
|
||||
continuation: sseContinuation,
|
||||
protocolVersion: protocolVersion
|
||||
)
|
||||
|
||||
// Yield the incoming message to the server
|
||||
incomingContinuation.yield(body)
|
||||
|
||||
// Build response headers
|
||||
var headers = sessionHeaders()
|
||||
headers[HTTPHeaderName.contentType] = ContentType.sse
|
||||
headers[HTTPHeaderName.cacheControl] = "no-cache, no-transform"
|
||||
headers[HTTPHeaderName.connection] = "keep-alive"
|
||||
|
||||
return .stream(sseStream, headers: headers)
|
||||
}
|
||||
|
||||
// MARK: - GET Handler
|
||||
|
||||
private func handleGet(_ request: HTTPRequest) -> HTTPResponse {
|
||||
// Build validation context (GET is never an initialization request)
|
||||
let context = HTTPValidationContext(
|
||||
httpMethod: "GET",
|
||||
sessionID: sessionID,
|
||||
isInitializationRequest: false,
|
||||
supportedProtocolVersions: Version.supported
|
||||
)
|
||||
|
||||
// Run validation pipeline
|
||||
if let errorResponse = validationPipeline.validate(request, context: context) {
|
||||
return errorResponse
|
||||
}
|
||||
|
||||
// Handle resumability: check for Last-Event-ID header
|
||||
if let lastEventID = request.header(HTTPHeaderName.lastEventID) {
|
||||
return handleResumeRequest(lastEventID: lastEventID, request: request)
|
||||
}
|
||||
|
||||
// Only one standalone GET stream per session
|
||||
guard standaloneSSEContinuation == nil else {
|
||||
return .error(
|
||||
statusCode: 409,
|
||||
.invalidRequest("Conflict: Only one SSE stream is allowed per session"),
|
||||
sessionID: sessionID
|
||||
)
|
||||
}
|
||||
|
||||
// Create standalone SSE stream
|
||||
let (sseStream, sseContinuation) = AsyncThrowingStream<Data, Swift.Error>.makeStream()
|
||||
standaloneSSEContinuation = sseContinuation
|
||||
|
||||
// Extract protocol version for priming event
|
||||
let protocolVersion = request.header(HTTPHeaderName.protocolVersion) ?? Version.latest
|
||||
|
||||
// Send priming event
|
||||
sendPrimingEvent(
|
||||
streamID: standaloneStreamID,
|
||||
continuation: sseContinuation,
|
||||
protocolVersion: protocolVersion
|
||||
)
|
||||
|
||||
// Build response headers
|
||||
var headers = sessionHeaders()
|
||||
headers[HTTPHeaderName.contentType] = ContentType.sse
|
||||
headers[HTTPHeaderName.cacheControl] = "no-cache, no-transform"
|
||||
headers[HTTPHeaderName.connection] = "keep-alive"
|
||||
|
||||
return .stream(sseStream, headers: headers)
|
||||
}
|
||||
|
||||
// MARK: - DELETE Handler
|
||||
|
||||
private func handleDelete(_ request: HTTPRequest) -> HTTPResponse {
|
||||
// Validate session
|
||||
let context = HTTPValidationContext(
|
||||
httpMethod: "DELETE",
|
||||
sessionID: sessionID,
|
||||
isInitializationRequest: false,
|
||||
supportedProtocolVersions: Version.supported
|
||||
)
|
||||
|
||||
// Only run session validation for DELETE (not all validators)
|
||||
let sessionValidator = SessionValidator()
|
||||
if let errorResponse = sessionValidator.validate(request, context: context) {
|
||||
return errorResponse
|
||||
}
|
||||
|
||||
terminate()
|
||||
|
||||
return .ok(headers: sessionHeaders())
|
||||
}
|
||||
|
||||
// MARK: - Message Routing
|
||||
|
||||
/// Routes a message to a specific request's SSE stream without closing it.
|
||||
/// Used for server-initiated messages during request handling.
|
||||
private func routeToRequestStream(_ data: Data, requestID: String) {
|
||||
let eventID = storeEvent(streamID: requestID, message: data)
|
||||
|
||||
guard let continuation = requestSSEContinuations[requestID] else {
|
||||
logger.debug(
|
||||
"No active stream for request, message stored for replay",
|
||||
metadata: ["requestID": "\(requestID)"]
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Format as SSE and yield (but don't close the stream)
|
||||
let sseEvent = SSEEvent.message(data: data, id: eventID)
|
||||
continuation.yield(sseEvent.formatted())
|
||||
}
|
||||
|
||||
/// Routes a response to a specific request's SSE stream and closes it.
|
||||
/// Used for final responses to client requests.
|
||||
private func routeResponse(_ data: Data, requestID: String) {
|
||||
routeToRequestStream(data, requestID: requestID)
|
||||
|
||||
// Response means the request is complete — close the stream
|
||||
if let continuation = requestSSEContinuations[requestID] {
|
||||
continuation.finish()
|
||||
requestSSEContinuations.removeValue(forKey: requestID)
|
||||
}
|
||||
}
|
||||
|
||||
private func routeServerInitiatedMessage(_ data: Data) {
|
||||
let eventID = storeEvent(streamID: standaloneStreamID, message: data)
|
||||
|
||||
guard let continuation = standaloneSSEContinuation else {
|
||||
logger.debug("No standalone GET stream connected, message stored for replay")
|
||||
return
|
||||
}
|
||||
|
||||
let sseEvent = SSEEvent.message(data: data, id: eventID)
|
||||
continuation.yield(sseEvent.formatted())
|
||||
}
|
||||
|
||||
// MARK: - Resumability
|
||||
|
||||
private func handleResumeRequest(lastEventID: String, request: HTTPRequest) -> HTTPResponse {
|
||||
guard let replay = replayEventsAfter(lastEventID) else {
|
||||
return .error(
|
||||
statusCode: 400,
|
||||
.invalidRequest("Invalid Last-Event-ID"),
|
||||
sessionID: sessionID
|
||||
)
|
||||
}
|
||||
|
||||
let (sseStream, sseContinuation) = AsyncThrowingStream<Data, Swift.Error>.makeStream()
|
||||
|
||||
// Replay stored events
|
||||
for (eventID, message) in replay.events {
|
||||
let sseEvent = SSEEvent.message(data: message, id: eventID)
|
||||
sseContinuation.yield(sseEvent.formatted())
|
||||
}
|
||||
|
||||
// Re-register the stream for future messages
|
||||
if replay.streamID == standaloneStreamID {
|
||||
standaloneSSEContinuation = sseContinuation
|
||||
} else {
|
||||
requestSSEContinuations[replay.streamID] = sseContinuation
|
||||
}
|
||||
|
||||
// Send a new priming event so the client can resume again if disconnected
|
||||
let protocolVersion = request.header(HTTPHeaderName.protocolVersion) ?? Version.latest
|
||||
sendPrimingEvent(
|
||||
streamID: replay.streamID,
|
||||
continuation: sseContinuation,
|
||||
protocolVersion: protocolVersion
|
||||
)
|
||||
|
||||
var headers = sessionHeaders()
|
||||
headers[HTTPHeaderName.contentType] = ContentType.sse
|
||||
headers[HTTPHeaderName.cacheControl] = "no-cache, no-transform"
|
||||
headers[HTTPHeaderName.connection] = "keep-alive"
|
||||
|
||||
return .stream(sseStream, headers: headers)
|
||||
}
|
||||
|
||||
// MARK: - Internal Event Store
|
||||
|
||||
private func storeEvent(streamID: String, message: Data?) -> String {
|
||||
eventCounter += 1
|
||||
let eventID = "\(streamID)_\(eventCounter)"
|
||||
storedEvents.append(StoredEvent(streamID: streamID, eventID: eventID, message: message))
|
||||
return eventID
|
||||
}
|
||||
|
||||
private func replayEventsAfter(_ lastEventID: String) -> (streamID: String, events: [(eventID: String, message: Data)])? {
|
||||
guard let index = storedEvents.firstIndex(where: { $0.eventID == lastEventID }) else {
|
||||
return nil
|
||||
}
|
||||
let streamID = storedEvents[index].streamID
|
||||
let eventsToReplay = storedEvents[(index + 1)...]
|
||||
.filter { $0.streamID == streamID && $0.message != nil }
|
||||
.map { (eventID: $0.eventID, message: $0.message!) }
|
||||
return (streamID, eventsToReplay)
|
||||
}
|
||||
|
||||
// MARK: - SSE Helpers
|
||||
|
||||
private func sendPrimingEvent(
|
||||
streamID: String,
|
||||
continuation: AsyncThrowingStream<Data, Swift.Error>.Continuation,
|
||||
protocolVersion: String
|
||||
) {
|
||||
// Priming events with empty data are only safe for clients >= 2025-11-25
|
||||
guard protocolVersion >= "2025-11-25" else { return }
|
||||
|
||||
let primingEventID = storeEvent(streamID: streamID, message: nil)
|
||||
let primingEvent = SSEEvent.priming(id: primingEventID, retry: retryInterval)
|
||||
continuation.yield(primingEvent.formatted())
|
||||
}
|
||||
|
||||
// MARK: - Session Helpers
|
||||
|
||||
private func sessionHeaders() -> [String: String] {
|
||||
var headers: [String: String] = [:]
|
||||
if let sessionID {
|
||||
headers[HTTPHeaderName.sessionID] = sessionID
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
private func isValidSessionID(_ id: String) -> Bool {
|
||||
guard !id.isEmpty else { return false }
|
||||
return id.utf8.allSatisfy { $0 >= 0x21 && $0 <= 0x7E }
|
||||
}
|
||||
|
||||
private func extractProtocolVersion(from body: Data, request: HTTPRequest) -> String {
|
||||
// For initialize requests, extract from the request body params
|
||||
if let json = try? JSONSerialization.jsonObject(with: body) as? [String: Any],
|
||||
let method = json["method"] as? String, method == "initialize",
|
||||
let params = json["params"] as? [String: Any],
|
||||
let version = params["protocolVersion"] as? String
|
||||
{
|
||||
return version
|
||||
}
|
||||
// For other requests, use the header
|
||||
return request.header(HTTPHeaderName.protocolVersion) ?? Version.latest
|
||||
}
|
||||
|
||||
// MARK: - Termination
|
||||
|
||||
/// Terminates the session, closing all active streams.
|
||||
/// After termination, all requests receive 404 Not Found.
|
||||
private func terminate() {
|
||||
guard !terminated else { return }
|
||||
terminated = true
|
||||
|
||||
logger.info("Terminating session", metadata: ["sessionID": "\(sessionID ?? "none")"])
|
||||
|
||||
// Close all request SSE streams
|
||||
for (_, continuation) in requestSSEContinuations {
|
||||
continuation.finish()
|
||||
}
|
||||
requestSSEContinuations.removeAll()
|
||||
|
||||
// Close standalone GET stream
|
||||
standaloneSSEContinuation?.finish()
|
||||
standaloneSSEContinuation = nil
|
||||
|
||||
// Clear stored events
|
||||
storedEvents.removeAll()
|
||||
|
||||
// Close incoming stream
|
||||
incomingContinuation.finish()
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,251 @@
|
|||
import Foundation
|
||||
import Logging
|
||||
|
||||
/// A stateless HTTP server transport that returns single JSON responses.
|
||||
///
|
||||
/// This transport implements a minimal subset of the MCP Streamable HTTP specification:
|
||||
/// - No session management (no `Mcp-Session-Id` header)
|
||||
/// - POST requests receive direct JSON responses (no SSE streaming)
|
||||
/// - GET and DELETE requests return 405 Method Not Allowed
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// ```swift
|
||||
/// let transport = StatelessHTTPServerTransport()
|
||||
///
|
||||
/// // Start the MCP server with this transport
|
||||
/// try await server.start(transport: transport)
|
||||
///
|
||||
/// // In your HTTP framework handler:
|
||||
/// let response = await transport.handleRequest(httpRequest)
|
||||
/// // Convert response to your framework's response type and return it
|
||||
/// ```
|
||||
///
|
||||
/// ## When to Use
|
||||
///
|
||||
/// Use this transport when:
|
||||
/// - You don't need server-initiated messages (no GET SSE stream)
|
||||
/// - You want simple request-response semantics
|
||||
/// - Session management is handled externally or not needed
|
||||
///
|
||||
/// For full streaming and session support, use ``StatefulHTTPServerTransport`` instead.
|
||||
public actor StatelessHTTPServerTransport: Transport {
|
||||
public nonisolated let logger: Logger
|
||||
|
||||
// MARK: - Dependencies
|
||||
|
||||
private let validationPipeline: any HTTPRequestValidationPipeline
|
||||
|
||||
// MARK: - State
|
||||
|
||||
private var terminated = false
|
||||
private var started = false
|
||||
|
||||
// MARK: - Incoming message stream (client → server)
|
||||
|
||||
private let incomingStream: AsyncThrowingStream<Data, Swift.Error>
|
||||
private let incomingContinuation: AsyncThrowingStream<Data, Swift.Error>.Continuation
|
||||
|
||||
// MARK: - Response waiters
|
||||
|
||||
/// Maps request ID → continuation waiting for the server's response.
|
||||
/// When the server calls `send()` with a response, the matching continuation is resumed.
|
||||
private var responseWaiters: [String: CheckedContinuation<Data, any Error>] = [:]
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a new stateless HTTP server transport.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - validationPipeline: Custom validation pipeline. If `nil`, uses sensible defaults:
|
||||
/// origin validation (localhost), Accept header (JSON only), Content-Type,
|
||||
/// and protocol version validation.
|
||||
/// - logger: Optional logger. If `nil`, a no-op logger is used.
|
||||
public init(
|
||||
validationPipeline: (any HTTPRequestValidationPipeline)? = nil,
|
||||
logger: Logger? = nil
|
||||
) {
|
||||
self.validationPipeline = validationPipeline ?? StandardValidationPipeline(validators: [
|
||||
OriginValidator.localhost(),
|
||||
AcceptHeaderValidator(mode: .jsonOnly),
|
||||
ContentTypeValidator(),
|
||||
ProtocolVersionValidator(),
|
||||
])
|
||||
self.logger = logger ?? Logger(
|
||||
label: "mcp.transport.http.server.stateless",
|
||||
factory: { _ in SwiftLogNoOpLogHandler() }
|
||||
)
|
||||
|
||||
let (stream, continuation) = AsyncThrowingStream<Data, Swift.Error>.makeStream()
|
||||
self.incomingStream = stream
|
||||
self.incomingContinuation = continuation
|
||||
}
|
||||
|
||||
// MARK: - Transport Conformance
|
||||
|
||||
public func connect() async throws {
|
||||
guard !started else {
|
||||
throw MCPError.internalError("Transport already started")
|
||||
}
|
||||
started = true
|
||||
logger.debug("Stateless HTTP server transport started")
|
||||
}
|
||||
|
||||
public func disconnect() async {
|
||||
await terminate()
|
||||
}
|
||||
|
||||
/// Routes outgoing server messages to the appropriate waiting HTTP handler.
|
||||
///
|
||||
/// - Responses are matched by JSON-RPC ID and delivered to the waiting `handleRequest` call.
|
||||
/// - Notifications and server-initiated requests are logged and dropped
|
||||
/// (no streaming channel available in stateless mode).
|
||||
public func send(_ data: Data) async throws {
|
||||
guard !terminated else {
|
||||
throw MCPError.connectionClosed
|
||||
}
|
||||
|
||||
guard let kind = JSONRPCMessageKind(data: data) else {
|
||||
logger.warning("Could not classify outgoing message for routing")
|
||||
return
|
||||
}
|
||||
|
||||
switch kind {
|
||||
case .response(let id):
|
||||
guard let continuation = responseWaiters.removeValue(forKey: id) else {
|
||||
logger.debug(
|
||||
"No waiter for response, may have timed out",
|
||||
metadata: ["requestID": "\(id)"]
|
||||
)
|
||||
return
|
||||
}
|
||||
continuation.resume(returning: data)
|
||||
|
||||
case .notification(let method):
|
||||
logger.debug(
|
||||
"Server-initiated notification dropped in stateless mode (no GET SSE stream)",
|
||||
metadata: ["method": "\(method)"]
|
||||
)
|
||||
|
||||
case .request(_, let method):
|
||||
logger.debug(
|
||||
"Server-initiated request dropped in stateless mode (no GET SSE stream)",
|
||||
metadata: ["method": "\(method)"]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
public func receive() -> AsyncThrowingStream<Data, Swift.Error> {
|
||||
incomingStream
|
||||
}
|
||||
|
||||
// MARK: - HTTP Request Handler
|
||||
|
||||
/// Handles an incoming HTTP request from the framework adapter.
|
||||
///
|
||||
/// Only POST is supported:
|
||||
/// - **POST**: JSON-RPC messages (requests, notifications)
|
||||
/// - **GET**: 405 Method Not Allowed
|
||||
/// - **DELETE**: 405 Method Not Allowed
|
||||
/// - Others: 405 Method Not Allowed
|
||||
public func handleRequest(_ request: HTTPRequest) async -> HTTPResponse {
|
||||
if terminated {
|
||||
return .error(
|
||||
statusCode: 404,
|
||||
.invalidRequest("Not Found: Transport has been terminated")
|
||||
)
|
||||
}
|
||||
|
||||
switch request.method.uppercased() {
|
||||
case "POST":
|
||||
return await handlePost(request)
|
||||
default:
|
||||
return .error(
|
||||
statusCode: 405,
|
||||
.invalidRequest("Method Not Allowed")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - POST Handler
|
||||
|
||||
private func handlePost(_ request: HTTPRequest) async -> HTTPResponse {
|
||||
// Parse body first to determine message type
|
||||
guard let body = request.body, !body.isEmpty else {
|
||||
return .error(
|
||||
statusCode: 400,
|
||||
.parseError("Empty request body")
|
||||
)
|
||||
}
|
||||
|
||||
guard let messageKind = JSONRPCMessageKind(data: body) else {
|
||||
return .error(
|
||||
statusCode: 400,
|
||||
.parseError("Invalid JSON-RPC message")
|
||||
)
|
||||
}
|
||||
|
||||
// Build validation context
|
||||
let context = HTTPValidationContext(
|
||||
httpMethod: "POST",
|
||||
sessionID: nil,
|
||||
isInitializationRequest: messageKind.isInitializeRequest,
|
||||
supportedProtocolVersions: Version.supported
|
||||
)
|
||||
|
||||
// Run validation pipeline
|
||||
if let errorResponse = validationPipeline.validate(request, context: context) {
|
||||
return errorResponse
|
||||
}
|
||||
|
||||
// Handle by message type
|
||||
switch messageKind {
|
||||
case .notification, .response:
|
||||
// Yield to server and return 202 Accepted
|
||||
incomingContinuation.yield(body)
|
||||
return .accepted()
|
||||
|
||||
case .request(let id, _):
|
||||
return await handleJSONRPCRequest(body, requestID: id)
|
||||
}
|
||||
}
|
||||
|
||||
private func handleJSONRPCRequest(_ body: Data, requestID: String) async -> HTTPResponse {
|
||||
// Yield the incoming message to the server
|
||||
incomingContinuation.yield(body)
|
||||
|
||||
// Wait for the server to process and send a response
|
||||
let responseData: Data
|
||||
do {
|
||||
responseData = try await withCheckedThrowingContinuation { continuation in
|
||||
responseWaiters[requestID] = continuation
|
||||
}
|
||||
} catch {
|
||||
return .error(
|
||||
statusCode: 500,
|
||||
.internalError("Error processing request: \(error.localizedDescription)")
|
||||
)
|
||||
}
|
||||
|
||||
return .data(responseData, headers: [HTTPHeaderName.contentType: ContentType.json])
|
||||
}
|
||||
|
||||
// MARK: - Termination
|
||||
|
||||
private func terminate() async {
|
||||
guard !terminated else { return }
|
||||
terminated = true
|
||||
|
||||
logger.debug("Stateless HTTP server transport terminated")
|
||||
|
||||
// Cancel all waiting continuations
|
||||
for (id, continuation) in responseWaiters {
|
||||
continuation.resume(throwing: MCPError.connectionClosed)
|
||||
logger.debug("Cancelled waiter for request", metadata: ["requestID": "\(id)"])
|
||||
}
|
||||
responseWaiters.removeAll()
|
||||
|
||||
// Close incoming stream
|
||||
incomingContinuation.finish()
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue