@@ -2571,6 +2571,111 @@ import Testing
25712571 override func stopLoading ( ) { }
25722572 }
25732573
2574+ /// Answers each request with an `application/json` body in chunks of at
2575+ /// most 1 MiB, as the script of its session says, and records the bytes
2576+ /// delivered.
2577+ private final class LongJSONBodyURLProtocol : URLProtocol {
2578+ struct Script : Sendable {
2579+ var length : Int
2580+ var contentLength : Int ? = nil
2581+ /// Once more bytes than this went out (-1: before the first
2582+ /// chunk), the body waits up to 30 s for the loading to stop
2583+ /// before it sends the rest or ends.
2584+ var pauseAfter : Int ? = nil
2585+ }
2586+
2587+ /// `@unchecked Sendable`: `lock` guards its state.
2588+ final class Log : @unchecked Sendable {
2589+ private let lock = NSLock ( )
2590+ private var bytes = 0
2591+ private var stopped = false
2592+
2593+ func delivered ( _ count : Int ) { lock . withLock { bytes += count } }
2594+ func stop ( ) { lock . withLock { stopped = true } }
2595+
2596+ /// The bytes delivered, once the loading stopped or all chunks went out.
2597+ func deliveredWhenStopped ( ) async throws -> Int {
2598+ let deadline = ContinuousClock . now + . seconds ( 30 )
2599+ while ! lock . withLock ( { stopped } ) && ContinuousClock . now < deadline {
2600+ try await Task . sleep ( for : . milliseconds ( 5 ) )
2601+ }
2602+ return lock . withLock { bytes }
2603+ }
2604+ }
2605+
2606+ static let chunk = 1 << 20
2607+ private static let keyHeader = " X-Long-Body-Key "
2608+ private static let lock = NSLock ( )
2609+ /// `nonisolated(unsafe)`: `lock` guards it.
2610+ nonisolated ( unsafe) private static var scripts : [ String : ( Script , Log ) ] = [ : ]
2611+
2612+ /// A configuration whose requests get `script`, and the log of their bodies.
2613+ static func configuration ( _ script : Script ) -> ( URLSessionConfiguration , Log ) {
2614+ let key = UUID ( ) . uuidString
2615+ let log = Log ( )
2616+ lock . withLock { scripts [ key ] = ( script , log ) }
2617+ let configuration = URLSessionConfiguration . ephemeral
2618+ configuration . protocolClasses = [ LongJSONBodyURLProtocol . self ]
2619+ configuration . httpAdditionalHeaders = [ keyHeader : key ]
2620+ return ( configuration , log )
2621+ }
2622+
2623+ override class func canInit ( with request : URLRequest ) -> Bool { true }
2624+ override class func canonicalRequest ( for request : URLRequest ) -> URLRequest { request }
2625+
2626+ /// swift-corelibs-foundation traps on a callback after `stopLoading()`.
2627+ private let stateLock = NSLock ( )
2628+ private var stopped = false
2629+ private var log : Log ?
2630+ private var isStopped : Bool { stateLock . withLock { stopped } }
2631+
2632+ override func startLoading ( ) {
2633+ let key = request . value ( forHTTPHeaderField : Self . keyHeader ) ?? " "
2634+ guard let url = request . url , let ( script , log ) = Self . lock . withLock ( { Self . scripts [ key ] } ) else {
2635+ client ? . urlProtocol ( self , didFailWithError : URLError ( . unsupportedURL ) )
2636+ return
2637+ }
2638+ stateLock . withLock { self . log = log }
2639+ var headers = [ " Content-Type " : " application/json " ]
2640+ if let contentLength = script . contentLength { headers [ " Content-Length " ] = String ( contentLength ) }
2641+ let response = HTTPURLResponse ( url : url , statusCode : 200 , httpVersion : " HTTP/1.1 " , headerFields : headers ) !
2642+ client ? . urlProtocol ( self , didReceive : response , cacheStoragePolicy : . notAllowed )
2643+ let loader = SendableURLProtocol ( self )
2644+ DispatchQueue . global ( ) . async { loader . value . stream ( script ) }
2645+ }
2646+
2647+ private func stream ( _ script : Script ) {
2648+ var sent = 0
2649+ var paused = false
2650+ while true {
2651+ guard ! isStopped else { return }
2652+ if let pauseAfter = script . pauseAfter , sent > pauseAfter , ! paused {
2653+ paused = true
2654+ let deadline = Date ( ) . addingTimeInterval ( 30 )
2655+ while ! isStopped && Date ( ) < deadline { Thread . sleep ( forTimeInterval : 0.005 ) }
2656+ guard ! isStopped else { return }
2657+ }
2658+ guard sent < script . length else { break }
2659+ let count = min ( Self . chunk , script . length - sent )
2660+ // Counted first, so the count is in place once the client has the bytes.
2661+ stateLock . withLock { log } ? . delivered ( count )
2662+ sent += count
2663+ client ? . urlProtocol ( self , didLoad : Data ( repeating : 0x20 , count : count ) )
2664+ }
2665+ guard ! isStopped else { return }
2666+ stateLock . withLock { log } ? . stop ( )
2667+ client ? . urlProtocolDidFinishLoading ( self )
2668+ }
2669+
2670+ override func stopLoading ( ) {
2671+ let log = stateLock . withLock { ( ) -> Log ? in
2672+ stopped = true
2673+ return self . log
2674+ }
2675+ log ? . stop ( )
2676+ }
2677+ }
2678+
25742679 @ Suite ( " HTTP client transport sessions " )
25752680 struct HTTPClientTransportSessionTests {
25762681 let endpoint = URL ( string : " http://127.0.0.1:9/mcp " ) !
@@ -2695,6 +2800,82 @@ import Testing
26952800 #expect ( delivered . isEmpty )
26962801 }
26972802
2803+ @ Test ( " A JSON response body over 16 MiB fails the request and is not read further " , . timeLimit ( . minutes ( 1 ) ) )
2804+ func oversizedJSONBody ( ) async throws {
2805+ let limit = ServerSentEventParser . maxEventLength
2806+ let chunk = LongJSONBodyURLProtocol . chunk
2807+ // The body pauses past the limit until the client stops it, so the
2808+ // bytes delivered show where the client stopped reading.
2809+ let ( configuration , log ) = LongJSONBodyURLProtocol . configuration ( . init ( length : 40 * chunk , pauseAfter : limit ) )
2810+ let transport = HTTPClientTransport ( endpoint : endpoint , configuration : configuration , streaming : false )
2811+ try await transport . connect ( )
2812+ await #expect {
2813+ try await transport . send ( request )
2814+ } throws : { error in
2815+ ( error as? MCPError ) == . internalError ( " JSON response body longer than 16 MiB " )
2816+ }
2817+ let delivered = try await log . deliveredWhenStopped ( )
2818+ #expect ( delivered == limit + chunk , " \( delivered ) bytes were delivered " )
2819+ await transport . disconnect ( )
2820+ var messages = 0
2821+ for try await _ in await transport . receive ( ) { messages += 1 }
2822+ #expect ( messages == 0 )
2823+ }
2824+
2825+ @ Test ( " A JSON response with a Content-Length over 16 MiB fails before its body is read " , . timeLimit ( . minutes ( 1 ) ) )
2826+ func oversizedJSONContentLength ( ) async throws {
2827+ let chunk = LongJSONBodyURLProtocol . chunk
2828+ // The body waits before its first chunk until the client stops it.
2829+ let ( configuration , log ) = LongJSONBodyURLProtocol . configuration (
2830+ . init ( length : 40 * chunk , contentLength : 40 * chunk , pauseAfter : - 1 ) )
2831+ let transport = HTTPClientTransport ( endpoint : endpoint , configuration : configuration , streaming : false )
2832+ try await transport . connect ( )
2833+ await #expect {
2834+ try await transport . send ( request )
2835+ } throws : { error in
2836+ ( error as? MCPError ) == . internalError ( " JSON response body longer than 16 MiB " )
2837+ }
2838+ let delivered = try await log . deliveredWhenStopped ( )
2839+ #expect ( delivered == 0 , " \( delivered ) bytes were delivered " )
2840+ await transport . disconnect ( )
2841+ }
2842+
2843+ @ Test ( " A JSON response body one byte over 16 MiB fails the request " , . timeLimit ( . minutes ( 1 ) ) )
2844+ func jsonBodyOneByteOverLimit ( ) async throws {
2845+ let limit = ServerSentEventParser . maxEventLength
2846+ // The body stays open after its last byte until the client stops it.
2847+ let ( configuration , log ) = LongJSONBodyURLProtocol . configuration ( . init ( length : limit + 1 , pauseAfter : limit ) )
2848+ let transport = HTTPClientTransport ( endpoint : endpoint , configuration : configuration , streaming : false )
2849+ try await transport . connect ( )
2850+ await #expect {
2851+ try await transport . send ( request )
2852+ } throws : { error in
2853+ ( error as? MCPError ) == . internalError ( " JSON response body longer than 16 MiB " )
2854+ }
2855+ let delivered = try await log . deliveredWhenStopped ( )
2856+ #expect ( delivered == limit + 1 , " \( delivered ) bytes were delivered " )
2857+ await transport . disconnect ( )
2858+ var messages = 0
2859+ for try await _ in await transport . receive ( ) { messages += 1 }
2860+ #expect ( messages == 0 )
2861+ }
2862+
2863+ @ Test ( " A JSON response body of 16 MiB is delivered whole " , . timeLimit ( . minutes ( 1 ) ) )
2864+ func jsonBodyAtLimit ( ) async throws {
2865+ let limit = ServerSentEventParser . maxEventLength
2866+ let ( configuration , _) = LongJSONBodyURLProtocol . configuration ( . init ( length : limit , contentLength : limit ) )
2867+ let transport = HTTPClientTransport ( endpoint : endpoint , configuration : configuration , streaming : false )
2868+ try await transport . connect ( )
2869+ try await transport . send ( request )
2870+ var delivered : [ Data ] = [ ]
2871+ for try await data in await transport . receive ( ) {
2872+ delivered . append ( data )
2873+ break
2874+ }
2875+ #expect ( delivered == [ Data ( repeating : 0x20 , count : limit ) ] )
2876+ await transport . disconnect ( )
2877+ }
2878+
26982879 #if canImport( FoundationNetworking )
26992880 @ Test ( " A second response for one request fails it instead of joining the bodies " )
27002881 func secondResponse ( ) async throws {
0 commit comments