diff --git "a/swift/swift-sdk_function_bench.jsonl" "b/swift/swift-sdk_function_bench.jsonl" new file mode 100644--- /dev/null +++ "b/swift/swift-sdk_function_bench.jsonl" @@ -0,0 +1,5 @@ +{"repo_name": "swift-sdk", "file_name": "/swift-sdk/Sources/MCP/Base/Transports/StdioTransport.swift", "inference_info": {"prefix_code": "import Logging\n\nimport struct Foundation.Data\n\n#if canImport(System)\n import System\n#else\n @preconcurrency import SystemPackage\n#endif\n\n// Import for specific low-level operations not yet in Swift System\n#if canImport(Darwin)\n import Darwin.POSIX\n#elseif canImport(Glibc)\n import Glibc\n#endif\n\n#if canImport(Darwin) || canImport(Glibc)\n /// An implementation of the MCP stdio transport protocol.\n ///\n /// This transport implements the [stdio transport](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#stdio)\n /// specification from the Model Context Protocol.\n ///\n /// The stdio transport works by:\n /// - Reading JSON-RPC messages from standard input\n /// - Writing JSON-RPC messages to standard output\n /// - Using newline characters as message delimiters\n /// - Supporting non-blocking I/O operations\n ///\n /// This transport is the recommended option for most MCP applications due to its\n /// simplicity and broad platform support.\n ///\n /// - Important: This transport is available on Apple platforms and Linux distributions with glibc\n /// (Ubuntu, Debian, Fedora, CentOS, RHEL).\n ///\n /// ## Example Usage\n ///\n /// ```swift\n /// import MCP\n ///\n /// // Initialize the client\n /// let client = Client(name: \"MyApp\", version: \"1.0.0\")\n ///\n /// // Create a transport and connect\n /// let transport = StdioTransport()\n /// try await client.connect(transport: transport)\n /// ```\n public actor StdioTransport: Transport {\n private let input: FileDescriptor\n private let output: FileDescriptor\n /// Logger instance for transport-related events\n public nonisolated let logger: Logger\n\n private var isConnected = false\n private let messageStream: AsyncThrowingStream\n private let messageContinuation: AsyncThrowingStream.Continuation\n\n /// Creates a new stdio transport with the specified file descriptors\n ///\n /// - Parameters:\n /// - input: File descriptor for reading (defaults to standard input)\n /// - output: File descriptor for writing (defaults to standard output)\n /// - logger: Optional logger instance for transport events\n public init(\n input: FileDescriptor = FileDescriptor.standardInput,\n output: FileDescriptor = FileDescriptor.standardOutput,\n logger: Logger? = nil\n ) {\n self.input = input\n self.output = output\n self.logger =\n logger\n ?? Logger(\n label: \"mcp.transport.stdio\",\n factory: { _ in SwiftLogNoOpLogHandler() })\n\n // Create message stream\n var continuation: AsyncThrowingStream.Continuation!\n self.messageStream = AsyncThrowingStream { continuation = $0 }\n self.messageContinuation = continuation\n }\n\n /// Establishes connection with the transport\n ///\n /// This method configures the file descriptors for non-blocking I/O\n /// and starts the background message reading loop.\n ///\n /// - Throws: Error if the file descriptors cannot be configured\n public func connect() async throws {\n guard !isConnected else { return }\n\n // Set non-blocking mode\n try setNonBlocking(fileDescriptor: input)\n try setNonBlocking(fileDescriptor: output)\n\n isConnected = true\n logger.info(\"Transport connected successfully\")\n\n // Start reading loop in background\n Task {\n await readLoop()\n }\n }\n\n /// Configures a file descriptor for non-blocking I/O\n ///\n /// - Parameter fileDescriptor: The file descriptor to configure\n /// - Throws: Error if the operation fails\n ", "suffix_code": "\n\n /// Continuous loop that reads and processes incoming messages\n ///\n /// This method runs in the background while the transport is connected,\n /// parsing complete messages delimited by newlines and yielding them\n /// to the message stream.\n private func readLoop() async {\n let bufferSize = 4096\n var buffer = [UInt8](repeating: 0, count: bufferSize)\n var pendingData = Data()\n\n while isConnected && !Task.isCancelled {\n do {\n let bytesRead = try buffer.withUnsafeMutableBufferPointer { pointer in\n try input.read(into: UnsafeMutableRawBufferPointer(pointer))\n }\n\n if bytesRead == 0 {\n logger.notice(\"EOF received\")\n break\n }\n\n pendingData.append(Data(buffer[.. 0 {\n remaining = remaining.dropFirst(written)\n }\n } catch let error where MCPError.isResourceTemporarilyUnavailable(error) {\n try await Task.sleep(for: .milliseconds(10))\n continue\n } catch {\n throw MCPError.transportError(error)\n }\n }\n }\n\n /// Receives messages from the transport.\n ///\n /// Messages may be individual JSON-RPC requests, notifications, responses,\n /// or batches containing multiple requests/notifications encoded as JSON arrays.\n /// Each message is guaranteed to be a complete JSON object or array.\n ///\n /// - Returns: An AsyncThrowingStream of Data objects representing JSON-RPC messages\n public func receive() -> AsyncThrowingStream {\n return messageStream\n }\n }\n#endif\n", "middle_code": "private func setNonBlocking(fileDescriptor: FileDescriptor) throws {\n #if canImport(Darwin) || canImport(Glibc)\n let flags = fcntl(fileDescriptor.rawValue, F_GETFL)\n guard flags >= 0 else {\n throw MCPError.transportError(Errno(rawValue: CInt(errno)))\n }\n let result = fcntl(fileDescriptor.rawValue, F_SETFL, flags | O_NONBLOCK)\n guard result >= 0 else {\n throw MCPError.transportError(Errno(rawValue: CInt(errno)))\n }\n #else\n throw MCPError.internalError(\n \"Setting non-blocking mode not supported on this platform\")\n #endif\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "swift", "sub_task_type": null}, "context_code": [["/swift-sdk/Sources/MCP/Base/Transports/NetworkTransport.swift", "import Foundation\nimport Logging\n\n#if canImport(Network)\n import Network\n\n /// Protocol that abstracts the Network.NWConnection functionality needed for NetworkTransport\n @preconcurrency protocol NetworkConnectionProtocol {\n var state: NWConnection.State { get }\n var stateUpdateHandler: ((@Sendable (NWConnection.State) -> Void))? { get set }\n\n func start(queue: DispatchQueue)\n func cancel()\n func send(\n content: Data?, contentContext: NWConnection.ContentContext, isComplete: Bool,\n completion: NWConnection.SendCompletion)\n func receive(\n minimumIncompleteLength: Int, maximumLength: Int,\n completion: @escaping @Sendable (\n Data?, NWConnection.ContentContext?, Bool, NWError?\n ) -> Void)\n }\n\n /// Extension to conform NWConnection to internal NetworkConnectionProtocol\n extension NWConnection: NetworkConnectionProtocol {}\n\n /// An implementation of a custom MCP transport using Apple's Network framework.\n ///\n /// This transport allows MCP clients and servers to communicate over TCP/UDP connections\n /// using Apple's Network framework.\n ///\n /// - Important: This transport is available exclusively on Apple platforms\n /// (macOS, iOS, watchOS, tvOS, visionOS) as it depends on the Network framework.\n ///\n /// ## Example Usage\n ///\n /// ```swift\n /// import MCP\n /// import Network\n ///\n /// // Create a TCP connection to a server\n /// let connection = NWConnection(\n /// host: NWEndpoint.Host(\"localhost\"),\n /// port: NWEndpoint.Port(8080)!,\n /// using: .tcp\n /// )\n ///\n /// // Initialize the transport with the connection\n /// let transport = NetworkTransport(connection: connection)\n ///\n /// // For large messages (e.g., images), configure unlimited buffer size\n /// let largeBufferTransport = NetworkTransport(\n /// connection: connection,\n /// bufferConfig: .unlimited\n /// )\n ///\n /// // Use the transport with an MCP client\n /// let client = Client(name: \"MyApp\", version: \"1.0.0\")\n /// try await client.connect(transport: transport)\n /// ```\n public actor NetworkTransport: Transport {\n /// Represents a heartbeat message for connection health monitoring.\n public struct Heartbeat: RawRepresentable, Hashable, Sendable {\n /// Magic bytes used to identify a heartbeat message.\n private static let magicBytes: [UInt8] = [0xF0, 0x9F, 0x92, 0x93]\n\n /// The timestamp of when the heartbeat was created.\n public let timestamp: Date\n\n /// Creates a new heartbeat with the current timestamp.\n public init() {\n self.timestamp = Date()\n }\n\n /// Creates a heartbeat with a specific timestamp.\n ///\n /// - Parameter timestamp: The timestamp for the heartbeat.\n public init(timestamp: Date) {\n self.timestamp = timestamp\n }\n\n // MARK: - RawRepresentable\n\n public typealias RawValue = [UInt8]\n\n /// Creates a heartbeat from its raw representation.\n ///\n /// - Parameter rawValue: The raw bytes of the heartbeat message.\n /// - Returns: A heartbeat if the raw value is valid, nil otherwise.\n public init?(rawValue: [UInt8]) {\n // Check if the data has the correct format (magic bytes + timestamp)\n guard rawValue.count >= 12,\n rawValue.prefix(4).elementsEqual(Self.magicBytes)\n else {\n return nil\n }\n\n // Extract the timestamp\n let timestampData = Data(rawValue[4..<12])\n let timestamp = timestampData.withUnsafeBytes {\n $0.load(as: UInt64.self)\n }\n\n self.timestamp = Date(\n timeIntervalSinceReferenceDate: TimeInterval(timestamp) / 1000.0)\n }\n\n /// Converts the heartbeat to its raw representation.\n public var rawValue: [UInt8] {\n var result = Data(Self.magicBytes)\n\n // Add timestamp (milliseconds since reference date)\n let timestamp = UInt64(self.timestamp.timeIntervalSinceReferenceDate * 1000)\n withUnsafeBytes(of: timestamp) { buffer in\n result.append(contentsOf: buffer)\n }\n\n return Array(result)\n }\n\n /// Converts the heartbeat to Data.\n public var data: Data {\n return Data(self.rawValue)\n }\n\n /// Checks if the given data represents a heartbeat message.\n ///\n /// - Parameter data: The data to check.\n /// - Returns: true if the data is a heartbeat message, false otherwise.\n public static func isHeartbeat(_ data: Data) -> Bool {\n guard data.count >= 4 else {\n return false\n }\n\n return data.prefix(4).elementsEqual(Self.magicBytes)\n }\n\n /// Attempts to parse a heartbeat from the given data.\n ///\n /// - Parameter data: The data to parse.\n /// - Returns: A heartbeat if the data is valid, nil otherwise.\n public static func from(data: Data) -> Heartbeat? {\n guard data.count >= 12 else {\n return nil\n }\n\n return Heartbeat(rawValue: Array(data))\n }\n }\n\n /// Configuration for heartbeat behavior.\n public struct HeartbeatConfiguration: Hashable, Sendable {\n /// Whether heartbeats are enabled.\n public let enabled: Bool\n /// Interval between heartbeats in seconds.\n public let interval: TimeInterval\n\n /// Creates a new heartbeat configuration.\n ///\n /// - Parameters:\n /// - enabled: Whether heartbeats are enabled (default: true)\n /// - interval: Interval in seconds between heartbeats (default: 15.0)\n public init(enabled: Bool = true, interval: TimeInterval = 15.0) {\n self.enabled = enabled\n self.interval = interval\n }\n\n /// Default heartbeat configuration.\n public static let `default` = HeartbeatConfiguration()\n\n /// Configuration with heartbeats disabled.\n public static let disabled = HeartbeatConfiguration(enabled: false)\n }\n\n /// Configuration for connection retry behavior.\n public struct ReconnectionConfiguration: Hashable, Sendable {\n /// Whether the transport should attempt to reconnect on failure.\n public let enabled: Bool\n /// Maximum number of reconnection attempts.\n public let maxAttempts: Int\n /// Multiplier for exponential backoff on reconnect.\n public let backoffMultiplier: Double\n\n /// Creates a new reconnection configuration.\n ///\n /// - Parameters:\n /// - enabled: Whether reconnection should be attempted on failure (default: true)\n /// - maxAttempts: Maximum number of reconnection attempts (default: 5)\n /// - backoffMultiplier: Multiplier for exponential backoff on reconnect (default: 1.5)\n public init(\n enabled: Bool = true,\n maxAttempts: Int = 5,\n backoffMultiplier: Double = 1.5\n ) {\n self.enabled = enabled\n self.maxAttempts = maxAttempts\n self.backoffMultiplier = backoffMultiplier\n }\n\n /// Default reconnection configuration.\n public static let `default` = ReconnectionConfiguration()\n\n /// Configuration with reconnection disabled.\n public static let disabled = ReconnectionConfiguration(enabled: false)\n\n /// Calculates the backoff delay for a given attempt number.\n ///\n /// - Parameter attempt: The current attempt number (1-based)\n /// - Returns: The delay in seconds before the next attempt\n public func backoffDelay(for attempt: Int) -> TimeInterval {\n let baseDelay = 0.5 // 500ms\n return baseDelay * pow(backoffMultiplier, Double(attempt - 1))\n }\n }\n\n /// Configuration for buffer behavior.\n public struct BufferConfiguration: Hashable, Sendable {\n /// Maximum buffer size for receiving data chunks.\n /// Set to nil for unlimited (uses system default).\n public let maxReceiveBufferSize: Int?\n\n /// Creates a new buffer configuration.\n ///\n /// - Parameter maxReceiveBufferSize: Maximum buffer size in bytes (default: 10MB, nil for unlimited)\n public init(maxReceiveBufferSize: Int? = 10 * 1024 * 1024) {\n self.maxReceiveBufferSize = maxReceiveBufferSize\n }\n\n /// Default buffer configuration with 10MB limit.\n public static let `default` = BufferConfiguration()\n\n /// Configuration with no buffer size limit.\n public static let unlimited = BufferConfiguration(maxReceiveBufferSize: nil)\n }\n\n // State tracking\n private var isConnected = false\n private var isStopping = false\n private var reconnectAttempt = 0\n private var heartbeatTask: Task?\n private var lastHeartbeatTime: Date?\n private let messageStream: AsyncThrowingStream\n private let messageContinuation: AsyncThrowingStream.Continuation\n\n // Track connection state for continuations\n private var connectionContinuationResumed = false\n\n // Connection is marked nonisolated(unsafe) to allow access from closures\n private nonisolated(unsafe) var connection: NetworkConnectionProtocol\n\n /// Logger instance for transport-related events\n public nonisolated let logger: Logger\n\n // Configuration\n private let heartbeatConfig: HeartbeatConfiguration\n private let reconnectionConfig: ReconnectionConfiguration\n private let bufferConfig: BufferConfiguration\n\n /// Creates a new NetworkTransport with the specified NWConnection\n ///\n /// - Parameters:\n /// - connection: The NWConnection to use for communication\n /// - logger: Optional logger instance for transport events\n /// - reconnectionConfig: Configuration for reconnection behavior (default: .default)\n /// - heartbeatConfig: Configuration for heartbeat behavior (default: .default)\n /// - bufferConfig: Configuration for buffer behavior (default: .default)\n public init(\n connection: NWConnection,\n logger: Logger? = nil,\n heartbeatConfig: HeartbeatConfiguration = .default,\n reconnectionConfig: ReconnectionConfiguration = .default,\n bufferConfig: BufferConfiguration = .default\n ) {\n self.init(\n connection,\n logger: logger,\n heartbeatConfig: heartbeatConfig,\n reconnectionConfig: reconnectionConfig,\n bufferConfig: bufferConfig\n )\n }\n\n init(\n _ connection: NetworkConnectionProtocol,\n logger: Logger? = nil,\n heartbeatConfig: HeartbeatConfiguration = .default,\n reconnectionConfig: ReconnectionConfiguration = .default,\n bufferConfig: BufferConfiguration = .default\n ) {\n self.connection = connection\n self.logger =\n logger\n ?? Logger(\n label: \"mcp.transport.network\",\n factory: { _ in SwiftLogNoOpLogHandler() }\n )\n self.reconnectionConfig = reconnectionConfig\n self.heartbeatConfig = heartbeatConfig\n self.bufferConfig = bufferConfig\n\n // Create message stream\n var continuation: AsyncThrowingStream.Continuation!\n self.messageStream = AsyncThrowingStream { continuation = $0 }\n self.messageContinuation = continuation\n }\n\n /// Establishes connection with the transport\n ///\n /// This initiates the NWConnection and waits for it to become ready.\n /// Once the connection is established, it starts the message receiving loop.\n ///\n /// - Throws: Error if the connection fails to establish\n public func connect() async throws {\n guard !isConnected else { return }\n\n // Reset state for fresh connection\n isStopping = false\n reconnectAttempt = 0\n\n // Reset continuation state\n connectionContinuationResumed = false\n\n // Wait for connection to be ready\n try await withCheckedThrowingContinuation {\n [weak self] (continuation: CheckedContinuation) in\n guard let self = self else {\n continuation.resume(throwing: MCPError.internalError(\"Transport deallocated\"))\n return\n }\n\n connection.stateUpdateHandler = { [weak self] state in\n guard let self = self else { return }\n\n Task { @MainActor in\n switch state {\n case .ready:\n await self.handleConnectionReady(continuation: continuation)\n case .failed(let error):\n await self.handleConnectionFailed(\n error: error, continuation: continuation)\n case .cancelled:\n await self.handleConnectionCancelled(continuation: continuation)\n case .waiting(let error):\n self.logger.debug(\"Connection waiting: \\(error)\")\n case .preparing:\n self.logger.debug(\"Connection preparing...\")\n case .setup:\n self.logger.debug(\"Connection setup...\")\n @unknown default:\n self.logger.warning(\"Unknown connection state\")\n }\n }\n }\n\n connection.start(queue: .main)\n }\n }\n\n /// Handles when the connection reaches the ready state\n ///\n /// - Parameter continuation: The continuation to resume when connection is ready\n private func handleConnectionReady(continuation: CheckedContinuation)\n async\n {\n if !connectionContinuationResumed {\n connectionContinuationResumed = true\n isConnected = true\n\n // Reset reconnect attempt counter on successful connection\n reconnectAttempt = 0\n logger.info(\"Network transport connected successfully\")\n continuation.resume()\n\n // Start the receive loop after connection is established\n Task { await self.receiveLoop() }\n\n // Start heartbeat task if enabled\n if heartbeatConfig.enabled {\n startHeartbeat()\n }\n }\n }\n\n /// Starts a task to periodically send heartbeats to check connection health\n private func startHeartbeat() {\n // Cancel any existing heartbeat task\n heartbeatTask?.cancel()\n\n // Start a new heartbeat task\n heartbeatTask = Task { [weak self] in\n guard let self = self else { return }\n\n // Initial delay before starting heartbeats\n try? await Task.sleep(for: .seconds(1))\n\n while !Task.isCancelled {\n do {\n // Check actor-isolated properties first\n let isStopping = await self.isStopping\n let isConnected = await self.isConnected\n\n guard !isStopping && isConnected else { break }\n\n try await self.sendHeartbeat()\n try await Task.sleep(for: .seconds(self.heartbeatConfig.interval))\n } catch {\n // If heartbeat fails, log and retry after a shorter interval\n self.logger.warning(\"Heartbeat failed: \\(error)\")\n try? await Task.sleep(for: .seconds(2))\n }\n }\n }\n }\n\n /// Sends a heartbeat message to verify connection health\n private func sendHeartbeat() async throws {\n guard isConnected && !isStopping else { return }\n\n // Try to send the heartbeat (without the newline delimiter used for normal messages)\n try await withCheckedThrowingContinuation {\n [weak self] (continuation: CheckedContinuation) in\n guard let self = self else {\n continuation.resume(throwing: MCPError.internalError(\"Transport deallocated\"))\n return\n }\n\n connection.send(\n content: Heartbeat().data,\n contentContext: .defaultMessage,\n isComplete: true,\n completion: .contentProcessed { [weak self] error in\n if let error = error {\n continuation.resume(throwing: error)\n } else {\n Task { [weak self] in\n await self?.setLastHeartbeatTime(Date())\n }\n continuation.resume()\n }\n })\n }\n\n logger.trace(\"Heartbeat sent\")\n }\n\n /// Handles connection failure\n ///\n /// - Parameters:\n /// - error: The error that caused the connection to fail\n /// - continuation: The continuation to resume with the error\n private func handleConnectionFailed(\n error: Swift.Error, continuation: CheckedContinuation\n ) async {\n if !connectionContinuationResumed {\n connectionContinuationResumed = true\n logger.error(\"Connection failed: \\(error)\")\n\n await handleReconnection(\n error: error,\n continuation: continuation,\n context: \"failure\"\n )\n }\n }\n\n /// Handles connection cancellation\n ///\n /// - Parameter continuation: The continuation to resume with cancellation error\n private func handleConnectionCancelled(continuation: CheckedContinuation)\n async\n {\n if !connectionContinuationResumed {\n connectionContinuationResumed = true\n logger.warning(\"Connection cancelled\")\n\n await handleReconnection(\n error: MCPError.internalError(\"Connection cancelled\"),\n continuation: continuation,\n context: \"cancellation\"\n )\n }\n }\n\n /// Common reconnection handling logic\n ///\n /// - Parameters:\n /// - error: The error that triggered the reconnection\n /// - continuation: The continuation to resume with the error\n /// - context: The context of the reconnection (for logging)\n private func handleReconnection(\n error: Swift.Error,\n continuation: CheckedContinuation,\n context: String\n ) async {\n if !isStopping,\n reconnectionConfig.enabled,\n reconnectAttempt < reconnectionConfig.maxAttempts\n {\n // Try to reconnect with exponential backoff\n reconnectAttempt += 1\n logger.info(\n \"Attempting reconnection after \\(context) (\\(reconnectAttempt)/\\(reconnectionConfig.maxAttempts))...\"\n )\n\n // Calculate backoff delay\n let delay = reconnectionConfig.backoffDelay(for: reconnectAttempt)\n\n // Schedule reconnection attempt after delay\n Task {\n try? await Task.sleep(for: .seconds(delay))\n if !isStopping {\n // Cancel the current connection before attempting to reconnect.\n self.connection.cancel()\n // Resume original continuation with error; outer logic or a new call to connect() will handle retry.\n continuation.resume(throwing: error)\n } else {\n continuation.resume(throwing: error) // Stopping, so fail.\n }\n }\n } else {\n // Not configured to reconnect, exceeded max attempts, or stopping\n self.connection.cancel() // Ensure connection is cancelled\n continuation.resume(throwing: error)\n }\n }\n\n /// Disconnects from the transport\n ///\n /// This cancels the NWConnection, finalizes the message stream,\n /// and releases associated resources.\n public func disconnect() async {\n guard isConnected else { return }\n\n // Mark as stopping to prevent reconnection attempts during disconnect\n isStopping = true\n isConnected = false\n\n // Cancel heartbeat task if it exists\n heartbeatTask?.cancel()\n heartbeatTask = nil\n\n connection.cancel()\n messageContinuation.finish()\n logger.info(\"Network transport disconnected\")\n }\n\n /// Sends data through the network connection\n ///\n /// This sends a JSON-RPC message through the NWConnection, adding a newline\n /// delimiter to mark the end of the message.\n ///\n /// - Parameter message: The JSON-RPC message to send\n /// - Throws: MCPError for transport failures or connection issues\n public func send(_ message: Data) async throws {\n guard isConnected else {\n throw MCPError.internalError(\"Transport not connected\")\n }\n\n // Add newline as delimiter\n var messageWithNewline = message\n messageWithNewline.append(UInt8(ascii: \"\\n\"))\n\n // Use a local actor-isolated variable to track continuation state\n var sendContinuationResumed = false\n\n try await withCheckedThrowingContinuation {\n [weak self] (continuation: CheckedContinuation) in\n guard let self = self else {\n continuation.resume(throwing: MCPError.internalError(\"Transport deallocated\"))\n return\n }\n\n connection.send(\n content: messageWithNewline,\n contentContext: .defaultMessage,\n isComplete: true,\n completion: .contentProcessed { [weak self] error in\n guard let self = self else { return }\n\n Task { @MainActor in\n if !sendContinuationResumed {\n sendContinuationResumed = true\n if let error = error {\n self.logger.error(\"Send error: \\(error)\")\n\n // Check if we should attempt to reconnect on send failure\n let isStopping = await self.isStopping // Await actor-isolated property\n if !isStopping && self.reconnectionConfig.enabled {\n let isConnected = await self.isConnected\n if isConnected {\n if error.isConnectionLost {\n self.logger.warning(\n \"Connection appears broken, will attempt to reconnect...\"\n )\n\n // Schedule connection restart\n Task { [weak self] in // Operate on self's executor\n guard let self = self else { return }\n\n await self.setIsConnected(false)\n\n try? await Task.sleep(for: .milliseconds(500))\n\n let currentIsStopping = await self.isStopping\n if !currentIsStopping {\n // Cancel the connection, then attempt to reconnect fully.\n self.connection.cancel()\n try? await self.connect()\n }\n }\n }\n }\n }\n\n continuation.resume(\n throwing: MCPError.internalError(\"Send error: \\(error)\"))\n } else {\n continuation.resume()\n }\n }\n }\n })\n }\n }\n\n /// Receives data in an async sequence\n ///\n /// This returns an AsyncThrowingStream that emits Data objects representing\n /// each JSON-RPC message received from the network connection.\n ///\n /// - Returns: An AsyncThrowingStream of Data objects\n public func receive() -> AsyncThrowingStream {\n return messageStream\n }\n\n /// Continuous loop to receive and process incoming messages\n ///\n /// This method runs continuously while the connection is active,\n /// receiving data and yielding complete messages to the message stream.\n /// Messages are delimited by newline characters.\n private func receiveLoop() async {\n var buffer = Data()\n var consecutiveEmptyReads = 0\n let maxConsecutiveEmptyReads = 5\n\n while isConnected && !Task.isCancelled && !isStopping {\n do {\n let newData = try await receiveData()\n\n // Check for EOF or empty data\n if newData.isEmpty {\n consecutiveEmptyReads += 1\n\n if consecutiveEmptyReads >= maxConsecutiveEmptyReads {\n logger.warning(\n \"Multiple consecutive empty reads (\\(consecutiveEmptyReads)), possible connection issue\"\n )\n\n // Check connection state\n if connection.state != .ready {\n logger.info(\"Connection no longer ready, exiting receive loop\")\n break\n }\n }\n\n // Brief pause before retry\n try await Task.sleep(for: .milliseconds(100))\n continue\n }\n\n // Check if this is a heartbeat message\n if Heartbeat.isHeartbeat(newData) {\n logger.trace(\"Received heartbeat from peer\")\n\n // Extract timestamp if available\n if let heartbeat = Heartbeat.from(data: newData) {\n logger.trace(\"Heartbeat timestamp: \\(heartbeat.timestamp)\")\n }\n\n // Reset the counter since we got valid data\n consecutiveEmptyReads = 0\n continue // Skip regular message processing for heartbeats\n }\n\n // Reset counter on successful data read\n consecutiveEmptyReads = 0\n buffer.append(newData)\n\n // Process complete messages\n while let newlineIndex = buffer.firstIndex(of: UInt8(ascii: \"\\n\")) {\n let messageData = buffer[.. Data {\n var receiveContinuationResumed = false\n\n return try await withCheckedThrowingContinuation {\n [weak self] (continuation: CheckedContinuation) in\n guard let self = self else {\n continuation.resume(throwing: MCPError.internalError(\"Transport deallocated\"))\n return\n }\n\n let maxLength = bufferConfig.maxReceiveBufferSize ?? Int.max\n connection.receive(minimumIncompleteLength: 1, maximumLength: maxLength) {\n content, _, isComplete, error in\n Task { @MainActor in\n if !receiveContinuationResumed {\n receiveContinuationResumed = true\n if let error = error {\n continuation.resume(throwing: MCPError.transportError(error))\n } else if let content = content {\n continuation.resume(returning: content)\n } else if isComplete {\n self.logger.trace(\"Connection completed by peer\")\n continuation.resume(throwing: MCPError.connectionClosed)\n } else {\n // EOF: Resume with empty data instead of throwing an error\n continuation.resume(returning: Data())\n }\n }\n }\n }\n }\n }\n\n private func setLastHeartbeatTime(_ time: Date) {\n self.lastHeartbeatTime = time\n }\n\n private func setIsConnected(_ connected: Bool) {\n self.isConnected = connected\n }\n }\n\n extension NWError {\n /// Whether this error indicates a connection has been lost or reset.\n fileprivate var isConnectionLost: Bool {\n let nsError = self as NSError\n return nsError.code == 57 // Socket is not connected (EHOSTUNREACH or ENOTCONN)\n || nsError.code == 54 // Connection reset by peer (ECONNRESET)\n }\n }\n#endif\n"], ["/swift-sdk/Sources/MCP/Base/Transports/HTTPClientTransport.swift", "import Foundation\nimport Logging\n\n#if !os(Linux)\n import EventSource\n#endif\n\n#if canImport(FoundationNetworking)\n import FoundationNetworking\n#endif\n\n/// An implementation of the MCP Streamable HTTP transport protocol for clients.\n///\n/// This transport implements the [Streamable HTTP transport](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http)\n/// specification from the Model Context Protocol.\n///\n/// It supports:\n/// - Sending JSON-RPC messages via HTTP POST requests\n/// - Receiving responses via both direct JSON responses and SSE streams\n/// - Session management using the `Mcp-Session-Id` header\n/// - Automatic reconnection for dropped SSE streams\n/// - Platform-specific optimizations for different operating systems\n///\n/// The transport supports two modes:\n/// - Regular HTTP (`streaming=false`): Simple request/response pattern\n/// - Streaming HTTP with SSE (`streaming=true`): Enables server-to-client push messages\n///\n/// - Important: Server-Sent Events (SSE) functionality is not supported on Linux platforms.\n///\n/// ## Example Usage\n///\n/// ```swift\n/// import MCP\n///\n/// // Create a streaming HTTP transport\n/// let transport = HTTPClientTransport(\n/// endpoint: URL(string: \"http://localhost:8080\")!,\n/// )\n///\n/// // Initialize the client with streaming transport\n/// let client = Client(name: \"MyApp\", version: \"1.0.0\")\n/// try await client.connect(transport: transport)\n///\n/// // The transport will automatically handle SSE events\n/// // and deliver them through the client's notification handlers\n/// ```\npublic actor HTTPClientTransport: Transport {\n /// The server endpoint URL to connect to\n public let endpoint: URL\n private let session: URLSession\n\n /// The session ID assigned by the server, used for maintaining state across requests\n public private(set) var sessionID: String?\n private let streaming: Bool\n private var streamingTask: Task?\n\n /// Logger instance for transport-related events\n public nonisolated let logger: Logger\n\n /// Maximum time to wait for a session ID before proceeding with SSE connection\n public let sseInitializationTimeout: TimeInterval\n\n private var isConnected = false\n private let messageStream: AsyncThrowingStream\n private let messageContinuation: AsyncThrowingStream.Continuation\n\n private var initialSessionIDSignalTask: Task?\n private var initialSessionIDContinuation: CheckedContinuation?\n\n /// Creates a new HTTP transport client with the specified endpoint\n ///\n /// - Parameters:\n /// - endpoint: The server URL to connect to\n /// - configuration: URLSession configuration to use for HTTP requests\n /// - streaming: Whether to enable SSE streaming mode (default: true)\n /// - sseInitializationTimeout: Maximum time to wait for session ID before proceeding with SSE (default: 10 seconds)\n /// - logger: Optional logger instance for transport events\n public init(\n endpoint: URL,\n configuration: URLSessionConfiguration = .default,\n streaming: Bool = true,\n sseInitializationTimeout: TimeInterval = 10,\n logger: Logger? = nil\n ) {\n self.init(\n endpoint: endpoint,\n session: URLSession(configuration: configuration),\n streaming: streaming,\n sseInitializationTimeout: sseInitializationTimeout,\n logger: logger\n )\n }\n\n internal init(\n endpoint: URL,\n session: URLSession,\n streaming: Bool = false,\n sseInitializationTimeout: TimeInterval = 10,\n logger: Logger? = nil\n ) {\n self.endpoint = endpoint\n self.session = session\n self.streaming = streaming\n self.sseInitializationTimeout = sseInitializationTimeout\n\n // Create message stream\n var continuation: AsyncThrowingStream.Continuation!\n self.messageStream = AsyncThrowingStream { continuation = $0 }\n self.messageContinuation = continuation\n\n self.logger =\n logger\n ?? Logger(\n label: \"mcp.transport.http.client\",\n factory: { _ in SwiftLogNoOpLogHandler() }\n )\n }\n\n // Setup the initial session ID signal\n private func setupInitialSessionIDSignal() {\n self.initialSessionIDSignalTask = Task {\n await withCheckedContinuation { continuation in\n self.initialSessionIDContinuation = continuation\n // This task will suspend here until continuation.resume() is called\n }\n }\n }\n\n // Trigger the initial session ID signal when a session ID is established\n private func triggerInitialSessionIDSignal() {\n if let continuation = self.initialSessionIDContinuation {\n continuation.resume()\n self.initialSessionIDContinuation = nil // Consume the continuation\n logger.trace(\"Initial session ID signal triggered for SSE task.\")\n }\n }\n\n /// Establishes connection with the transport\n ///\n /// This prepares the transport for communication and sets up SSE streaming\n /// if streaming mode is enabled. The actual HTTP connection happens with the\n /// first message sent.\n public func connect() async throws {\n guard !isConnected else { return }\n isConnected = true\n\n // Setup initial session ID signal\n setupInitialSessionIDSignal()\n\n if streaming {\n // Start listening to server events\n streamingTask = Task { await startListeningForServerEvents() }\n }\n\n logger.info(\"HTTP transport connected\")\n }\n\n /// Disconnects from the transport\n ///\n /// This terminates any active connections, cancels the streaming task,\n /// and releases any resources being used by the transport.\n public func disconnect() async {\n guard isConnected else { return }\n isConnected = false\n\n // Cancel streaming task if active\n streamingTask?.cancel()\n streamingTask = nil\n\n // Cancel any in-progress requests\n session.invalidateAndCancel()\n\n // Clean up message stream\n messageContinuation.finish()\n\n // Cancel the initial session ID signal task if active\n initialSessionIDSignalTask?.cancel()\n initialSessionIDSignalTask = nil\n // Resume the continuation if it's still pending to avoid leaks\n initialSessionIDContinuation?.resume()\n initialSessionIDContinuation = nil\n\n logger.info(\"HTTP clienttransport disconnected\")\n }\n\n /// Sends data through an HTTP POST request\n ///\n /// This sends a JSON-RPC message to the server via HTTP POST and processes\n /// the response according to the MCP Streamable HTTP specification. It handles:\n ///\n /// - Adding appropriate Accept headers for both JSON and SSE\n /// - Including the session ID in requests if one has been established\n /// - Processing different response types (JSON vs SSE)\n /// - Handling HTTP error codes according to the specification\n ///\n /// - Parameter data: The JSON-RPC message to send\n /// - Throws: MCPError for transport failures or server errors\n public func send(_ data: Data) async throws {\n guard isConnected else {\n throw MCPError.internalError(\"Transport not connected\")\n }\n\n var request = URLRequest(url: endpoint)\n request.httpMethod = \"POST\"\n request.addValue(\"application/json, text/event-stream\", forHTTPHeaderField: \"Accept\")\n request.addValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\n request.httpBody = data\n\n // Add session ID if available\n if let sessionID = sessionID {\n request.addValue(sessionID, forHTTPHeaderField: \"Mcp-Session-Id\")\n }\n\n #if os(Linux)\n // Linux implementation using data(for:) instead of bytes(for:)\n let (responseData, response) = try await session.data(for: request)\n try await processResponse(response: response, data: responseData)\n #else\n // macOS and other platforms with bytes(for:) support\n let (responseStream, response) = try await session.bytes(for: request)\n try await processResponse(response: response, stream: responseStream)\n #endif\n }\n\n #if os(Linux)\n // Process response with data payload (Linux)\n private func processResponse(response: URLResponse, data: Data) async throws {\n guard let httpResponse = response as? HTTPURLResponse else {\n throw MCPError.internalError(\"Invalid HTTP response\")\n }\n\n // Process the response based on content type and status code\n let contentType = httpResponse.value(forHTTPHeaderField: \"Content-Type\") ?? \"\"\n\n // Extract session ID if present\n if let newSessionID = httpResponse.value(forHTTPHeaderField: \"Mcp-Session-Id\") {\n let wasSessionIDNil = (self.sessionID == nil)\n self.sessionID = newSessionID\n if wasSessionIDNil {\n // Trigger signal on first session ID\n triggerInitialSessionIDSignal()\n }\n logger.debug(\"Session ID received\", metadata: [\"sessionID\": \"\\(newSessionID)\"])\n }\n\n try processHTTPResponse(httpResponse, contentType: contentType)\n guard case 200..<300 = httpResponse.statusCode else { return }\n\n // For JSON responses, yield the data\n if contentType.contains(\"text/event-stream\") {\n logger.warning(\"SSE responses aren't fully supported on Linux\")\n messageContinuation.yield(data)\n } else if contentType.contains(\"application/json\") {\n logger.trace(\"Received JSON response\", metadata: [\"size\": \"\\(data.count)\"])\n messageContinuation.yield(data)\n } else {\n logger.warning(\"Unexpected content type: \\(contentType)\")\n }\n }\n #else\n // Process response with byte stream (macOS, iOS, etc.)\n private func processResponse(response: URLResponse, stream: URLSession.AsyncBytes)\n async throws\n {\n guard let httpResponse = response as? HTTPURLResponse else {\n throw MCPError.internalError(\"Invalid HTTP response\")\n }\n\n // Process the response based on content type and status code\n let contentType = httpResponse.value(forHTTPHeaderField: \"Content-Type\") ?? \"\"\n\n // Extract session ID if present\n if let newSessionID = httpResponse.value(forHTTPHeaderField: \"Mcp-Session-Id\") {\n let wasSessionIDNil = (self.sessionID == nil)\n self.sessionID = newSessionID\n if wasSessionIDNil {\n // Trigger signal on first session ID\n triggerInitialSessionIDSignal()\n }\n logger.debug(\"Session ID received\", metadata: [\"sessionID\": \"\\(newSessionID)\"])\n }\n\n try processHTTPResponse(httpResponse, contentType: contentType)\n guard case 200..<300 = httpResponse.statusCode else { return }\n\n if contentType.contains(\"text/event-stream\") {\n // For SSE, processing happens via the stream\n logger.trace(\"Received SSE response, processing in streaming task\")\n try await self.processSSE(stream)\n } else if contentType.contains(\"application/json\") {\n // For JSON responses, collect and deliver the data\n var buffer = Data()\n for try await byte in stream {\n buffer.append(byte)\n }\n logger.trace(\"Received JSON response\", metadata: [\"size\": \"\\(buffer.count)\"])\n messageContinuation.yield(buffer)\n } else {\n logger.warning(\"Unexpected content type: \\(contentType)\")\n }\n }\n #endif\n\n // Common HTTP response handling for all platforms\n private func processHTTPResponse(_ response: HTTPURLResponse, contentType: String) throws {\n // Handle status codes according to HTTP semantics\n switch response.statusCode {\n case 200..<300:\n // Success range - these are handled by the platform-specific code\n return\n\n case 400:\n throw MCPError.internalError(\"Bad request\")\n\n case 401:\n throw MCPError.internalError(\"Authentication required\")\n\n case 403:\n throw MCPError.internalError(\"Access forbidden\")\n\n case 404:\n // If we get a 404 with a session ID, it means our session is invalid\n if sessionID != nil {\n logger.warning(\"Session has expired\")\n sessionID = nil\n throw MCPError.internalError(\"Session expired\")\n }\n throw MCPError.internalError(\"Endpoint not found\")\n\n case 405:\n // If we get a 405, it means the server does not support the requested method\n // If streaming was requested, we should cancel the streaming task\n if streaming {\n self.streamingTask?.cancel()\n throw MCPError.internalError(\"Server does not support streaming\")\n }\n throw MCPError.internalError(\"Method not allowed\")\n\n case 408:\n throw MCPError.internalError(\"Request timeout\")\n\n case 429:\n throw MCPError.internalError(\"Too many requests\")\n\n case 500..<600:\n // Server error range\n throw MCPError.internalError(\"Server error: \\(response.statusCode)\")\n\n default:\n throw MCPError.internalError(\n \"Unexpected HTTP response: \\(response.statusCode) (\\(contentType))\")\n }\n }\n\n /// Receives data in an async sequence\n ///\n /// This returns an AsyncThrowingStream that emits Data objects representing\n /// each JSON-RPC message received from the server. This includes:\n ///\n /// - Direct responses to client requests\n /// - Server-initiated messages delivered via SSE streams\n ///\n /// - Returns: An AsyncThrowingStream of Data objects\n public func receive() -> AsyncThrowingStream {\n return messageStream\n }\n\n // MARK: - SSE\n\n /// Starts listening for server events using SSE\n ///\n /// This establishes a long-lived HTTP connection using Server-Sent Events (SSE)\n /// to enable server-to-client push messaging. It handles:\n ///\n /// - Waiting for session ID if needed\n /// - Opening the SSE connection\n /// - Automatic reconnection on connection drops\n /// - Processing received events\n private func startListeningForServerEvents() async {\n #if os(Linux)\n // SSE is not fully supported on Linux\n if streaming {\n logger.warning(\n \"SSE streaming was requested but is not fully supported on Linux. SSE connection will not be attempted.\"\n )\n }\n #else\n // This is the original code for platforms that support SSE\n guard isConnected else { return }\n\n // Wait for the initial session ID signal, but only if sessionID isn't already set\n if self.sessionID == nil, let signalTask = self.initialSessionIDSignalTask {\n logger.trace(\"SSE streaming task waiting for initial sessionID signal...\")\n\n // Race the signalTask against a timeout\n let timeoutTask = Task {\n try? await Task.sleep(for: .seconds(self.sseInitializationTimeout))\n return false\n }\n\n let signalCompletionTask = Task {\n await signalTask.value\n return true // Indicates signal received\n }\n\n // Use TaskGroup to race the two tasks\n var signalReceived = false\n do {\n signalReceived = try await withThrowingTaskGroup(of: Bool.self) { group in\n group.addTask {\n await signalCompletionTask.value\n }\n group.addTask {\n await timeoutTask.value\n }\n\n // Take the first result and cancel the other task\n if let firstResult = try await group.next() {\n group.cancelAll()\n return firstResult\n }\n return false\n }\n } catch {\n logger.error(\"Error while waiting for session ID signal: \\(error)\")\n }\n\n // Clean up tasks\n timeoutTask.cancel()\n\n if signalReceived {\n logger.trace(\"SSE streaming task proceeding after initial sessionID signal.\")\n } else {\n logger.warning(\n \"Timeout waiting for initial sessionID signal. SSE stream will proceed (sessionID might be nil).\"\n )\n }\n } else if self.sessionID != nil {\n logger.trace(\n \"Initial sessionID already available. Proceeding with SSE streaming task immediately.\"\n )\n } else {\n logger.info(\n \"Proceeding with SSE connection attempt; sessionID is nil. This might be expected for stateless servers or if initialize hasn't provided one yet.\"\n )\n }\n\n // Retry loop for connection drops\n while isConnected && !Task.isCancelled {\n do {\n try await connectToEventStream()\n } catch {\n if !Task.isCancelled {\n logger.error(\"SSE connection error: \\(error)\")\n // Wait before retrying\n try? await Task.sleep(for: .seconds(1))\n }\n }\n }\n #endif\n }\n\n #if !os(Linux)\n /// Establishes an SSE connection to the server\n ///\n /// This initiates a GET request to the server endpoint with appropriate\n /// headers to establish an SSE stream according to the MCP specification.\n ///\n /// - Throws: MCPError for connection failures or server errors\n private func connectToEventStream() async throws {\n guard isConnected else { return }\n\n var request = URLRequest(url: endpoint)\n request.httpMethod = \"GET\"\n request.addValue(\"text/event-stream\", forHTTPHeaderField: \"Accept\")\n request.addValue(\"no-cache\", forHTTPHeaderField: \"Cache-Control\")\n\n // Add session ID if available\n if let sessionID = sessionID {\n request.addValue(sessionID, forHTTPHeaderField: \"Mcp-Session-Id\")\n }\n\n logger.debug(\"Starting SSE connection\")\n\n // Create URLSession task for SSE\n let (stream, response) = try await session.bytes(for: request)\n\n guard let httpResponse = response as? HTTPURLResponse else {\n throw MCPError.internalError(\"Invalid HTTP response\")\n }\n\n // Check response status\n guard httpResponse.statusCode == 200 else {\n // If the server returns 405 Method Not Allowed,\n // it indicates that the server doesn't support SSE streaming.\n // We should cancel the task instead of retrying the connection.\n if httpResponse.statusCode == 405 {\n self.streamingTask?.cancel()\n }\n throw MCPError.internalError(\"HTTP error: \\(httpResponse.statusCode)\")\n }\n\n // Extract session ID if present\n if let newSessionID = httpResponse.value(forHTTPHeaderField: \"Mcp-Session-Id\") {\n let wasSessionIDNil = (self.sessionID == nil)\n self.sessionID = newSessionID\n if wasSessionIDNil {\n // Trigger signal on first session ID, though this is unlikely to happen here\n // as GET usually follows a POST that would have already set the session ID\n triggerInitialSessionIDSignal()\n }\n logger.debug(\"Session ID received\", metadata: [\"sessionID\": \"\\(newSessionID)\"])\n }\n\n try await self.processSSE(stream)\n }\n\n /// Processes an SSE byte stream, extracting events and delivering them\n ///\n /// - Parameter stream: The URLSession.AsyncBytes stream to process\n /// - Throws: Error for stream processing failures\n private func processSSE(_ stream: URLSession.AsyncBytes) async throws {\n do {\n for try await event in stream.events {\n // Check if task has been cancelled\n if Task.isCancelled { break }\n\n logger.trace(\n \"SSE event received\",\n metadata: [\n \"type\": \"\\(event.event ?? \"message\")\",\n \"id\": \"\\(event.id ?? \"none\")\",\n ]\n )\n\n // Convert the event data to Data and yield it to the message stream\n if !event.data.isEmpty, let data = event.data.data(using: .utf8) {\n messageContinuation.yield(data)\n }\n }\n } catch {\n logger.error(\"Error processing SSE events: \\(error)\")\n throw error\n }\n }\n #endif\n}\n"], ["/swift-sdk/Sources/MCP/Client/Client.swift", "import Logging\n\nimport struct Foundation.Data\nimport struct Foundation.Date\nimport class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\n/// Model Context Protocol client\npublic actor Client {\n /// The client configuration\n public struct Configuration: Hashable, Codable, Sendable {\n /// The default configuration.\n public static let `default` = Configuration(strict: false)\n\n /// The strict configuration.\n public static let strict = Configuration(strict: true)\n\n /// When strict mode is enabled, the client:\n /// - Requires server capabilities to be initialized before making requests\n /// - Rejects all requests that require capabilities before initialization\n ///\n /// While the MCP specification requires servers to respond to initialize requests\n /// with their capabilities, some implementations may not follow this.\n /// Disabling strict mode allows the client to be more lenient with non-compliant\n /// servers, though this may lead to undefined behavior.\n public var strict: Bool\n\n public init(strict: Bool = false) {\n self.strict = strict\n }\n }\n\n /// Implementation information\n public struct Info: Hashable, Codable, Sendable {\n /// The client name\n public var name: String\n /// The client version\n public var version: String\n\n public init(name: String, version: String) {\n self.name = name\n self.version = version\n }\n }\n\n /// The client capabilities\n public struct Capabilities: Hashable, Codable, Sendable {\n /// The roots capabilities\n public struct Roots: Hashable, Codable, Sendable {\n /// Whether the list of roots has changed\n public var listChanged: Bool?\n\n public init(listChanged: Bool? = nil) {\n self.listChanged = listChanged\n }\n }\n\n /// The sampling capabilities\n public struct Sampling: Hashable, Codable, Sendable {\n public init() {}\n }\n\n /// Whether the client supports sampling\n public var sampling: Sampling?\n /// Experimental features supported by the client\n public var experimental: [String: String]?\n /// Whether the client supports roots\n public var roots: Capabilities.Roots?\n\n public init(\n sampling: Sampling? = nil,\n experimental: [String: String]? = nil,\n roots: Capabilities.Roots? = nil\n ) {\n self.sampling = sampling\n self.experimental = experimental\n self.roots = roots\n }\n }\n\n /// The connection to the server\n private var connection: (any Transport)?\n /// The logger for the client\n private var logger: Logger? {\n get async {\n await connection?.logger\n }\n }\n\n /// The client information\n private let clientInfo: Client.Info\n /// The client name\n public nonisolated var name: String { clientInfo.name }\n /// The client version\n public nonisolated var version: String { clientInfo.version }\n\n /// The client capabilities\n public var capabilities: Client.Capabilities\n /// The client configuration\n public var configuration: Configuration\n\n /// The server capabilities\n private var serverCapabilities: Server.Capabilities?\n /// The server version\n private var serverVersion: String?\n /// The server instructions\n private var instructions: String?\n\n /// A dictionary of type-erased notification handlers, keyed by method name\n private var notificationHandlers: [String: [NotificationHandlerBox]] = [:]\n /// The task for the message handling loop\n private var task: Task?\n\n /// An error indicating a type mismatch when decoding a pending request\n private struct TypeMismatchError: Swift.Error {}\n\n /// A pending request with a continuation for the result\n private struct PendingRequest {\n let continuation: CheckedContinuation\n }\n\n /// A type-erased pending request\n private struct AnyPendingRequest {\n private let _resume: (Result) -> Void\n\n init(_ request: PendingRequest) {\n _resume = { result in\n switch result {\n case .success(let value):\n if let typedValue = value as? T {\n request.continuation.resume(returning: typedValue)\n } else if let value = value as? Value,\n let data = try? JSONEncoder().encode(value),\n let decoded = try? JSONDecoder().decode(T.self, from: data)\n {\n request.continuation.resume(returning: decoded)\n } else {\n request.continuation.resume(throwing: TypeMismatchError())\n }\n case .failure(let error):\n request.continuation.resume(throwing: error)\n }\n }\n }\n func resume(returning value: Any) {\n _resume(.success(value))\n }\n\n func resume(throwing error: Swift.Error) {\n _resume(.failure(error))\n }\n }\n\n /// A dictionary of type-erased pending requests, keyed by request ID\n private var pendingRequests: [ID: AnyPendingRequest] = [:]\n // Add reusable JSON encoder/decoder\n private let encoder = JSONEncoder()\n private let decoder = JSONDecoder()\n\n public init(\n name: String,\n version: String,\n configuration: Configuration = .default\n ) {\n self.clientInfo = Client.Info(name: name, version: version)\n self.capabilities = Capabilities()\n self.configuration = configuration\n }\n\n /// Connect to the server using the given transport\n @discardableResult\n public func connect(transport: any Transport) async throws -> Initialize.Result {\n self.connection = transport\n try await self.connection?.connect()\n\n await logger?.info(\n \"Client connected\", metadata: [\"name\": \"\\(name)\", \"version\": \"\\(version)\"])\n\n // Start message handling loop\n task = Task {\n guard let connection = self.connection else { return }\n repeat {\n // Check for cancellation before starting the iteration\n if Task.isCancelled { break }\n\n do {\n let stream = await connection.receive()\n for try await data in stream {\n if Task.isCancelled { break } // Check inside loop too\n\n // Attempt to decode data\n // Try decoding as a batch response first\n if let batchResponse = try? decoder.decode([AnyResponse].self, from: data) {\n await handleBatchResponse(batchResponse)\n } else if let response = try? decoder.decode(AnyResponse.self, from: data) {\n await handleResponse(response)\n } else if let message = try? decoder.decode(AnyMessage.self, from: data) {\n await handleMessage(message)\n } else {\n var metadata: Logger.Metadata = [:]\n if let string = String(data: data, encoding: .utf8) {\n metadata[\"message\"] = .string(string)\n }\n await logger?.warning(\n \"Unexpected message received by client (not single/batch response or notification)\",\n metadata: metadata\n )\n }\n }\n } catch let error where MCPError.isResourceTemporarilyUnavailable(error) {\n try? await Task.sleep(for: .milliseconds(10))\n continue\n } catch {\n await logger?.error(\n \"Error in message handling loop\", metadata: [\"error\": \"\\(error)\"])\n break\n }\n } while true\n await self.logger?.info(\"Client message handling loop task is terminating.\")\n }\n\n // Automatically initialize after connecting\n return try await _initialize()\n }\n\n /// Disconnect the client and cancel all pending requests\n public func disconnect() async {\n await logger?.info(\"Initiating client disconnect...\")\n\n // Part 1: Inside actor - Grab state and clear internal references\n let taskToCancel = self.task\n let connectionToDisconnect = self.connection\n let pendingRequestsToCancel = self.pendingRequests\n\n self.task = nil\n self.connection = nil\n self.pendingRequests = [:] // Use empty dictionary literal\n\n // Part 2: Outside actor - Resume continuations, disconnect transport, await task\n\n // Resume continuations first\n for (_, request) in pendingRequestsToCancel {\n request.resume(throwing: MCPError.internalError(\"Client disconnected\"))\n }\n await logger?.info(\"Pending requests cancelled.\")\n\n // Cancel the task\n taskToCancel?.cancel()\n await logger?.info(\"Message loop task cancellation requested.\")\n\n // Disconnect the transport *before* awaiting the task\n // This should ensure the transport stream is finished, unblocking the loop.\n if let conn = connectionToDisconnect {\n await conn.disconnect()\n await logger?.info(\"Transport disconnected.\")\n } else {\n await logger?.info(\"No active transport connection to disconnect.\")\n }\n\n // Await the task completion *after* transport disconnect\n _ = await taskToCancel?.value\n await logger?.info(\"Client message loop task finished.\")\n\n await logger?.info(\"Client disconnect complete.\")\n }\n\n // MARK: - Registration\n\n /// Register a handler for a notification\n @discardableResult\n public func onNotification(\n _ type: N.Type,\n handler: @escaping @Sendable (Message) async throws -> Void\n ) async -> Self {\n let handlers = notificationHandlers[N.name, default: []]\n notificationHandlers[N.name] = handlers + [TypedNotificationHandler(handler)]\n return self\n }\n\n /// Send a notification to the server\n public func notify(_ notification: Message) async throws {\n guard let connection = connection else {\n throw MCPError.internalError(\"Client connection not initialized\")\n }\n\n let notificationData = try encoder.encode(notification)\n try await connection.send(notificationData)\n }\n\n // MARK: - Requests\n\n /// Send a request and receive its response\n public func send(_ request: Request) async throws -> M.Result {\n guard let connection = connection else {\n throw MCPError.internalError(\"Client connection not initialized\")\n }\n\n let requestData = try encoder.encode(request)\n\n // Store the pending request first\n return try await withCheckedThrowingContinuation { continuation in\n Task {\n // Add the pending request before attempting to send\n self.addPendingRequest(\n id: request.id,\n continuation: continuation,\n type: M.Result.self\n )\n\n // Send the request data\n do {\n // Use the existing connection send\n try await connection.send(requestData)\n } catch {\n // If send fails, try to remove the pending request.\n // Resume with the send error only if we successfully removed the request,\n // indicating the response handler hasn't processed it yet.\n if self.removePendingRequest(id: request.id) != nil {\n continuation.resume(throwing: error)\n }\n // Otherwise, the request was already removed by the response handler\n // or by disconnect, so the continuation was already resumed.\n // Do nothing here.\n }\n }\n }\n }\n\n private func addPendingRequest(\n id: ID,\n continuation: CheckedContinuation,\n type: T.Type // Keep type for AnyPendingRequest internal logic\n ) {\n pendingRequests[id] = AnyPendingRequest(PendingRequest(continuation: continuation))\n }\n\n private func removePendingRequest(id: ID) -> AnyPendingRequest? {\n return pendingRequests.removeValue(forKey: id)\n }\n\n // MARK: - Batching\n\n /// A batch of requests.\n ///\n /// Objects of this type are passed as an argument to the closure\n /// of the ``Client/withBatch(_:)`` method.\n public actor Batch {\n unowned let client: Client\n var requests: [AnyRequest] = []\n\n init(client: Client) {\n self.client = client\n }\n\n /// Adds a request to the batch and prepares its expected response task.\n /// The actual sending happens when the `withBatch` scope completes.\n /// - Returns: A `Task` that will eventually produce the result or throw an error.\n public func addRequest(_ request: Request) async throws -> Task<\n M.Result, Swift.Error\n > {\n requests.append(try AnyRequest(request))\n\n // Return a Task that registers the pending request and awaits its result.\n // The continuation is resumed when the response arrives.\n return Task {\n try await withCheckedThrowingContinuation { continuation in\n // We are already inside a Task, but need another Task\n // to bridge to the client actor's context.\n Task {\n await client.addPendingRequest(\n id: request.id,\n continuation: continuation,\n type: M.Result.self\n )\n }\n }\n }\n }\n }\n\n /// Executes multiple requests in a single batch.\n ///\n /// This method allows you to group multiple MCP requests together,\n /// which are then sent to the server as a single JSON array.\n /// The server processes these requests and sends back a corresponding\n /// JSON array of responses.\n ///\n /// Within the `body` closure, use the provided `Batch` actor to add\n /// requests using `batch.addRequest(_:)`. Each call to `addRequest`\n /// returns a `Task` handle representing the asynchronous operation\n /// for that specific request's result.\n ///\n /// It's recommended to collect these `Task` handles into an array\n /// within the `body` closure`. After the `withBatch` method returns\n /// (meaning the batch request has been sent), you can then process\n /// the results by awaiting each `Task` in the collected array.\n ///\n /// Example 1: Batching multiple tool calls and collecting typed tasks:\n /// ```swift\n /// // Array to hold the task handles for each tool call\n /// var toolTasks: [Task] = []\n /// try await client.withBatch { batch in\n /// for i in 0..<10 {\n /// toolTasks.append(\n /// try await batch.addRequest(\n /// CallTool.request(.init(name: \"square\", arguments: [\"n\": i]))\n /// )\n /// )\n /// }\n /// }\n ///\n /// // Process results after the batch is sent\n /// print(\"Processing \\(toolTasks.count) tool results...\")\n /// for (index, task) in toolTasks.enumerated() {\n /// do {\n /// let result = try await task.value\n /// print(\"\\(index): \\(result.content)\")\n /// } catch {\n /// print(\"\\(index) failed: \\(error)\")\n /// }\n /// }\n /// ```\n ///\n /// Example 2: Batching different request types and awaiting individual tasks:\n /// ```swift\n /// // Declare optional task variables beforehand\n /// var pingTask: Task?\n /// var promptTask: Task?\n ///\n /// try await client.withBatch { batch in\n /// // Assign the tasks within the batch closure\n /// pingTask = try await batch.addRequest(Ping.request())\n /// promptTask = try await batch.addRequest(GetPrompt.request(.init(name: \"greeting\")))\n /// }\n ///\n /// // Await the results after the batch is sent\n /// do {\n /// if let pingTask = pingTask {\n /// try await pingTask.value // Await ping result (throws if ping failed)\n /// print(\"Ping successful\")\n /// }\n /// if let promptTask = promptTask {\n /// let promptResult = try await promptTask.value // Await prompt result\n /// print(\"Prompt description: \\(promptResult.description ?? \"None\")\")\n /// }\n /// } catch {\n /// print(\"Error processing batch results: \\(error)\")\n /// }\n /// ```\n ///\n /// - Parameter body: An asynchronous closure that takes a `Batch` object as input.\n /// Use this object to add requests to the batch.\n /// - Throws: `MCPError.internalError` if the client is not connected.\n /// Can also rethrow errors from the `body` closure or from sending the batch request.\n public func withBatch(body: @escaping (Batch) async throws -> Void) async throws {\n guard let connection = connection else {\n throw MCPError.internalError(\"Client connection not initialized\")\n }\n\n // Create Batch actor, passing self (Client)\n let batch = Batch(client: self)\n\n // Populate the batch actor by calling the user's closure.\n try await body(batch)\n\n // Get the collected requests from the batch actor\n let requests = await batch.requests\n\n // Check if there are any requests to send\n guard !requests.isEmpty else {\n await logger?.info(\"Batch requested but no requests were added.\")\n return // Nothing to send\n }\n\n await logger?.debug(\n \"Sending batch request\", metadata: [\"count\": \"\\(requests.count)\"])\n\n // Encode the array of AnyMethod requests into a single JSON payload\n let data = try encoder.encode(requests)\n try await connection.send(data)\n\n // Responses will be handled asynchronously by the message loop and handleBatchResponse/handleResponse.\n }\n\n // MARK: - Lifecycle\n\n /// Initialize the connection with the server.\n ///\n /// - Important: This method is deprecated. Initialization now happens automatically\n /// when calling `connect(transport:)`. You should use that method instead.\n ///\n /// - Returns: The server's initialization response containing capabilities and server info\n @available(\n *, deprecated,\n message:\n \"Initialization now happens automatically during connect. Use connect(transport:) instead.\"\n )\n public func initialize() async throws -> Initialize.Result {\n return try await _initialize()\n }\n\n /// Internal initialization implementation\n private func _initialize() async throws -> Initialize.Result {\n let request = Initialize.request(\n .init(\n protocolVersion: Version.latest,\n capabilities: capabilities,\n clientInfo: clientInfo\n ))\n\n let result = try await send(request)\n\n self.serverCapabilities = result.capabilities\n self.serverVersion = result.protocolVersion\n self.instructions = result.instructions\n\n try await notify(InitializedNotification.message())\n\n return result\n }\n\n public func ping() async throws {\n let request = Ping.request()\n _ = try await send(request)\n }\n\n // MARK: - Prompts\n\n public func getPrompt(name: String, arguments: [String: Value]? = nil) async throws\n -> (description: String?, messages: [Prompt.Message])\n {\n try validateServerCapability(\\.prompts, \"Prompts\")\n let request = GetPrompt.request(.init(name: name, arguments: arguments))\n let result = try await send(request)\n return (description: result.description, messages: result.messages)\n }\n\n public func listPrompts(cursor: String? = nil) async throws\n -> (prompts: [Prompt], nextCursor: String?)\n {\n try validateServerCapability(\\.prompts, \"Prompts\")\n let request: Request\n if let cursor = cursor {\n request = ListPrompts.request(.init(cursor: cursor))\n } else {\n request = ListPrompts.request(.init())\n }\n let result = try await send(request)\n return (prompts: result.prompts, nextCursor: result.nextCursor)\n }\n\n // MARK: - Resources\n\n public func readResource(uri: String) async throws -> [Resource.Content] {\n try validateServerCapability(\\.resources, \"Resources\")\n let request = ReadResource.request(.init(uri: uri))\n let result = try await send(request)\n return result.contents\n }\n\n public func listResources(cursor: String? = nil) async throws -> (\n resources: [Resource], nextCursor: String?\n ) {\n try validateServerCapability(\\.resources, \"Resources\")\n let request: Request\n if let cursor = cursor {\n request = ListResources.request(.init(cursor: cursor))\n } else {\n request = ListResources.request(.init())\n }\n let result = try await send(request)\n return (resources: result.resources, nextCursor: result.nextCursor)\n }\n\n public func subscribeToResource(uri: String) async throws {\n try validateServerCapability(\\.resources?.subscribe, \"Resource subscription\")\n let request = ResourceSubscribe.request(.init(uri: uri))\n _ = try await send(request)\n }\n\n public func listResourceTemplates(cursor: String? = nil) async throws -> (\n templates: [Resource.Template], nextCursor: String?\n ) {\n try validateServerCapability(\\.resources, \"Resources\")\n let request: Request\n if let cursor = cursor {\n request = ListResourceTemplates.request(.init(cursor: cursor))\n } else {\n request = ListResourceTemplates.request(.init())\n }\n let result = try await send(request)\n return (templates: result.templates, nextCursor: result.nextCursor)\n }\n\n // MARK: - Tools\n\n public func listTools(cursor: String? = nil) async throws -> (\n tools: [Tool], nextCursor: String?\n ) {\n try validateServerCapability(\\.tools, \"Tools\")\n let request: Request\n if let cursor = cursor {\n request = ListTools.request(.init(cursor: cursor))\n } else {\n request = ListTools.request(.init())\n }\n let result = try await send(request)\n return (tools: result.tools, nextCursor: result.nextCursor)\n }\n\n public func callTool(name: String, arguments: [String: Value]? = nil) async throws -> (\n content: [Tool.Content], isError: Bool?\n ) {\n try validateServerCapability(\\.tools, \"Tools\")\n let request = CallTool.request(.init(name: name, arguments: arguments))\n let result = try await send(request)\n return (content: result.content, isError: result.isError)\n }\n\n // MARK: - Sampling\n\n /// Register a handler for sampling requests from servers\n ///\n /// Sampling allows servers to request LLM completions through the client,\n /// enabling sophisticated agentic behaviors while maintaining human-in-the-loop control.\n ///\n /// The sampling flow follows these steps:\n /// 1. Server sends a `sampling/createMessage` request to the client\n /// 2. Client reviews the request and can modify it (via this handler)\n /// 3. Client samples from an LLM (via this handler)\n /// 4. Client reviews the completion (via this handler)\n /// 5. Client returns the result to the server\n ///\n /// - Parameter handler: A closure that processes sampling requests and returns completions\n /// - Returns: Self for method chaining\n /// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/sampling#how-sampling-works\n @discardableResult\n public func withSamplingHandler(\n _ handler: @escaping @Sendable (CreateSamplingMessage.Parameters) async throws ->\n CreateSamplingMessage.Result\n ) -> Self {\n // Note: This would require extending the client architecture to handle incoming requests from servers.\n // The current MCP Swift SDK architecture assumes clients only send requests to servers,\n // but sampling requires bidirectional communication where servers can send requests to clients.\n //\n // A full implementation would need:\n // 1. Request handlers in the client (similar to how servers handle requests)\n // 2. Bidirectional transport support\n // 3. Request/response correlation for server-to-client requests\n //\n // For now, this serves as the correct API design for when bidirectional support is added.\n\n // This would register the handler similar to how servers register method handlers:\n // methodHandlers[CreateSamplingMessage.name] = TypedRequestHandler(handler)\n\n return self\n }\n\n // MARK: -\n\n private func handleResponse(_ response: Response) async {\n await logger?.trace(\n \"Processing response\",\n metadata: [\"id\": \"\\(response.id)\"])\n\n // Attempt to remove the pending request using the response ID.\n // Resume with the response only if it hadn't yet been removed.\n if let removedRequest = self.removePendingRequest(id: response.id) {\n // If we successfully removed it, resume its continuation.\n switch response.result {\n case .success(let value):\n removedRequest.resume(returning: value)\n case .failure(let error):\n removedRequest.resume(throwing: error)\n }\n } else {\n // Request was already removed (e.g., by send error handler or disconnect).\n // Log this, but it's not an error in race condition scenarios.\n await logger?.warning(\n \"Attempted to handle response for already removed request\",\n metadata: [\"id\": \"\\(response.id)\"]\n )\n }\n }\n\n private func handleMessage(_ message: Message) async {\n await logger?.trace(\n \"Processing notification\",\n metadata: [\"method\": \"\\(message.method)\"])\n\n // Find notification handlers for this method\n guard let handlers = notificationHandlers[message.method] else { return }\n\n // Convert notification parameters to concrete type and call handlers\n for handler in handlers {\n do {\n try await handler(message)\n } catch {\n await logger?.error(\n \"Error handling notification\",\n metadata: [\n \"method\": \"\\(message.method)\",\n \"error\": \"\\(error)\",\n ])\n }\n }\n }\n\n // MARK: -\n\n /// Validate the server capabilities.\n /// Throws an error if the client is configured to be strict and the capability is not supported.\n private func validateServerCapability(\n _ keyPath: KeyPath,\n _ name: String\n )\n throws\n {\n if configuration.strict {\n guard let capabilities = serverCapabilities else {\n throw MCPError.methodNotFound(\"Server capabilities not initialized\")\n }\n guard capabilities[keyPath: keyPath] != nil else {\n throw MCPError.methodNotFound(\"\\(name) is not supported by the server\")\n }\n }\n }\n\n // Add handler for batch responses\n private func handleBatchResponse(_ responses: [AnyResponse]) async {\n await logger?.trace(\"Processing batch response\", metadata: [\"count\": \"\\(responses.count)\"])\n for response in responses {\n // Attempt to remove the pending request.\n // If successful, pendingRequest contains the request.\n if let pendingRequest = self.removePendingRequest(id: response.id) {\n // If we successfully removed it, handle the response using the pending request.\n switch response.result {\n case .success(let value):\n pendingRequest.resume(returning: value)\n case .failure(let error):\n pendingRequest.resume(throwing: error)\n }\n } else {\n // If removal failed, it means the request ID was not found (or already handled).\n // Log a warning.\n await logger?.warning(\n \"Received response in batch for unknown or already handled request ID\",\n metadata: [\"id\": \"\\(response.id)\"]\n )\n }\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Server/Server.swift", "import Logging\n\nimport struct Foundation.Data\nimport struct Foundation.Date\nimport class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\n/// Model Context Protocol server\npublic actor Server {\n /// The server configuration\n public struct Configuration: Hashable, Codable, Sendable {\n /// The default configuration.\n public static let `default` = Configuration(strict: false)\n\n /// The strict configuration.\n public static let strict = Configuration(strict: true)\n\n /// When strict mode is enabled, the server:\n /// - Requires clients to send an initialize request before any other requests\n /// - Rejects all requests from uninitialized clients with a protocol error\n ///\n /// While the MCP specification requires clients to initialize the connection\n /// before sending other requests, some implementations may not follow this.\n /// Disabling strict mode allows the server to be more lenient with non-compliant\n /// clients, though this may lead to undefined behavior.\n public var strict: Bool\n }\n\n /// Implementation information\n public struct Info: Hashable, Codable, Sendable {\n /// The server name\n public let name: String\n /// The server version\n public let version: String\n\n public init(name: String, version: String) {\n self.name = name\n self.version = version\n }\n }\n\n /// Server capabilities\n public struct Capabilities: Hashable, Codable, Sendable {\n /// Resources capabilities\n public struct Resources: Hashable, Codable, Sendable {\n /// Whether the resource can be subscribed to\n public var subscribe: Bool?\n /// Whether the list of resources has changed\n public var listChanged: Bool?\n\n public init(\n subscribe: Bool? = nil,\n listChanged: Bool? = nil\n ) {\n self.subscribe = subscribe\n self.listChanged = listChanged\n }\n }\n\n /// Tools capabilities\n public struct Tools: Hashable, Codable, Sendable {\n /// Whether the server notifies clients when tools change\n public var listChanged: Bool?\n\n public init(listChanged: Bool? = nil) {\n self.listChanged = listChanged\n }\n }\n\n /// Prompts capabilities\n public struct Prompts: Hashable, Codable, Sendable {\n /// Whether the server notifies clients when prompts change\n public var listChanged: Bool?\n\n public init(listChanged: Bool? = nil) {\n self.listChanged = listChanged\n }\n }\n\n /// Logging capabilities\n public struct Logging: Hashable, Codable, Sendable {\n public init() {}\n }\n\n /// Sampling capabilities\n public struct Sampling: Hashable, Codable, Sendable {\n public init() {}\n }\n\n /// Logging capabilities\n public var logging: Logging?\n /// Prompts capabilities\n public var prompts: Prompts?\n /// Resources capabilities\n public var resources: Resources?\n /// Sampling capabilities\n public var sampling: Sampling?\n /// Tools capabilities\n public var tools: Tools?\n\n public init(\n logging: Logging? = nil,\n prompts: Prompts? = nil,\n resources: Resources? = nil,\n sampling: Sampling? = nil,\n tools: Tools? = nil\n ) {\n self.logging = logging\n self.prompts = prompts\n self.resources = resources\n self.sampling = sampling\n self.tools = tools\n }\n }\n\n /// Server information\n private let serverInfo: Server.Info\n /// The server connection\n private var connection: (any Transport)?\n /// The server logger\n private var logger: Logger? {\n get async {\n await connection?.logger\n }\n }\n\n /// The server name\n public nonisolated var name: String { serverInfo.name }\n /// The server version\n public nonisolated var version: String { serverInfo.version }\n /// The server capabilities\n public var capabilities: Capabilities\n /// The server configuration\n public var configuration: Configuration\n\n /// Request handlers\n private var methodHandlers: [String: RequestHandlerBox] = [:]\n /// Notification handlers\n private var notificationHandlers: [String: [NotificationHandlerBox]] = [:]\n\n /// Whether the server is initialized\n private var isInitialized = false\n /// The client information\n private var clientInfo: Client.Info?\n /// The client capabilities\n private var clientCapabilities: Client.Capabilities?\n /// The protocol version\n private var protocolVersion: String?\n /// The list of subscriptions\n private var subscriptions: [String: Set] = [:]\n /// The task for the message handling loop\n private var task: Task?\n\n public init(\n name: String,\n version: String,\n capabilities: Server.Capabilities = .init(),\n configuration: Configuration = .default\n ) {\n self.serverInfo = Server.Info(name: name, version: version)\n self.capabilities = capabilities\n self.configuration = configuration\n }\n\n /// Start the server\n /// - Parameters:\n /// - transport: The transport to use for the server\n /// - initializeHook: An optional hook that runs when the client sends an initialize request\n public func start(\n transport: any Transport,\n initializeHook: (@Sendable (Client.Info, Client.Capabilities) async throws -> Void)? = nil\n ) async throws {\n self.connection = transport\n registerDefaultHandlers(initializeHook: initializeHook)\n try await transport.connect()\n\n await logger?.info(\n \"Server started\", metadata: [\"name\": \"\\(name)\", \"version\": \"\\(version)\"])\n\n // Start message handling loop\n task = Task {\n do {\n let stream = await transport.receive()\n for try await data in stream {\n if Task.isCancelled { break } // Check cancellation inside loop\n\n var requestID: ID?\n do {\n // Attempt to decode as batch first, then as individual request or notification\n let decoder = JSONDecoder()\n if let batch = try? decoder.decode(Server.Batch.self, from: data) {\n try await handleBatch(batch)\n } else if let request = try? decoder.decode(AnyRequest.self, from: data) {\n _ = try await handleRequest(request, sendResponse: true)\n } else if let message = try? decoder.decode(AnyMessage.self, from: data) {\n try await handleMessage(message)\n } else {\n // Try to extract request ID from raw JSON if possible\n if let json = try? JSONDecoder().decode(\n [String: Value].self, from: data),\n let idValue = json[\"id\"]\n {\n if let strValue = idValue.stringValue {\n requestID = .string(strValue)\n } else if let intValue = idValue.intValue {\n requestID = .number(intValue)\n }\n }\n throw MCPError.parseError(\"Invalid message format\")\n }\n } catch let error where MCPError.isResourceTemporarilyUnavailable(error) {\n // Resource temporarily unavailable, retry after a short delay\n try? await Task.sleep(for: .milliseconds(10))\n continue\n } catch {\n await logger?.error(\n \"Error processing message\", metadata: [\"error\": \"\\(error)\"])\n let response = AnyMethod.response(\n id: requestID ?? .random,\n error: error as? MCPError\n ?? MCPError.internalError(error.localizedDescription)\n )\n try? await send(response)\n }\n }\n } catch {\n await logger?.error(\n \"Fatal error in message handling loop\", metadata: [\"error\": \"\\(error)\"])\n }\n await logger?.info(\"Server finished\", metadata: [:])\n }\n }\n\n /// Stop the server\n public func stop() async {\n task?.cancel()\n task = nil\n if let connection = connection {\n await connection.disconnect()\n }\n connection = nil\n }\n\n public func waitUntilCompleted() async {\n await task?.value\n }\n\n // MARK: - Registration\n\n /// Register a method handler\n @discardableResult\n public func withMethodHandler(\n _ type: M.Type,\n handler: @escaping @Sendable (M.Parameters) async throws -> M.Result\n ) -> Self {\n methodHandlers[M.name] = TypedRequestHandler { (request: Request) -> Response in\n let result = try await handler(request.params)\n return Response(id: request.id, result: result)\n }\n return self\n }\n\n /// Register a notification handler\n @discardableResult\n public func onNotification(\n _ type: N.Type,\n handler: @escaping @Sendable (Message) async throws -> Void\n ) -> Self {\n let handlers = notificationHandlers[N.name, default: []]\n notificationHandlers[N.name] = handlers + [TypedNotificationHandler(handler)]\n return self\n }\n\n // MARK: - Sending\n\n /// Send a response to a request\n public func send(_ response: Response) async throws {\n guard let connection = connection else {\n throw MCPError.internalError(\"Server connection not initialized\")\n }\n\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]\n\n let responseData = try encoder.encode(response)\n try await connection.send(responseData)\n }\n\n /// Send a notification to connected clients\n public func notify(_ notification: Message) async throws {\n guard let connection = connection else {\n throw MCPError.internalError(\"Server connection not initialized\")\n }\n\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]\n\n let notificationData = try encoder.encode(notification)\n try await connection.send(notificationData)\n }\n\n // MARK: - Sampling\n\n /// Request sampling from the connected client\n ///\n /// Sampling allows servers to request LLM completions through the client,\n /// enabling sophisticated agentic behaviors while maintaining human-in-the-loop control.\n ///\n /// The sampling flow follows these steps:\n /// 1. Server sends a `sampling/createMessage` request to the client\n /// 2. Client reviews the request and can modify it\n /// 3. Client samples from an LLM\n /// 4. Client reviews the completion\n /// 5. Client returns the result to the server\n ///\n /// - Parameters:\n /// - messages: The conversation history to send to the LLM\n /// - modelPreferences: Model selection preferences\n /// - systemPrompt: Optional system prompt\n /// - includeContext: What MCP context to include\n /// - temperature: Controls randomness (0.0 to 1.0)\n /// - maxTokens: Maximum tokens to generate\n /// - stopSequences: Array of sequences that stop generation\n /// - metadata: Additional provider-specific parameters\n /// - Returns: The sampling result containing the model used, stop reason, role, and content\n /// - Throws: MCPError if the request fails\n /// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/sampling#how-sampling-works\n public func requestSampling(\n messages: [Sampling.Message],\n modelPreferences: Sampling.ModelPreferences? = nil,\n systemPrompt: String? = nil,\n includeContext: Sampling.ContextInclusion? = nil,\n temperature: Double? = nil,\n maxTokens: Int,\n stopSequences: [String]? = nil,\n metadata: [String: Value]? = nil\n ) async throws -> CreateSamplingMessage.Result {\n guard connection != nil else {\n throw MCPError.internalError(\"Server connection not initialized\")\n }\n\n // Note: This is a conceptual implementation. The actual implementation would require\n // bidirectional communication support in the transport layer, allowing servers to\n // send requests to clients and receive responses.\n\n _ = CreateSamplingMessage.request(\n .init(\n messages: messages,\n modelPreferences: modelPreferences,\n systemPrompt: systemPrompt,\n includeContext: includeContext,\n temperature: temperature,\n maxTokens: maxTokens,\n stopSequences: stopSequences,\n metadata: metadata\n )\n )\n\n // This would need to be implemented with proper request/response handling\n // similar to how the client sends requests to servers\n throw MCPError.internalError(\n \"Bidirectional sampling requests not yet implemented in transport layer\")\n }\n\n /// A JSON-RPC batch containing multiple requests and/or notifications\n struct Batch: Sendable {\n /// An item in a JSON-RPC batch\n enum Item: Sendable {\n case request(Request)\n case notification(Message)\n\n }\n\n var items: [Item]\n\n init(items: [Item]) {\n self.items = items\n }\n }\n\n /// Process a batch of requests and/or notifications\n private func handleBatch(_ batch: Batch) async throws {\n await logger?.trace(\"Processing batch request\", metadata: [\"size\": \"\\(batch.items.count)\"])\n\n if batch.items.isEmpty {\n // Empty batch is invalid according to JSON-RPC spec\n let error = MCPError.invalidRequest(\"Batch array must not be empty\")\n let response = AnyMethod.response(id: .random, error: error)\n try await send(response)\n return\n }\n\n // Process each item in the batch and collect responses\n var responses: [Response] = []\n\n for item in batch.items {\n do {\n switch item {\n case .request(let request):\n // For batched requests, collect responses instead of sending immediately\n if let response = try await handleRequest(request, sendResponse: false) {\n responses.append(response)\n }\n\n case .notification(let notification):\n // Handle notification (no response needed)\n try await handleMessage(notification)\n }\n } catch {\n // Only add errors to response for requests (notifications don't have responses)\n if case .request(let request) = item {\n let mcpError =\n error as? MCPError ?? MCPError.internalError(error.localizedDescription)\n responses.append(AnyMethod.response(id: request.id, error: mcpError))\n }\n }\n }\n\n // Send collected responses if any\n if !responses.isEmpty {\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]\n let responseData = try encoder.encode(responses)\n\n guard let connection = connection else {\n throw MCPError.internalError(\"Server connection not initialized\")\n }\n\n try await connection.send(responseData)\n }\n }\n\n // MARK: - Request and Message Handling\n\n /// Handle a request and either send the response immediately or return it\n ///\n /// - Parameters:\n /// - request: The request to handle\n /// - sendResponse: Whether to send the response immediately (true) or return it (false)\n /// - Returns: The response when sendResponse is false\n private func handleRequest(_ request: Request, sendResponse: Bool = true)\n async throws -> Response?\n {\n // Check if this is a pre-processed error request (empty method)\n if request.method.isEmpty && !sendResponse {\n // This is a placeholder for an invalid request that couldn't be parsed in batch mode\n return AnyMethod.response(\n id: request.id,\n error: MCPError.invalidRequest(\"Invalid batch item format\")\n )\n }\n\n await logger?.trace(\n \"Processing request\",\n metadata: [\n \"method\": \"\\(request.method)\",\n \"id\": \"\\(request.id)\",\n ])\n\n if configuration.strict {\n // The client SHOULD NOT send requests other than pings\n // before the server has responded to the initialize request.\n switch request.method {\n case Initialize.name, Ping.name:\n break\n default:\n try checkInitialized()\n }\n }\n\n // Find handler for method name\n guard let handler = methodHandlers[request.method] else {\n let error = MCPError.methodNotFound(\"Unknown method: \\(request.method)\")\n let response = AnyMethod.response(id: request.id, error: error)\n\n if sendResponse {\n try await send(response)\n return nil\n }\n\n return response\n }\n\n do {\n // Handle request and get response\n let response = try await handler(request)\n\n if sendResponse {\n try await send(response)\n return nil\n }\n\n return response\n } catch {\n let mcpError = error as? MCPError ?? MCPError.internalError(error.localizedDescription)\n let response = AnyMethod.response(id: request.id, error: mcpError)\n\n if sendResponse {\n try await send(response)\n return nil\n }\n\n return response\n }\n }\n\n private func handleMessage(_ message: Message) async throws {\n await logger?.trace(\n \"Processing notification\",\n metadata: [\"method\": \"\\(message.method)\"])\n\n if configuration.strict {\n // Check initialization state unless this is an initialized notification\n if message.method != InitializedNotification.name {\n try checkInitialized()\n }\n }\n\n // Find notification handlers for this method\n guard let handlers = notificationHandlers[message.method] else { return }\n\n // Convert notification parameters to concrete type and call handlers\n for handler in handlers {\n do {\n try await handler(message)\n } catch {\n await logger?.error(\n \"Error handling notification\",\n metadata: [\n \"method\": \"\\(message.method)\",\n \"error\": \"\\(error)\",\n ])\n }\n }\n }\n\n private func checkInitialized() throws {\n guard isInitialized else {\n throw MCPError.invalidRequest(\"Server is not initialized\")\n }\n }\n\n private func registerDefaultHandlers(\n initializeHook: (@Sendable (Client.Info, Client.Capabilities) async throws -> Void)?\n ) {\n // Initialize\n withMethodHandler(Initialize.self) { [weak self] params in\n guard let self = self else {\n throw MCPError.internalError(\"Server was deallocated\")\n }\n\n guard await !self.isInitialized else {\n throw MCPError.invalidRequest(\"Server is already initialized\")\n }\n\n // Call initialization hook if registered\n if let hook = initializeHook {\n try await hook(params.clientInfo, params.capabilities)\n }\n\n // Perform version negotiation\n let clientRequestedVersion = params.protocolVersion\n let negotiatedProtocolVersion = Version.negotiate(\n clientRequestedVersion: clientRequestedVersion)\n\n // Set initial state with the negotiated protocol version\n await self.setInitialState(\n clientInfo: params.clientInfo,\n clientCapabilities: params.capabilities,\n protocolVersion: negotiatedProtocolVersion\n )\n\n return Initialize.Result(\n protocolVersion: negotiatedProtocolVersion,\n capabilities: await self.capabilities,\n serverInfo: self.serverInfo,\n instructions: nil\n )\n }\n\n // Ping\n withMethodHandler(Ping.self) { _ in return Empty() }\n }\n\n private func setInitialState(\n clientInfo: Client.Info,\n clientCapabilities: Client.Capabilities,\n protocolVersion: String\n ) async {\n self.clientInfo = clientInfo\n self.clientCapabilities = clientCapabilities\n self.protocolVersion = protocolVersion\n self.isInitialized = true\n }\n}\n\nextension Server.Batch: Codable {\n init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n\n let encoder = JSONEncoder()\n let decoder = JSONDecoder()\n\n var items: [Item] = []\n for item in try container.decode([Value].self) {\n let data = try encoder.encode(item)\n try items.append(decoder.decode(Item.self, from: data))\n }\n\n self.items = items\n }\n\n func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n try container.encode(items)\n }\n}\n\nextension Server.Batch.Item: Codable {\n private enum CodingKeys: String, CodingKey {\n case id\n }\n\n init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n // Check if it's a request (has id) or notification (no id)\n if container.contains(.id) {\n self = .request(try Request(from: decoder))\n } else {\n self = .notification(try Message(from: decoder))\n }\n }\n\n func encode(to encoder: Encoder) throws {\n switch self {\n case .request(let request):\n try request.encode(to: encoder)\n case .notification(let notification):\n try notification.encode(to: encoder)\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Error.swift", "import Foundation\n\n#if canImport(System)\n import System\n#else\n @preconcurrency import SystemPackage\n#endif\n\n/// A model context protocol error.\npublic enum MCPError: Swift.Error, Sendable {\n // Standard JSON-RPC 2.0 errors (-32700 to -32603)\n case parseError(String?) // -32700\n case invalidRequest(String?) // -32600\n case methodNotFound(String?) // -32601\n case invalidParams(String?) // -32602\n case internalError(String?) // -32603\n\n // Server errors (-32000 to -32099)\n case serverError(code: Int, message: String)\n\n // Transport specific errors\n case connectionClosed\n case transportError(Swift.Error)\n\n /// The JSON-RPC 2.0 error code\n public var code: Int {\n switch self {\n case .parseError: return -32700\n case .invalidRequest: return -32600\n case .methodNotFound: return -32601\n case .invalidParams: return -32602\n case .internalError: return -32603\n case .serverError(let code, _): return code\n case .connectionClosed: return -32000\n case .transportError: return -32001\n }\n }\n\n /// Check if an error represents a \"resource temporarily unavailable\" condition\n public static func isResourceTemporarilyUnavailable(_ error: Swift.Error) -> Bool {\n #if canImport(System)\n if let errno = error as? System.Errno, errno == .resourceTemporarilyUnavailable {\n return true\n }\n #else\n if let errno = error as? SystemPackage.Errno, errno == .resourceTemporarilyUnavailable {\n return true\n }\n #endif\n return false\n }\n}\n\n// MARK: LocalizedError\n\nextension MCPError: LocalizedError {\n public var errorDescription: String? {\n switch self {\n case .parseError(let detail):\n return \"Parse error: Invalid JSON\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .invalidRequest(let detail):\n return \"Invalid Request\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .methodNotFound(let detail):\n return \"Method not found\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .invalidParams(let detail):\n return \"Invalid params\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .internalError(let detail):\n return \"Internal error\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .serverError(_, let message):\n return \"Server error: \\(message)\"\n case .connectionClosed:\n return \"Connection closed\"\n case .transportError(let error):\n return \"Transport error: \\(error.localizedDescription)\"\n }\n }\n\n public var failureReason: String? {\n switch self {\n case .parseError:\n return \"The server received invalid JSON that could not be parsed\"\n case .invalidRequest:\n return \"The JSON sent is not a valid Request object\"\n case .methodNotFound:\n return \"The method does not exist or is not available\"\n case .invalidParams:\n return \"Invalid method parameter(s)\"\n case .internalError:\n return \"Internal JSON-RPC error\"\n case .serverError:\n return \"Server-defined error occurred\"\n case .connectionClosed:\n return \"The connection to the server was closed\"\n case .transportError(let error):\n return (error as? LocalizedError)?.failureReason ?? error.localizedDescription\n }\n }\n\n public var recoverySuggestion: String? {\n switch self {\n case .parseError:\n return \"Verify that the JSON being sent is valid and well-formed\"\n case .invalidRequest:\n return \"Ensure the request follows the JSON-RPC 2.0 specification format\"\n case .methodNotFound:\n return \"Check the method name and ensure it is supported by the server\"\n case .invalidParams:\n return \"Verify the parameters match the method's expected parameters\"\n case .connectionClosed:\n return \"Try reconnecting to the server\"\n default:\n return nil\n }\n }\n}\n\n// MARK: CustomDebugStringConvertible\n\nextension MCPError: CustomDebugStringConvertible {\n public var debugDescription: String {\n switch self {\n case .transportError(let error):\n return\n \"[\\(code)] \\(errorDescription ?? \"\") (Underlying error: \\(String(reflecting: error)))\"\n default:\n return \"[\\(code)] \\(errorDescription ?? \"\")\"\n }\n }\n\n}\n\n// MARK: Codable\n\nextension MCPError: Codable {\n private enum CodingKeys: String, CodingKey {\n case code, message, data\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(code, forKey: .code)\n try container.encode(errorDescription ?? \"Unknown error\", forKey: .message)\n\n // Encode additional data if available\n switch self {\n case .parseError(let detail),\n .invalidRequest(let detail),\n .methodNotFound(let detail),\n .invalidParams(let detail),\n .internalError(let detail):\n if let detail = detail {\n try container.encode([\"detail\": detail], forKey: .data)\n }\n case .serverError(_, _):\n // No additional data for server errors\n break\n case .connectionClosed:\n break\n case .transportError(let error):\n try container.encode(\n [\"error\": error.localizedDescription],\n forKey: .data\n )\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let code = try container.decode(Int.self, forKey: .code)\n let message = try container.decode(String.self, forKey: .message)\n let data = try container.decodeIfPresent([String: Value].self, forKey: .data)\n\n // Helper to extract detail from data, falling back to message if needed\n let unwrapDetail: (String?) -> String? = { fallback in\n guard let detailValue = data?[\"detail\"] else { return fallback }\n if case .string(let str) = detailValue { return str }\n return fallback\n }\n\n switch code {\n case -32700:\n self = .parseError(unwrapDetail(message))\n case -32600:\n self = .invalidRequest(unwrapDetail(message))\n case -32601:\n self = .methodNotFound(unwrapDetail(message))\n case -32602:\n self = .invalidParams(unwrapDetail(message))\n case -32603:\n self = .internalError(unwrapDetail(nil))\n case -32000:\n self = .connectionClosed\n case -32001:\n // Extract underlying error string if present\n let underlyingErrorString =\n data?[\"error\"].flatMap { val -> String? in\n if case .string(let str) = val { return str }\n return nil\n } ?? message\n self = .transportError(\n NSError(\n domain: \"org.jsonrpc.error\",\n code: code,\n userInfo: [NSLocalizedDescriptionKey: underlyingErrorString]\n )\n )\n default:\n self = .serverError(code: code, message: message)\n }\n }\n}\n\n// MARK: Equatable\n\nextension MCPError: Equatable {\n public static func == (lhs: MCPError, rhs: MCPError) -> Bool {\n lhs.code == rhs.code\n }\n}\n\n// MARK: Hashable\n\nextension MCPError: Hashable {\n public func hash(into hasher: inout Hasher) {\n hasher.combine(code)\n switch self {\n case .parseError(let detail):\n hasher.combine(detail)\n case .invalidRequest(let detail):\n hasher.combine(detail)\n case .methodNotFound(let detail):\n hasher.combine(detail)\n case .invalidParams(let detail):\n hasher.combine(detail)\n case .internalError(let detail):\n hasher.combine(detail)\n case .serverError(_, let message):\n hasher.combine(message)\n case .connectionClosed:\n break\n case .transportError(let error):\n hasher.combine(error.localizedDescription)\n }\n }\n}\n\n// MARK: -\n\n/// This is provided to allow existing code that uses `MCP.Error` to continue\n/// to work without modification.\n///\n/// The MCPError type is now the recommended way to handle errors in MCP.\n@available(*, deprecated, renamed: \"MCPError\", message: \"Use MCPError instead of MCP.Error\")\npublic typealias Error = MCPError\n"], ["/swift-sdk/Sources/MCP/Base/Messages.swift", "import class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\nprivate let jsonrpc = \"2.0\"\n\npublic protocol NotRequired {\n init()\n}\n\npublic struct Empty: NotRequired, Hashable, Codable, Sendable {\n public init() {}\n}\n\nextension Value: NotRequired {\n public init() {\n self = .null\n }\n}\n\n// MARK: -\n\n/// A method that can be used to send requests and receive responses.\npublic protocol Method {\n /// The parameters of the method.\n associatedtype Parameters: Codable, Hashable, Sendable = Empty\n /// The result of the method.\n associatedtype Result: Codable, Hashable, Sendable = Empty\n /// The name of the method.\n static var name: String { get }\n}\n\n/// Type-erased method for request/response handling\nstruct AnyMethod: Method, Sendable {\n static var name: String { \"\" }\n typealias Parameters = Value\n typealias Result = Value\n}\n\nextension Method where Parameters == Empty {\n public static func request(id: ID = .random) -> Request {\n Request(id: id, method: name, params: Empty())\n }\n}\n\nextension Method where Result == Empty {\n public static func response(id: ID) -> Response {\n Response(id: id, result: Empty())\n }\n}\n\nextension Method {\n /// Create a request with the given parameters.\n public static func request(id: ID = .random, _ parameters: Self.Parameters) -> Request {\n Request(id: id, method: name, params: parameters)\n }\n\n /// Create a response with the given result.\n public static func response(id: ID, result: Self.Result) -> Response {\n Response(id: id, result: result)\n }\n\n /// Create a response with the given error.\n public static func response(id: ID, error: MCPError) -> Response {\n Response(id: id, error: error)\n }\n}\n\n// MARK: -\n\n/// A request message.\npublic struct Request: Hashable, Identifiable, Codable, Sendable {\n /// The request ID.\n public let id: ID\n /// The method name.\n public let method: String\n /// The request parameters.\n public let params: M.Parameters\n\n init(id: ID = .random, method: String, params: M.Parameters) {\n self.id = id\n self.method = method\n self.params = params\n }\n\n private enum CodingKeys: String, CodingKey {\n case jsonrpc, id, method, params\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(jsonrpc, forKey: .jsonrpc)\n try container.encode(id, forKey: .id)\n try container.encode(method, forKey: .method)\n try container.encode(params, forKey: .params)\n }\n}\n\nextension Request {\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let version = try container.decode(String.self, forKey: .jsonrpc)\n guard version == jsonrpc else {\n throw DecodingError.dataCorruptedError(\n forKey: .jsonrpc, in: container, debugDescription: \"Invalid JSON-RPC version\")\n }\n id = try container.decode(ID.self, forKey: .id)\n method = try container.decode(String.self, forKey: .method)\n\n if M.Parameters.self is NotRequired.Type {\n // For NotRequired parameters, use decodeIfPresent or init()\n params =\n (try container.decodeIfPresent(M.Parameters.self, forKey: .params)\n ?? (M.Parameters.self as! NotRequired.Type).init() as! M.Parameters)\n } else if let value = try? container.decode(M.Parameters.self, forKey: .params) {\n // If params exists and can be decoded, use it\n params = value\n } else if !container.contains(.params)\n || (try? container.decodeNil(forKey: .params)) == true\n {\n // If params is missing or explicitly null, use Empty for Empty parameters\n // or throw for non-Empty parameters\n if M.Parameters.self == Empty.self {\n params = Empty() as! M.Parameters\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Missing required params field\"))\n }\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Invalid params field\"))\n }\n }\n}\n\n/// A type-erased request for request/response handling\ntypealias AnyRequest = Request\n\nextension AnyRequest {\n init(_ request: Request) throws {\n let encoder = JSONEncoder()\n let decoder = JSONDecoder()\n\n let data = try encoder.encode(request)\n self = try decoder.decode(AnyRequest.self, from: data)\n }\n}\n\n/// A box for request handlers that can be type-erased\nclass RequestHandlerBox: @unchecked Sendable {\n func callAsFunction(_ request: AnyRequest) async throws -> AnyResponse {\n fatalError(\"Must override\")\n }\n}\n\n/// A typed request handler that can be used to handle requests of a specific type\nfinal class TypedRequestHandler: RequestHandlerBox, @unchecked Sendable {\n private let _handle: @Sendable (Request) async throws -> Response\n\n init(_ handler: @escaping @Sendable (Request) async throws -> Response) {\n self._handle = handler\n super.init()\n }\n\n override func callAsFunction(_ request: AnyRequest) async throws -> AnyResponse {\n let encoder = JSONEncoder()\n let decoder = JSONDecoder()\n\n // Create a concrete request from the type-erased one\n let data = try encoder.encode(request)\n let request = try decoder.decode(Request.self, from: data)\n\n // Handle with concrete type\n let response = try await _handle(request)\n\n // Convert result to AnyMethod response\n switch response.result {\n case .success(let result):\n let resultData = try encoder.encode(result)\n let resultValue = try decoder.decode(Value.self, from: resultData)\n return Response(id: response.id, result: resultValue)\n case .failure(let error):\n return Response(id: response.id, error: error)\n }\n }\n}\n\n// MARK: -\n\n/// A response message.\npublic struct Response: Hashable, Identifiable, Codable, Sendable {\n /// The response ID.\n public let id: ID\n /// The response result.\n public let result: Swift.Result\n\n public init(id: ID, result: M.Result) {\n self.id = id\n self.result = .success(result)\n }\n\n public init(id: ID, error: MCPError) {\n self.id = id\n self.result = .failure(error)\n }\n\n private enum CodingKeys: String, CodingKey {\n case jsonrpc, id, result, error\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(jsonrpc, forKey: .jsonrpc)\n try container.encode(id, forKey: .id)\n switch result {\n case .success(let result):\n try container.encode(result, forKey: .result)\n case .failure(let error):\n try container.encode(error, forKey: .error)\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let version = try container.decode(String.self, forKey: .jsonrpc)\n guard version == jsonrpc else {\n throw DecodingError.dataCorruptedError(\n forKey: .jsonrpc, in: container, debugDescription: \"Invalid JSON-RPC version\")\n }\n id = try container.decode(ID.self, forKey: .id)\n if let result = try? container.decode(M.Result.self, forKey: .result) {\n self.result = .success(result)\n } else if let error = try? container.decode(MCPError.self, forKey: .error) {\n self.result = .failure(error)\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Invalid response\"))\n }\n }\n}\n\n/// A type-erased response for request/response handling\ntypealias AnyResponse = Response\n\nextension AnyResponse {\n init(_ response: Response) throws {\n // Instead of re-encoding/decoding which might double-wrap the error,\n // directly transfer the properties\n self.id = response.id\n switch response.result {\n case .success(let result):\n // For success, we still need to convert the result to a Value\n let data = try JSONEncoder().encode(result)\n let resultValue = try JSONDecoder().decode(Value.self, from: data)\n self.result = .success(resultValue)\n case .failure(let error):\n // Keep the original error without re-encoding/decoding\n self.result = .failure(error)\n }\n }\n}\n\n// MARK: -\n\n/// A notification message.\npublic protocol Notification: Hashable, Codable, Sendable {\n /// The parameters of the notification.\n associatedtype Parameters: Hashable, Codable, Sendable = Empty\n /// The name of the notification.\n static var name: String { get }\n}\n\n/// A type-erased notification for message handling\nstruct AnyNotification: Notification, Sendable {\n static var name: String { \"\" }\n typealias Parameters = Value\n}\n\nextension AnyNotification {\n init(_ notification: some Notification) throws {\n let encoder = JSONEncoder()\n let decoder = JSONDecoder()\n\n let data = try encoder.encode(notification)\n self = try decoder.decode(AnyNotification.self, from: data)\n }\n}\n\n/// A message that can be used to send notifications.\npublic struct Message: Hashable, Codable, Sendable {\n /// The method name.\n public let method: String\n /// The notification parameters.\n public let params: N.Parameters\n\n public init(method: String, params: N.Parameters) {\n self.method = method\n self.params = params\n }\n\n private enum CodingKeys: String, CodingKey {\n case jsonrpc, method, params\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(jsonrpc, forKey: .jsonrpc)\n try container.encode(method, forKey: .method)\n if N.Parameters.self != Empty.self {\n try container.encode(params, forKey: .params)\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let version = try container.decode(String.self, forKey: .jsonrpc)\n guard version == jsonrpc else {\n throw DecodingError.dataCorruptedError(\n forKey: .jsonrpc, in: container, debugDescription: \"Invalid JSON-RPC version\")\n }\n method = try container.decode(String.self, forKey: .method)\n\n if N.Parameters.self is NotRequired.Type {\n // For NotRequired parameters, use decodeIfPresent or init()\n params =\n (try container.decodeIfPresent(N.Parameters.self, forKey: .params)\n ?? (N.Parameters.self as! NotRequired.Type).init() as! N.Parameters)\n } else if let value = try? container.decode(N.Parameters.self, forKey: .params) {\n // If params exists and can be decoded, use it\n params = value\n } else if !container.contains(.params)\n || (try? container.decodeNil(forKey: .params)) == true\n {\n // If params is missing or explicitly null, use Empty for Empty parameters\n // or throw for non-Empty parameters\n if N.Parameters.self == Empty.self {\n params = Empty() as! N.Parameters\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Missing required params field\"))\n }\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Invalid params field\"))\n }\n }\n}\n\n/// A type-erased message for message handling\ntypealias AnyMessage = Message\n\nextension Notification where Parameters == Empty {\n /// Create a message with empty parameters.\n public static func message() -> Message {\n Message(method: name, params: Empty())\n }\n}\n\nextension Notification {\n /// Create a message with the given parameters.\n public static func message(_ parameters: Parameters) -> Message {\n Message(method: name, params: parameters)\n }\n}\n\n/// A box for notification handlers that can be type-erased\nclass NotificationHandlerBox: @unchecked Sendable {\n func callAsFunction(_ notification: Message) async throws {}\n}\n\n/// A typed notification handler that can be used to handle notifications of a specific type\nfinal class TypedNotificationHandler: NotificationHandlerBox,\n @unchecked Sendable\n{\n private let _handle: @Sendable (Message) async throws -> Void\n\n init(_ handler: @escaping @Sendable (Message) async throws -> Void) {\n self._handle = handler\n super.init()\n }\n\n override func callAsFunction(_ notification: Message) async throws {\n // Create a concrete notification from the type-erased one\n let data = try JSONEncoder().encode(notification)\n let typedNotification = try JSONDecoder().decode(Message.self, from: data)\n\n try await _handle(typedNotification)\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Value.swift", "import struct Foundation.Data\nimport class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\n/// A codable value.\npublic enum Value: Hashable, Sendable {\n case null\n case bool(Bool)\n case int(Int)\n case double(Double)\n case string(String)\n case data(mimeType: String? = nil, Data)\n case array([Value])\n case object([String: Value])\n\n /// Create a `Value` from a `Codable` value.\n /// - Parameter value: The codable value\n /// - Returns: A value\n public init(_ value: T) throws {\n if let valueAsValue = value as? Value {\n self = valueAsValue\n } else {\n let data = try JSONEncoder().encode(value)\n self = try JSONDecoder().decode(Value.self, from: data)\n }\n }\n\n /// Returns whether the value is `null`.\n public var isNull: Bool {\n return self == .null\n }\n\n /// Returns the `Bool` value if the value is a `bool`,\n /// otherwise returns `nil`.\n public var boolValue: Bool? {\n guard case let .bool(value) = self else { return nil }\n return value\n }\n\n /// Returns the `Int` value if the value is an `integer`,\n /// otherwise returns `nil`.\n public var intValue: Int? {\n guard case let .int(value) = self else { return nil }\n return value\n }\n\n /// Returns the `Double` value if the value is a `double`,\n /// otherwise returns `nil`.\n public var doubleValue: Double? {\n guard case let .double(value) = self else { return nil }\n return value\n }\n\n /// Returns the `String` value if the value is a `string`,\n /// otherwise returns `nil`.\n public var stringValue: String? {\n guard case let .string(value) = self else { return nil }\n return value\n }\n\n /// Returns the data value and optional MIME type if the value is `data`,\n /// otherwise returns `nil`.\n public var dataValue: (mimeType: String?, Data)? {\n guard case let .data(mimeType: mimeType, data) = self else { return nil }\n return (mimeType: mimeType, data)\n }\n\n /// Returns the `[Value]` value if the value is an `array`,\n /// otherwise returns `nil`.\n public var arrayValue: [Value]? {\n guard case let .array(value) = self else { return nil }\n return value\n }\n\n /// Returns the `[String: Value]` value if the value is an `object`,\n /// otherwise returns `nil`.\n public var objectValue: [String: Value]? {\n guard case let .object(value) = self else { return nil }\n return value\n }\n}\n\n// MARK: - Codable\n\nextension Value: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n\n if container.decodeNil() {\n self = .null\n } else if let value = try? container.decode(Bool.self) {\n self = .bool(value)\n } else if let value = try? container.decode(Int.self) {\n self = .int(value)\n } else if let value = try? container.decode(Double.self) {\n self = .double(value)\n } else if let value = try? container.decode(String.self) {\n if Data.isDataURL(string: value),\n case let (mimeType, data)? = Data.parseDataURL(value)\n {\n self = .data(mimeType: mimeType, data)\n } else {\n self = .string(value)\n }\n } else if let value = try? container.decode([Value].self) {\n self = .array(value)\n } else if let value = try? container.decode([String: Value].self) {\n self = .object(value)\n } else {\n throw DecodingError.dataCorruptedError(\n in: container, debugDescription: \"Value type not found\")\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n\n switch self {\n case .null:\n try container.encodeNil()\n case .bool(let value):\n try container.encode(value)\n case .int(let value):\n try container.encode(value)\n case .double(let value):\n try container.encode(value)\n case .string(let value):\n try container.encode(value)\n case let .data(mimeType, value):\n try container.encode(value.dataURLEncoded(mimeType: mimeType))\n case .array(let value):\n try container.encode(value)\n case .object(let value):\n try container.encode(value)\n }\n }\n}\n\nextension Value: CustomStringConvertible {\n public var description: String {\n switch self {\n case .null:\n return \"\"\n case .bool(let value):\n return value.description\n case .int(let value):\n return value.description\n case .double(let value):\n return value.description\n case .string(let value):\n return value.description\n case let .data(mimeType, value):\n return value.dataURLEncoded(mimeType: mimeType)\n case .array(let value):\n return value.description\n case .object(let value):\n return value.description\n }\n }\n}\n\n// MARK: - ExpressibleByNilLiteral\n\nextension Value: ExpressibleByNilLiteral {\n public init(nilLiteral: ()) {\n self = .null\n }\n}\n\n// MARK: - ExpressibleByBooleanLiteral\n\nextension Value: ExpressibleByBooleanLiteral {\n public init(booleanLiteral value: Bool) {\n self = .bool(value)\n }\n}\n\n// MARK: - ExpressibleByIntegerLiteral\n\nextension Value: ExpressibleByIntegerLiteral {\n public init(integerLiteral value: Int) {\n self = .int(value)\n }\n}\n\n// MARK: - ExpressibleByFloatLiteral\n\nextension Value: ExpressibleByFloatLiteral {\n public init(floatLiteral value: Double) {\n self = .double(value)\n }\n}\n\n// MARK: - ExpressibleByStringLiteral\n\nextension Value: ExpressibleByStringLiteral {\n public init(stringLiteral value: String) {\n self = .string(value)\n }\n}\n\n// MARK: - ExpressibleByArrayLiteral\n\nextension Value: ExpressibleByArrayLiteral {\n public init(arrayLiteral elements: Value...) {\n self = .array(elements)\n }\n}\n\n// MARK: - ExpressibleByDictionaryLiteral\n\nextension Value: ExpressibleByDictionaryLiteral {\n public init(dictionaryLiteral elements: (String, Value)...) {\n var dictionary: [String: Value] = [:]\n for (key, value) in elements {\n dictionary[key] = value\n }\n self = .object(dictionary)\n }\n}\n\n// MARK: - ExpressibleByStringInterpolation\n\nextension Value: ExpressibleByStringInterpolation {\n public struct StringInterpolation: StringInterpolationProtocol {\n var stringValue: String\n\n public init(literalCapacity: Int, interpolationCount: Int) {\n self.stringValue = \"\"\n self.stringValue.reserveCapacity(literalCapacity + interpolationCount)\n }\n\n public mutating func appendLiteral(_ literal: String) {\n self.stringValue.append(literal)\n }\n\n public mutating func appendInterpolation(_ value: T) {\n self.stringValue.append(value.description)\n }\n }\n\n public init(stringInterpolation: StringInterpolation) {\n self = .string(stringInterpolation.stringValue)\n }\n}\n\n// MARK: - Standard Library Type Extensions\n\nextension Bool {\n /// Creates a boolean value from a `Value` instance.\n ///\n /// In strict mode, only `.bool` values are converted. In non-strict mode, the following conversions are supported:\n /// - Integers: `1` is `true`, `0` is `false`\n /// - Doubles: `1.0` is `true`, `0.0` is `false`\n /// - Strings (lowercase only):\n /// - `true`: \"true\", \"t\", \"yes\", \"y\", \"on\", \"1\"\n /// - `false`: \"false\", \"f\", \"no\", \"n\", \"off\", \"0\"\n ///\n /// - Parameters:\n /// - value: The `Value` to convert\n /// - strict: When `true`, only converts from `.bool` values. Defaults to `true`\n /// - Returns: A boolean value if conversion is possible, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// Bool(Value.bool(true)) // Returns true\n /// Bool(Value.int(1), strict: false) // Returns true\n /// Bool(Value.string(\"yes\"), strict: false) // Returns true\n /// ```\n public init?(_ value: Value, strict: Bool = true) {\n switch value {\n case .bool(let b):\n self = b\n case .int(let i) where !strict:\n switch i {\n case 0: self = false\n case 1: self = true\n default: return nil\n }\n case .double(let d) where !strict:\n switch d {\n case 0.0: self = false\n case 1.0: self = true\n default: return nil\n }\n case .string(let s) where !strict:\n switch s {\n case \"true\", \"t\", \"yes\", \"y\", \"on\", \"1\":\n self = true\n case \"false\", \"f\", \"no\", \"n\", \"off\", \"0\":\n self = false\n default:\n return nil\n }\n default:\n return nil\n }\n }\n}\n\nextension Int {\n /// Creates an integer value from a `Value` instance.\n ///\n /// In strict mode, only `.int` values are converted. In non-strict mode, the following conversions are supported:\n /// - Doubles: Converted if they can be represented exactly as integers\n /// - Strings: Parsed if they contain a valid integer representation\n ///\n /// - Parameters:\n /// - value: The `Value` to convert\n /// - strict: When `true`, only converts from `.int` values. Defaults to `true`\n /// - Returns: An integer value if conversion is possible, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// Int(Value.int(42)) // Returns 42\n /// Int(Value.double(42.0), strict: false) // Returns 42\n /// Int(Value.string(\"42\"), strict: false) // Returns 42\n /// Int(Value.double(42.5), strict: false) // Returns nil\n /// ```\n public init?(_ value: Value, strict: Bool = true) {\n switch value {\n case .int(let i):\n self = i\n case .double(let d) where !strict:\n guard let intValue = Int(exactly: d) else { return nil }\n self = intValue\n case .string(let s) where !strict:\n guard let intValue = Int(s) else { return nil }\n self = intValue\n default:\n return nil\n }\n }\n}\n\nextension Double {\n /// Creates a double value from a `Value` instance.\n ///\n /// In strict mode, converts from `.double` and `.int` values. In non-strict mode, the following conversions are supported:\n /// - Integers: Converted to their double representation\n /// - Strings: Parsed if they contain a valid floating-point representation\n ///\n /// - Parameters:\n /// - value: The `Value` to convert\n /// - strict: When `true`, only converts from `.double` and `.int` values. Defaults to `true`\n /// - Returns: A double value if conversion is possible, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// Double(Value.double(42.5)) // Returns 42.5\n /// Double(Value.int(42)) // Returns 42.0\n /// Double(Value.string(\"42.5\"), strict: false) // Returns 42.5\n /// ```\n public init?(_ value: Value, strict: Bool = true) {\n switch value {\n case .double(let d):\n self = d\n case .int(let i):\n self = Double(i)\n case .string(let s) where !strict:\n guard let doubleValue = Double(s) else { return nil }\n self = doubleValue\n default:\n return nil\n }\n }\n}\n\nextension String {\n /// Creates a string value from a `Value` instance.\n ///\n /// In strict mode, only `.string` values are converted. In non-strict mode, the following conversions are supported:\n /// - Integers: Converted to their string representation\n /// - Doubles: Converted to their string representation\n /// - Booleans: Converted to \"true\" or \"false\"\n ///\n /// - Parameters:\n /// - value: The `Value` to convert\n /// - strict: When `true`, only converts from `.string` values. Defaults to `true`\n /// - Returns: A string value if conversion is possible, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// String(Value.string(\"hello\")) // Returns \"hello\"\n /// String(Value.int(42), strict: false) // Returns \"42\"\n /// String(Value.bool(true), strict: false) // Returns \"true\"\n /// ```\n public init?(_ value: Value, strict: Bool = true) {\n switch value {\n case .string(let s):\n self = s\n case .int(let i) where !strict:\n self = String(i)\n case .double(let d) where !strict:\n self = String(d)\n case .bool(let b) where !strict:\n self = String(b)\n default:\n return nil\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Extensions/Data+Extensions.swift", "import Foundation\nimport RegexBuilder\n\nextension Data {\n /// Regex pattern for data URLs\n @inline(__always) private static var dataURLRegex:\n Regex<(Substring, Substring, Substring?, Substring)>\n {\n Regex {\n \"data:\"\n Capture {\n ZeroOrMore(.reluctant) {\n CharacterClass.anyOf(\",;\").inverted\n }\n }\n Optionally {\n \";charset=\"\n Capture {\n OneOrMore(.reluctant) {\n CharacterClass.anyOf(\",;\").inverted\n }\n }\n }\n Optionally { \";base64\" }\n \",\"\n Capture {\n ZeroOrMore { .any }\n }\n }\n }\n\n /// Checks if a given string is a valid data URL.\n ///\n /// - Parameter string: The string to check.\n /// - Returns: `true` if the string is a valid data URL, otherwise `false`.\n /// - SeeAlso: [RFC 2397](https://www.rfc-editor.org/rfc/rfc2397.html)\n public static func isDataURL(string: String) -> Bool {\n return string.wholeMatch(of: dataURLRegex) != nil\n }\n\n /// Parses a data URL string into its MIME type and data components.\n ///\n /// - Parameter string: The data URL string to parse.\n /// - Returns: A tuple containing the MIME type and decoded data, or `nil` if parsing fails.\n /// - SeeAlso: [RFC 2397](https://www.rfc-editor.org/rfc/rfc2397.html)\n public static func parseDataURL(_ string: String) -> (mimeType: String, data: Data)? {\n guard let match = string.wholeMatch(of: dataURLRegex) else {\n return nil\n }\n\n // Extract components using strongly typed captures\n let (_, mediatype, charset, encodedData) = match.output\n\n let isBase64 = string.contains(\";base64,\")\n\n // Process MIME type\n var mimeType = mediatype.isEmpty ? \"text/plain\" : String(mediatype)\n if let charset = charset, !charset.isEmpty, mimeType.starts(with: \"text/\") {\n mimeType += \";charset=\\(charset)\"\n }\n\n // Decode data\n let decodedData: Data\n if isBase64 {\n guard let base64Data = Data(base64Encoded: String(encodedData)) else { return nil }\n decodedData = base64Data\n } else {\n guard\n let percentDecodedData = String(encodedData).removingPercentEncoding?.data(\n using: .utf8)\n else { return nil }\n decodedData = percentDecodedData\n }\n\n return (mimeType: mimeType, data: decodedData)\n }\n\n /// Encodes the data as a data URL string with an optional MIME type.\n ///\n /// - Parameter mimeType: The MIME type of the data. If `nil`, \"text/plain\" will be used.\n /// - Returns: A data URL string representation of the data.\n /// - SeeAlso: [RFC 2397](https://www.rfc-editor.org/rfc/rfc2397.html)\n public func dataURLEncoded(mimeType: String? = nil) -> String {\n let base64Data = self.base64EncodedString()\n return \"data:\\(mimeType ?? \"text/plain\");base64,\\(base64Data)\"\n }\n}\n"], ["/swift-sdk/Sources/MCP/Server/Tools.swift", "import Foundation\n\n/// The Model Context Protocol (MCP) allows servers to expose tools\n/// that can be invoked by language models.\n/// Tools enable models to interact with external systems, such as\n/// querying databases, calling APIs, or performing computations.\n/// Each tool is uniquely identified by a name and includes metadata\n/// describing its schema.\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/\npublic struct Tool: Hashable, Codable, Sendable {\n /// The tool name\n public let name: String\n /// The tool description\n public let description: String\n /// The tool input schema\n public let inputSchema: Value?\n\n /// Annotations that provide display-facing and operational information for a Tool.\n ///\n /// - Note: All properties in `ToolAnnotations` are **hints**.\n /// They are not guaranteed to provide a faithful description of\n /// tool behavior (including descriptive properties like `title`).\n ///\n /// Clients should never make tool use decisions based on `ToolAnnotations`\n /// received from untrusted servers.\n public struct Annotations: Hashable, Codable, Sendable, ExpressibleByNilLiteral {\n /// A human-readable title for the tool\n public var title: String?\n\n /// If true, the tool may perform destructive updates to its environment.\n /// If false, the tool performs only additive updates.\n /// (This property is meaningful only when `readOnlyHint == false`)\n ///\n /// When unspecified, the implicit default is `true`.\n public var destructiveHint: Bool?\n\n /// If true, calling the tool repeatedly with the same arguments\n /// will have no additional effect on its environment.\n /// (This property is meaningful only when `readOnlyHint == false`)\n ///\n /// When unspecified, the implicit default is `false`.\n public var idempotentHint: Bool?\n\n /// If true, this tool may interact with an \"open world\" of external\n /// entities. If false, the tool's domain of interaction is closed.\n /// For example, the world of a web search tool is open, whereas that\n /// of a memory tool is not.\n ///\n /// When unspecified, the implicit default is `true`.\n public var openWorldHint: Bool?\n\n /// If true, the tool does not modify its environment.\n ///\n /// When unspecified, the implicit default is `false`.\n public var readOnlyHint: Bool?\n\n /// Returns true if all properties are nil\n public var isEmpty: Bool {\n title == nil && readOnlyHint == nil && destructiveHint == nil && idempotentHint == nil\n && openWorldHint == nil\n }\n\n public init(\n title: String? = nil,\n readOnlyHint: Bool? = nil,\n destructiveHint: Bool? = nil,\n idempotentHint: Bool? = nil,\n openWorldHint: Bool? = nil\n ) {\n self.title = title\n self.readOnlyHint = readOnlyHint\n self.destructiveHint = destructiveHint\n self.idempotentHint = idempotentHint\n self.openWorldHint = openWorldHint\n }\n\n /// Initialize an empty annotations object\n public init(nilLiteral: ()) {}\n }\n\n /// Annotations that provide display-facing and operational information\n public var annotations: Annotations\n\n /// Initialize a tool with a name, description, input schema, and annotations\n public init(\n name: String,\n description: String,\n inputSchema: Value? = nil,\n annotations: Annotations = nil\n ) {\n self.name = name\n self.description = description\n self.inputSchema = inputSchema\n self.annotations = annotations\n }\n\n /// Content types that can be returned by a tool\n public enum Content: Hashable, Codable, Sendable {\n /// Text content\n case text(String)\n /// Image content\n case image(data: String, mimeType: String, metadata: [String: String]?)\n /// Audio content\n case audio(data: String, mimeType: String)\n /// Embedded resource content\n case resource(uri: String, mimeType: String, text: String?)\n\n private enum CodingKeys: String, CodingKey {\n case type\n case text\n case image\n case resource\n case audio\n case uri\n case mimeType\n case data\n case metadata\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let type = try container.decode(String.self, forKey: .type)\n\n switch type {\n case \"text\":\n let text = try container.decode(String.self, forKey: .text)\n self = .text(text)\n case \"image\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n let metadata = try container.decodeIfPresent(\n [String: String].self, forKey: .metadata)\n self = .image(data: data, mimeType: mimeType, metadata: metadata)\n case \"audio\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n self = .audio(data: data, mimeType: mimeType)\n case \"resource\":\n let uri = try container.decode(String.self, forKey: .uri)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n let text = try container.decodeIfPresent(String.self, forKey: .text)\n self = .resource(uri: uri, mimeType: mimeType, text: text)\n default:\n throw DecodingError.dataCorruptedError(\n forKey: .type, in: container, debugDescription: \"Unknown tool content type\")\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n\n switch self {\n case .text(let text):\n try container.encode(\"text\", forKey: .type)\n try container.encode(text, forKey: .text)\n case .image(let data, let mimeType, let metadata):\n try container.encode(\"image\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n try container.encodeIfPresent(metadata, forKey: .metadata)\n case .audio(let data, let mimeType):\n try container.encode(\"audio\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n case .resource(let uri, let mimeType, let text):\n try container.encode(\"resource\", forKey: .type)\n try container.encode(uri, forKey: .uri)\n try container.encode(mimeType, forKey: .mimeType)\n try container.encodeIfPresent(text, forKey: .text)\n }\n }\n }\n\n private enum CodingKeys: String, CodingKey {\n case name\n case description\n case inputSchema\n case annotations\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n name = try container.decode(String.self, forKey: .name)\n description = try container.decode(String.self, forKey: .description)\n inputSchema = try container.decodeIfPresent(Value.self, forKey: .inputSchema)\n annotations =\n try container.decodeIfPresent(Tool.Annotations.self, forKey: .annotations) ?? .init()\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(name, forKey: .name)\n try container.encode(description, forKey: .description)\n if let schema = inputSchema {\n try container.encode(schema, forKey: .inputSchema)\n }\n if !annotations.isEmpty {\n try container.encode(annotations, forKey: .annotations)\n }\n }\n}\n\n// MARK: -\n\n/// To discover available tools, clients send a `tools/list` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/#listing-tools\npublic enum ListTools: Method {\n public static let name = \"tools/list\"\n\n public struct Parameters: NotRequired, Hashable, Codable, Sendable {\n public let cursor: String?\n\n public init() {\n self.cursor = nil\n }\n\n public init(cursor: String) {\n self.cursor = cursor\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let tools: [Tool]\n public let nextCursor: String?\n\n public init(tools: [Tool], nextCursor: String? = nil) {\n self.tools = tools\n self.nextCursor = nextCursor\n }\n }\n}\n\n/// To call a tool, clients send a `tools/call` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/#calling-tools\npublic enum CallTool: Method {\n public static let name = \"tools/call\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let name: String\n public let arguments: [String: Value]?\n\n public init(name: String, arguments: [String: Value]? = nil) {\n self.name = name\n self.arguments = arguments\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let content: [Tool.Content]\n public let isError: Bool?\n\n public init(content: [Tool.Content], isError: Bool? = nil) {\n self.content = content\n self.isError = isError\n }\n }\n}\n\n/// When the list of available tools changes, servers that declared the listChanged capability SHOULD send a notification:\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/#list-changed-notification\npublic struct ToolListChangedNotification: Notification {\n public static let name: String = \"notifications/tools/list_changed\"\n}\n"], ["/swift-sdk/Sources/MCP/Base/UnitInterval.swift", "/// A value constrained to the range 0.0 to 1.0, inclusive.\n///\n/// `UnitInterval` represents a normalized value that is guaranteed to be within\n/// the unit interval [0, 1]. This type is commonly used for representing\n/// priorities in sampling request model preferences.\n///\n/// The type provides safe initialization that returns `nil` for values outside\n/// the valid range, ensuring that all instances contain valid unit interval values.\n///\n/// - Example:\n/// ```swift\n/// let zero: UnitInterval = 0 // 0.0\n/// let half = UnitInterval(0.5)! // 0.5\n/// let one: UnitInterval = 1.0 // 1.0\n/// let invalid = UnitInterval(1.5) // nil\n/// ```\npublic struct UnitInterval: Hashable, Sendable {\n private let value: Double\n\n /// Creates a unit interval value from a `Double`.\n ///\n /// - Parameter value: A double value that must be in the range 0.0...1.0\n /// - Returns: A `UnitInterval` instance if the value is valid, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// let valid = UnitInterval(0.75) // Optional(0.75)\n /// let invalid = UnitInterval(-0.1) // nil\n /// let boundary = UnitInterval(1.0) // Optional(1.0)\n /// ```\n public init?(_ value: Double) {\n guard (0...1).contains(value) else { return nil }\n self.value = value\n }\n\n /// The underlying double value.\n ///\n /// This property provides access to the raw double value that is guaranteed\n /// to be within the range [0, 1].\n ///\n /// - Returns: The double value between 0.0 and 1.0, inclusive\n public var doubleValue: Double { value }\n}\n\n// MARK: - Comparable\n\nextension UnitInterval: Comparable {\n public static func < (lhs: UnitInterval, rhs: UnitInterval) -> Bool {\n lhs.value < rhs.value\n }\n}\n\n// MARK: - CustomStringConvertible\n\nextension UnitInterval: CustomStringConvertible {\n public var description: String { \"\\(value)\" }\n}\n\n// MARK: - Codable\n\nextension UnitInterval: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let doubleValue = try container.decode(Double.self)\n guard let interval = UnitInterval(doubleValue) else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: decoder.codingPath,\n debugDescription: \"Value \\(doubleValue) is not in range 0...1\")\n )\n }\n self = interval\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n try container.encode(value)\n }\n}\n\n// MARK: - ExpressibleByFloatLiteral\n\nextension UnitInterval: ExpressibleByFloatLiteral {\n /// Creates a unit interval from a floating-point literal.\n ///\n /// This initializer allows you to create `UnitInterval` instances using\n /// floating-point literals. The literal value must be in the range [0, 1]\n /// or a runtime error will occur.\n ///\n /// - Parameter value: A floating-point literal between 0.0 and 1.0\n ///\n /// - Warning: This initializer will crash if the literal is outside the valid range.\n /// Use the failable initializer `init(_:)` for runtime validation.\n ///\n /// - Example:\n /// ```swift\n /// let quarter: UnitInterval = 0.25\n /// let half: UnitInterval = 0.5\n /// ```\n public init(floatLiteral value: Double) {\n self.init(value)!\n }\n}\n\n// MARK: - ExpressibleByIntegerLiteral\n\nextension UnitInterval: ExpressibleByIntegerLiteral {\n /// Creates a unit interval from an integer literal.\n ///\n /// This initializer allows you to create `UnitInterval` instances using\n /// integer literals. Only the values 0 and 1 are valid.\n ///\n /// - Parameter value: An integer literal, either 0 or 1\n ///\n /// - Warning: This initializer will crash if the literal is outside the valid range.\n /// Use the failable initializer `init(_:)` for runtime validation.\n ///\n /// - Example:\n /// ```swift\n /// let zero: UnitInterval = 0\n /// let one: UnitInterval = 1\n /// ```\n public init(integerLiteral value: Int) {\n self.init(Double(value))!\n }\n}\n"], ["/swift-sdk/Sources/MCP/Client/Sampling.swift", "import Foundation\n\n/// The Model Context Protocol (MCP) allows servers to request LLM completions\n/// through the client, enabling sophisticated agentic behaviors while maintaining\n/// security and privacy.\n///\n/// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/sampling#how-sampling-works\npublic enum Sampling {\n /// A message in the conversation history.\n public struct Message: Hashable, Codable, Sendable {\n /// The message role\n public enum Role: String, Hashable, Codable, Sendable {\n /// A user message\n case user\n /// An assistant message\n case assistant\n }\n\n /// The message role\n public let role: Role\n /// The message content\n public let content: Content\n\n /// Creates a message with the specified role and content\n @available(\n *, deprecated, message: \"Use static factory methods .user(_:) or .assistant(_:) instead\"\n )\n public init(role: Role, content: Content) {\n self.role = role\n self.content = content\n }\n\n /// Private initializer for convenience methods to avoid deprecation warnings\n private init(_role role: Role, _content content: Content) {\n self.role = role\n self.content = content\n }\n\n /// Creates a user message with the specified content\n public static func user(_ content: Content) -> Message {\n return Message(_role: .user, _content: content)\n }\n\n /// Creates an assistant message with the specified content\n public static func assistant(_ content: Content) -> Message {\n return Message(_role: .assistant, _content: content)\n }\n\n /// Content types for sampling messages\n public enum Content: Hashable, Sendable {\n /// Text content\n case text(String)\n /// Image content\n case image(data: String, mimeType: String)\n }\n }\n\n /// Model preferences for sampling requests\n public struct ModelPreferences: Hashable, Codable, Sendable {\n /// Model hints for selection\n public struct Hint: Hashable, Codable, Sendable {\n /// Suggested model name/family\n public let name: String?\n\n public init(name: String? = nil) {\n self.name = name\n }\n }\n\n /// Array of model name suggestions that clients can use to select an appropriate model\n public let hints: [Hint]?\n /// Importance of minimizing costs (0-1 normalized)\n public let costPriority: UnitInterval?\n /// Importance of low latency response (0-1 normalized)\n public let speedPriority: UnitInterval?\n /// Importance of advanced model capabilities (0-1 normalized)\n public let intelligencePriority: UnitInterval?\n\n public init(\n hints: [Hint]? = nil,\n costPriority: UnitInterval? = nil,\n speedPriority: UnitInterval? = nil,\n intelligencePriority: UnitInterval? = nil\n ) {\n self.hints = hints\n self.costPriority = costPriority\n self.speedPriority = speedPriority\n self.intelligencePriority = intelligencePriority\n }\n }\n\n /// Context inclusion options for sampling requests\n public enum ContextInclusion: String, Hashable, Codable, Sendable {\n /// No additional context\n case none\n /// Include context from the requesting server\n case thisServer\n /// Include context from all connected MCP servers\n case allServers\n }\n\n /// Stop reason for sampling completion\n public enum StopReason: String, Hashable, Codable, Sendable {\n /// Natural end of turn\n case endTurn\n /// Hit a stop sequence\n case stopSequence\n /// Reached maximum tokens\n case maxTokens\n }\n}\n\n// MARK: - Codable\n\nextension Sampling.Message.Content: Codable {\n private enum CodingKeys: String, CodingKey {\n case type, text, data, mimeType\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let type = try container.decode(String.self, forKey: .type)\n\n switch type {\n case \"text\":\n let text = try container.decode(String.self, forKey: .text)\n self = .text(text)\n case \"image\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n self = .image(data: data, mimeType: mimeType)\n default:\n throw DecodingError.dataCorruptedError(\n forKey: .type, in: container,\n debugDescription: \"Unknown sampling message content type\")\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n\n switch self {\n case .text(let text):\n try container.encode(\"text\", forKey: .type)\n try container.encode(text, forKey: .text)\n case .image(let data, let mimeType):\n try container.encode(\"image\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n }\n }\n}\n\n// MARK: - ExpressibleByStringLiteral\n\nextension Sampling.Message.Content: ExpressibleByStringLiteral {\n public init(stringLiteral value: String) {\n self = .text(value)\n }\n}\n\n// MARK: - ExpressibleByStringInterpolation\n\nextension Sampling.Message.Content: ExpressibleByStringInterpolation {\n public init(stringInterpolation: DefaultStringInterpolation) {\n self = .text(String(stringInterpolation: stringInterpolation))\n }\n}\n\n// MARK: -\n\n/// To request sampling from a client, servers send a `sampling/createMessage` request.\n/// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/sampling#how-sampling-works\npublic enum CreateSamplingMessage: Method {\n public static let name = \"sampling/createMessage\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n /// The conversation history to send to the LLM\n public let messages: [Sampling.Message]\n /// Model selection preferences\n public let modelPreferences: Sampling.ModelPreferences?\n /// Optional system prompt\n public let systemPrompt: String?\n /// What MCP context to include\n public let includeContext: Sampling.ContextInclusion?\n /// Controls randomness (0.0 to 1.0)\n public let temperature: Double?\n /// Maximum tokens to generate\n public let maxTokens: Int\n /// Array of sequences that stop generation\n public let stopSequences: [String]?\n /// Additional provider-specific parameters\n public let metadata: [String: Value]?\n\n public init(\n messages: [Sampling.Message],\n modelPreferences: Sampling.ModelPreferences? = nil,\n systemPrompt: String? = nil,\n includeContext: Sampling.ContextInclusion? = nil,\n temperature: Double? = nil,\n maxTokens: Int,\n stopSequences: [String]? = nil,\n metadata: [String: Value]? = nil\n ) {\n self.messages = messages\n self.modelPreferences = modelPreferences\n self.systemPrompt = systemPrompt\n self.includeContext = includeContext\n self.temperature = temperature\n self.maxTokens = maxTokens\n self.stopSequences = stopSequences\n self.metadata = metadata\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n /// Name of the model used\n public let model: String\n /// Why sampling stopped\n public let stopReason: Sampling.StopReason?\n /// The role of the completion\n public let role: Sampling.Message.Role\n /// The completion content\n public let content: Sampling.Message.Content\n\n public init(\n model: String,\n stopReason: Sampling.StopReason? = nil,\n role: Sampling.Message.Role,\n content: Sampling.Message.Content\n ) {\n self.model = model\n self.stopReason = stopReason\n self.role = role\n self.content = content\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Server/Prompts.swift", "import Foundation\n\n/// The Model Context Protocol (MCP) provides a standardized way\n/// for servers to expose prompt templates to clients.\n/// Prompts allow servers to provide structured messages and instructions\n/// for interacting with language models.\n/// Clients can discover available prompts, retrieve their contents,\n/// and provide arguments to customize them.\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/\npublic struct Prompt: Hashable, Codable, Sendable {\n /// The prompt name\n public let name: String\n /// The prompt description\n public let description: String?\n /// The prompt arguments\n public let arguments: [Argument]?\n\n public init(name: String, description: String? = nil, arguments: [Argument]? = nil) {\n self.name = name\n self.description = description\n self.arguments = arguments\n }\n\n /// An argument for a prompt\n public struct Argument: Hashable, Codable, Sendable {\n /// The argument name\n public let name: String\n /// The argument description\n public let description: String?\n /// Whether the argument is required\n public let required: Bool?\n\n public init(name: String, description: String? = nil, required: Bool? = nil) {\n self.name = name\n self.description = description\n self.required = required\n }\n }\n\n /// A message in a prompt\n public struct Message: Hashable, Codable, Sendable {\n /// The message role\n public enum Role: String, Hashable, Codable, Sendable {\n /// A user message\n case user\n /// An assistant message\n case assistant\n }\n\n /// The message role\n public let role: Role\n /// The message content\n public let content: Content\n\n /// Creates a message with the specified role and content\n @available(\n *, deprecated, message: \"Use static factory methods .user(_:) or .assistant(_:) instead\"\n )\n public init(role: Role, content: Content) {\n self.role = role\n self.content = content\n }\n\n /// Private initializer for convenience methods to avoid deprecation warnings\n private init(_role role: Role, _content content: Content) {\n self.role = role\n self.content = content\n }\n\n /// Creates a user message with the specified content\n public static func user(_ content: Content) -> Message {\n return Message(_role: .user, _content: content)\n }\n\n /// Creates an assistant message with the specified content\n public static func assistant(_ content: Content) -> Message {\n return Message(_role: .assistant, _content: content)\n }\n\n /// Content types for messages\n public enum Content: Hashable, Sendable {\n /// Text content\n case text(text: String)\n /// Image content\n case image(data: String, mimeType: String)\n /// Audio content\n case audio(data: String, mimeType: String)\n /// Embedded resource content\n case resource(uri: String, mimeType: String, text: String?, blob: String?)\n }\n }\n\n /// Reference type for prompts\n public struct Reference: Hashable, Codable, Sendable {\n /// The prompt reference name\n public let name: String\n\n public init(name: String) {\n self.name = name\n }\n\n private enum CodingKeys: String, CodingKey {\n case type, name\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(\"ref/prompt\", forKey: .type)\n try container.encode(name, forKey: .name)\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n _ = try container.decode(String.self, forKey: .type)\n name = try container.decode(String.self, forKey: .name)\n }\n }\n}\n\n// MARK: - Codable\n\nextension Prompt.Message.Content: Codable {\n private enum CodingKeys: String, CodingKey {\n case type, text, data, mimeType, uri, blob\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n\n switch self {\n case .text(let text):\n try container.encode(\"text\", forKey: .type)\n try container.encode(text, forKey: .text)\n case .image(let data, let mimeType):\n try container.encode(\"image\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n case .audio(let data, let mimeType):\n try container.encode(\"audio\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n case .resource(let uri, let mimeType, let text, let blob):\n try container.encode(\"resource\", forKey: .type)\n try container.encode(uri, forKey: .uri)\n try container.encode(mimeType, forKey: .mimeType)\n try container.encodeIfPresent(text, forKey: .text)\n try container.encodeIfPresent(blob, forKey: .blob)\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let type = try container.decode(String.self, forKey: .type)\n\n switch type {\n case \"text\":\n let text = try container.decode(String.self, forKey: .text)\n self = .text(text: text)\n case \"image\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n self = .image(data: data, mimeType: mimeType)\n case \"audio\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n self = .audio(data: data, mimeType: mimeType)\n case \"resource\":\n let uri = try container.decode(String.self, forKey: .uri)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n let text = try container.decodeIfPresent(String.self, forKey: .text)\n let blob = try container.decodeIfPresent(String.self, forKey: .blob)\n self = .resource(uri: uri, mimeType: mimeType, text: text, blob: blob)\n default:\n throw DecodingError.dataCorruptedError(\n forKey: .type,\n in: container,\n debugDescription: \"Unknown content type\")\n }\n }\n}\n\n// MARK: - ExpressibleByStringLiteral\n\nextension Prompt.Message.Content: ExpressibleByStringLiteral {\n public init(stringLiteral value: String) {\n self = .text(text: value)\n }\n}\n\n// MARK: - ExpressibleByStringInterpolation\n\nextension Prompt.Message.Content: ExpressibleByStringInterpolation {\n public init(stringInterpolation: DefaultStringInterpolation) {\n self = .text(text: String(stringInterpolation: stringInterpolation))\n }\n}\n\n// MARK: -\n\n/// To retrieve available prompts, clients send a `prompts/list` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/#listing-prompts\npublic enum ListPrompts: Method {\n public static let name: String = \"prompts/list\"\n\n public struct Parameters: NotRequired, Hashable, Codable, Sendable {\n public let cursor: String?\n\n public init() {\n self.cursor = nil\n }\n\n public init(cursor: String) {\n self.cursor = cursor\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let prompts: [Prompt]\n public let nextCursor: String?\n\n public init(prompts: [Prompt], nextCursor: String? = nil) {\n self.prompts = prompts\n self.nextCursor = nextCursor\n }\n }\n}\n\n/// To retrieve a specific prompt, clients send a `prompts/get` request.\n/// Arguments may be auto-completed through the completion API.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/#getting-a-prompt\npublic enum GetPrompt: Method {\n public static let name: String = \"prompts/get\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let name: String\n public let arguments: [String: Value]?\n\n public init(name: String, arguments: [String: Value]? = nil) {\n self.name = name\n self.arguments = arguments\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let description: String?\n public let messages: [Prompt.Message]\n\n public init(description: String?, messages: [Prompt.Message]) {\n self.description = description\n self.messages = messages\n }\n }\n}\n\n/// When the list of available prompts changes, servers that declared the listChanged capability SHOULD send a notification.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/#list-changed-notification\npublic struct PromptListChangedNotification: Notification {\n public static let name: String = \"notifications/prompts/list_changed\"\n}\n"], ["/swift-sdk/Sources/MCP/Base/Transport.swift", "import Logging\n\nimport struct Foundation.Data\n\n/// Protocol defining the transport layer for MCP communication\npublic protocol Transport: Actor {\n var logger: Logger { get }\n\n /// Establishes connection with the transport\n func connect() async throws\n\n /// Disconnects from the transport\n func disconnect() async\n\n /// Sends data\n func send(_ data: Data) async throws\n\n /// Receives data in an async sequence\n func receive() -> AsyncThrowingStream\n}\n"], ["/swift-sdk/Sources/MCP/Server/Resources.swift", "import Foundation\n\n/// The Model Context Protocol (MCP) provides a standardized way\n/// for servers to expose resources to clients.\n/// Resources allow servers to share data that provides context to language models,\n/// such as files, database schemas, or application-specific information.\n/// Each resource is uniquely identified by a URI.\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/\npublic struct Resource: Hashable, Codable, Sendable {\n /// The resource name\n public var name: String\n /// The resource URI\n public var uri: String\n /// The resource description\n public var description: String?\n /// The resource MIME type\n public var mimeType: String?\n /// The resource metadata\n public var metadata: [String: String]?\n\n public init(\n name: String,\n uri: String,\n description: String? = nil,\n mimeType: String? = nil,\n metadata: [String: String]? = nil\n ) {\n self.name = name\n self.uri = uri\n self.description = description\n self.mimeType = mimeType\n self.metadata = metadata\n }\n\n /// Content of a resource.\n public struct Content: Hashable, Codable, Sendable {\n /// The resource URI\n public let uri: String\n /// The resource MIME type\n public let mimeType: String?\n /// The resource text content\n public let text: String?\n /// The resource binary content\n public let blob: String?\n\n public static func text(_ content: String, uri: String, mimeType: String? = nil) -> Self {\n .init(uri: uri, mimeType: mimeType, text: content)\n }\n\n public static func binary(_ data: Data, uri: String, mimeType: String? = nil) -> Self {\n .init(uri: uri, mimeType: mimeType, blob: data.base64EncodedString())\n }\n\n private init(uri: String, mimeType: String? = nil, text: String? = nil) {\n self.uri = uri\n self.mimeType = mimeType\n self.text = text\n self.blob = nil\n }\n\n private init(uri: String, mimeType: String? = nil, blob: String) {\n self.uri = uri\n self.mimeType = mimeType\n self.text = nil\n self.blob = blob\n }\n }\n\n /// A resource template.\n public struct Template: Hashable, Codable, Sendable {\n /// The URI template pattern\n public var uriTemplate: String\n /// The template name\n public var name: String\n /// The template description\n public var description: String?\n /// The resource MIME type\n public var mimeType: String?\n\n public init(\n uriTemplate: String,\n name: String,\n description: String? = nil,\n mimeType: String? = nil\n ) {\n self.uriTemplate = uriTemplate\n self.name = name\n self.description = description\n self.mimeType = mimeType\n }\n }\n}\n\n// MARK: -\n\n/// To discover available resources, clients send a `resources/list` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#listing-resources\npublic enum ListResources: Method {\n public static let name: String = \"resources/list\"\n\n public struct Parameters: NotRequired, Hashable, Codable, Sendable {\n public let cursor: String?\n\n public init() {\n self.cursor = nil\n }\n \n public init(cursor: String) {\n self.cursor = cursor\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let resources: [Resource]\n public let nextCursor: String?\n\n public init(resources: [Resource], nextCursor: String? = nil) {\n self.resources = resources\n self.nextCursor = nextCursor\n }\n }\n}\n\n/// To retrieve resource contents, clients send a `resources/read` request:\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#reading-resources\npublic enum ReadResource: Method {\n public static let name: String = \"resources/read\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let uri: String\n\n public init(uri: String) {\n self.uri = uri\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let contents: [Resource.Content]\n\n public init(contents: [Resource.Content]) {\n self.contents = contents\n }\n }\n}\n\n/// To discover available resource templates, clients send a `resources/templates/list` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#resource-templates\npublic enum ListResourceTemplates: Method {\n public static let name: String = \"resources/templates/list\"\n\n public struct Parameters: NotRequired, Hashable, Codable, Sendable {\n public let cursor: String?\n\n public init() {\n self.cursor = nil\n }\n \n public init(cursor: String) {\n self.cursor = cursor\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let templates: [Resource.Template]\n public let nextCursor: String?\n\n public init(templates: [Resource.Template], nextCursor: String? = nil) {\n self.templates = templates\n self.nextCursor = nextCursor\n }\n\n private enum CodingKeys: String, CodingKey {\n case templates = \"resourceTemplates\"\n case nextCursor\n }\n }\n}\n\n/// When the list of available resources changes, servers that declared the listChanged capability SHOULD send a notification.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#list-changed-notification\npublic struct ResourceListChangedNotification: Notification {\n public static let name: String = \"notifications/resources/list_changed\"\n\n public typealias Parameters = Empty\n}\n\n/// Clients can subscribe to specific resources and receive notifications when they change.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#subscriptions\npublic enum ResourceSubscribe: Method {\n public static let name: String = \"resources/subscribe\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let uri: String\n }\n\n public typealias Result = Empty\n}\n\n/// When a resource changes, servers that declared the updated capability SHOULD send a notification to subscribed clients.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#subscriptions\npublic struct ResourceUpdatedNotification: Notification {\n public static let name: String = \"notifications/resources/updated\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let uri: String\n\n public init(uri: String) {\n self.uri = uri\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Lifecycle.swift", "/// The initialization phase MUST be the first interaction between client and server.\n/// During this phase, the client and server:\n/// - Establish protocol version compatibility\n/// - Exchange and negotiate capabilities\n/// - Share implementation details\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle/#initialization\npublic enum Initialize: Method {\n public static let name: String = \"initialize\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let protocolVersion: String\n public let capabilities: Client.Capabilities\n public let clientInfo: Client.Info\n\n public init(\n protocolVersion: String = Version.latest,\n capabilities: Client.Capabilities,\n clientInfo: Client.Info\n ) {\n self.protocolVersion = protocolVersion\n self.capabilities = capabilities\n self.clientInfo = clientInfo\n }\n\n private enum CodingKeys: String, CodingKey {\n case protocolVersion, capabilities, clientInfo\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n protocolVersion =\n try container.decodeIfPresent(String.self, forKey: .protocolVersion)\n ?? Version.latest\n capabilities =\n try container.decodeIfPresent(Client.Capabilities.self, forKey: .capabilities)\n ?? .init()\n clientInfo =\n try container.decodeIfPresent(Client.Info.self, forKey: .clientInfo)\n ?? .init(name: \"unknown\", version: \"0.0.0\")\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let protocolVersion: String\n public let capabilities: Server.Capabilities\n public let serverInfo: Server.Info\n public let instructions: String?\n }\n}\n\n/// After successful initialization, the client MUST send an initialized notification to indicate it is ready to begin normal operations.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle/#initialization\npublic struct InitializedNotification: Notification {\n public static let name: String = \"notifications/initialized\"\n}\n"], ["/swift-sdk/Sources/MCP/Base/ID.swift", "import struct Foundation.UUID\n\n/// A unique identifier for a request.\npublic enum ID: Hashable, Sendable {\n /// A string ID.\n case string(String)\n\n /// A number ID.\n case number(Int)\n\n /// Generates a random string ID.\n public static var random: ID {\n return .string(UUID().uuidString)\n }\n}\n\n// MARK: - ExpressibleByStringLiteral\n\nextension ID: ExpressibleByStringLiteral {\n public init(stringLiteral value: String) {\n self = .string(value)\n }\n}\n\n// MARK: - ExpressibleByIntegerLiteral\n\nextension ID: ExpressibleByIntegerLiteral {\n public init(integerLiteral value: Int) {\n self = .number(value)\n }\n}\n\n// MARK: - CustomStringConvertible\n\nextension ID: CustomStringConvertible {\n public var description: String {\n switch self {\n case .string(let str): return str\n case .number(let num): return String(num)\n }\n }\n}\n\n// MARK: - Codable\n\nextension ID: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n if let string = try? container.decode(String.self) {\n self = .string(string)\n } else if let number = try? container.decode(Int.self) {\n self = .number(number)\n } else if container.decodeNil() {\n // Handle unspecified/null IDs as empty string\n self = .string(\"\")\n } else {\n throw DecodingError.dataCorruptedError(\n in: container, debugDescription: \"ID must be string or number\")\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n switch self {\n case .string(let str): try container.encode(str)\n case .number(let num): try container.encode(num)\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Versioning.swift", "import Foundation\n\n/// The Model Context Protocol uses string-based version identifiers\n/// following the format YYYY-MM-DD, to indicate\n/// the last date backwards incompatible changes were made.\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2025-03-26/\npublic enum Version {\n /// All protocol versions supported by this implementation, ordered from newest to oldest.\n static let supported: Set = [\n \"2025-03-26\",\n \"2024-11-05\",\n ]\n\n /// The latest protocol version supported by this implementation.\n public static let latest = supported.max()!\n\n /// Negotiates the protocol version based on the client's request and server's capabilities.\n /// - Parameter clientRequestedVersion: The protocol version requested by the client.\n /// - Returns: The negotiated protocol version. If the client's requested version is supported,\n /// that version is returned. Otherwise, the server's latest supported version is returned.\n static func negotiate(clientRequestedVersion: String) -> String {\n if supported.contains(clientRequestedVersion) {\n return clientRequestedVersion\n }\n return latest\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Utilities/Ping.swift", "/// The Model Context Protocol includes an optional ping mechanism that allows either party to verify that their counterpart is still responsive and the connection is alive.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/utilities/ping\npublic enum Ping: Method {\n public static let name: String = \"ping\"\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 03:25:14", "created_task_model": "DeepSeek-R1", "function_skeleton": "private func setNonBlocking ( fileDescriptor: FileDescriptor ) throws { }", "code_description": "This code segment functions to: Configure system resources for asynchronous operation by modifying their access modes while performing error checking and platform compatibility enforcement during the configuration process."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```swift\n[TASK_BEGIN]\nprivate func setNonBlocking(fileDescriptor: FileDescriptor) throws {\n let currentFlags = try fileDescriptor.getStatusFlags()\n try fileDescriptor.setStatusFlags(currentFlags.union(.nonBlocking))\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 03-26-00"}, "editdistance_info": {"edit_distance": 11.3475, "calculate_time": "2025-08-21 03:26:00", "true_code_clean": "private func setNonBlocking(fileDescriptor: FileDescriptor) throws {\n #if canImport(Darwin) || canImport(Glibc)\n let flags = fcntl(fileDescriptor.rawValue, F_GETFL)\n guard flags >= 0 else {\n throw MCPError.transportError(Errno(rawValue: CInt(errno)))\n }\n let result = fcntl(fileDescriptor.rawValue, F_SETFL, flags | O_NONBLOCK)\n guard result >= 0 else {\n throw MCPError.transportError(Errno(rawValue: CInt(errno)))\n }\n #else\n throw MCPError.internalError(\n \"Setting non-blocking mode not supported on this platform\")\n #endif\n }", "predict_code_clean": "private func setNonBlocking(fileDescriptor: FileDescriptor) throws {\n let currentFlags = try fileDescriptor.getStatusFlags()\n try fileDescriptor.setStatusFlags(currentFlags.union(.nonBlocking))\n}"}} +{"repo_name": "swift-sdk", "file_name": "/swift-sdk/Sources/MCP/Base/Error.swift", "inference_info": {"prefix_code": "import Foundation\n\n#if canImport(System)\n import System\n#else\n @preconcurrency import SystemPackage\n#endif\n\n/// A model context protocol error.\npublic enum MCPError: Swift.Error, Sendable {\n // Standard JSON-RPC 2.0 errors (-32700 to -32603)\n case parseError(String?) // -32700\n case invalidRequest(String?) // -32600\n case methodNotFound(String?) // -32601\n case invalidParams(String?) // -32602\n case internalError(String?) // -32603\n\n // Server errors (-32000 to -32099)\n case serverError(code: Int, message: String)\n\n // Transport specific errors\n case connectionClosed\n case transportError(Swift.Error)\n\n /// The JSON-RPC 2.0 error code\n public var code: Int {\n switch self {\n case .parseError: return -32700\n case .invalidRequest: return -32600\n case .methodNotFound: return -32601\n case .invalidParams: return -32602\n case .internalError: return -32603\n case .serverError(let code, _): return code\n case .connectionClosed: return -32000\n case .transportError: return -32001\n }\n }\n\n /// Check if an error represents a \"resource temporarily unavailable\" condition\n public static func isResourceTemporarilyUnavailable(_ error: Swift.Error) -> Bool {\n #if canImport(System)\n if let errno = error as? System.Errno, errno == .resourceTemporarilyUnavailable {\n return true\n }\n #else\n if let errno = error as? SystemPackage.Errno, errno == .resourceTemporarilyUnavailable {\n return true\n }\n #endif\n return false\n }\n}\n\n// MARK: LocalizedError\n\nextension MCPError: LocalizedError {\n public var errorDescription: String? {\n switch self {\n case .parseError(let detail):\n return \"Parse error: Invalid JSON\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .invalidRequest(let detail):\n return \"Invalid Request\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .methodNotFound(let detail):\n return \"Method not found\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .invalidParams(let detail):\n return \"Invalid params\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .internalError(let detail):\n return \"Internal error\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .serverError(_, let message):\n return \"Server error: \\(message)\"\n case .connectionClosed:\n return \"Connection closed\"\n case .transportError(let error):\n return \"Transport error: \\(error.localizedDescription)\"\n }\n }\n\n public var failureReason: String? {\n switch self {\n case .parseError:\n return \"The server received invalid JSON that could not be parsed\"\n case .invalidRequest:\n return \"The JSON sent is not a valid Request object\"\n case .methodNotFound:\n return \"The method does not exist or is not available\"\n case .invalidParams:\n return \"Invalid method parameter(s)\"\n case .internalError:\n return \"Internal JSON-RPC error\"\n case .serverError:\n return \"Server-defined error occurred\"\n case .connectionClosed:\n return \"The connection to the server was closed\"\n case .transportError(let error):\n return (error as? LocalizedError)?.failureReason ?? error.localizedDescription\n }\n }\n\n public var recoverySuggestion: String? {\n switch self {\n case .parseError:\n return \"Verify that the JSON being sent is valid and well-formed\"\n case .invalidRequest:\n return \"Ensure the request follows the JSON-RPC 2.0 specification format\"\n case .methodNotFound:\n return \"Check the method name and ensure it is supported by the server\"\n case .invalidParams:\n return \"Verify the parameters match the method's expected parameters\"\n case .connectionClosed:\n return \"Try reconnecting to the server\"\n default:\n return nil\n }\n }\n}\n\n// MARK: CustomDebugStringConvertible\n\nextension MCPError: CustomDebugStringConvertible {\n public var debugDescription: String {\n switch self {\n case .transportError(let error):\n return\n \"[\\(code)] \\(errorDescription ?? \"\") (Underlying error: \\(String(reflecting: error)))\"\n default:\n return \"[\\(code)] \\(errorDescription ?? \"\")\"\n }\n }\n\n}\n\n// MARK: Codable\n\nextension MCPError: Codable {\n private enum CodingKeys: String, CodingKey {\n case code, message, data\n }\n\n ", "suffix_code": "\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let code = try container.decode(Int.self, forKey: .code)\n let message = try container.decode(String.self, forKey: .message)\n let data = try container.decodeIfPresent([String: Value].self, forKey: .data)\n\n // Helper to extract detail from data, falling back to message if needed\n let unwrapDetail: (String?) -> String? = { fallback in\n guard let detailValue = data?[\"detail\"] else { return fallback }\n if case .string(let str) = detailValue { return str }\n return fallback\n }\n\n switch code {\n case -32700:\n self = .parseError(unwrapDetail(message))\n case -32600:\n self = .invalidRequest(unwrapDetail(message))\n case -32601:\n self = .methodNotFound(unwrapDetail(message))\n case -32602:\n self = .invalidParams(unwrapDetail(message))\n case -32603:\n self = .internalError(unwrapDetail(nil))\n case -32000:\n self = .connectionClosed\n case -32001:\n // Extract underlying error string if present\n let underlyingErrorString =\n data?[\"error\"].flatMap { val -> String? in\n if case .string(let str) = val { return str }\n return nil\n } ?? message\n self = .transportError(\n NSError(\n domain: \"org.jsonrpc.error\",\n code: code,\n userInfo: [NSLocalizedDescriptionKey: underlyingErrorString]\n )\n )\n default:\n self = .serverError(code: code, message: message)\n }\n }\n}\n\n// MARK: Equatable\n\nextension MCPError: Equatable {\n public static func == (lhs: MCPError, rhs: MCPError) -> Bool {\n lhs.code == rhs.code\n }\n}\n\n// MARK: Hashable\n\nextension MCPError: Hashable {\n public func hash(into hasher: inout Hasher) {\n hasher.combine(code)\n switch self {\n case .parseError(let detail):\n hasher.combine(detail)\n case .invalidRequest(let detail):\n hasher.combine(detail)\n case .methodNotFound(let detail):\n hasher.combine(detail)\n case .invalidParams(let detail):\n hasher.combine(detail)\n case .internalError(let detail):\n hasher.combine(detail)\n case .serverError(_, let message):\n hasher.combine(message)\n case .connectionClosed:\n break\n case .transportError(let error):\n hasher.combine(error.localizedDescription)\n }\n }\n}\n\n// MARK: -\n\n/// This is provided to allow existing code that uses `MCP.Error` to continue\n/// to work without modification.\n///\n/// The MCPError type is now the recommended way to handle errors in MCP.\n@available(*, deprecated, renamed: \"MCPError\", message: \"Use MCPError instead of MCP.Error\")\npublic typealias Error = MCPError\n", "middle_code": "public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(code, forKey: .code)\n try container.encode(errorDescription ?? \"Unknown error\", forKey: .message)\n switch self {\n case .parseError(let detail),\n .invalidRequest(let detail),\n .methodNotFound(let detail),\n .invalidParams(let detail),\n .internalError(let detail):\n if let detail = detail {\n try container.encode([\"detail\": detail], forKey: .data)\n }\n case .serverError(_, _):\n break\n case .connectionClosed:\n break\n case .transportError(let error):\n try container.encode(\n [\"error\": error.localizedDescription],\n forKey: .data\n )\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "swift", "sub_task_type": null}, "context_code": [["/swift-sdk/Sources/MCP/Server/Server.swift", "import Logging\n\nimport struct Foundation.Data\nimport struct Foundation.Date\nimport class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\n/// Model Context Protocol server\npublic actor Server {\n /// The server configuration\n public struct Configuration: Hashable, Codable, Sendable {\n /// The default configuration.\n public static let `default` = Configuration(strict: false)\n\n /// The strict configuration.\n public static let strict = Configuration(strict: true)\n\n /// When strict mode is enabled, the server:\n /// - Requires clients to send an initialize request before any other requests\n /// - Rejects all requests from uninitialized clients with a protocol error\n ///\n /// While the MCP specification requires clients to initialize the connection\n /// before sending other requests, some implementations may not follow this.\n /// Disabling strict mode allows the server to be more lenient with non-compliant\n /// clients, though this may lead to undefined behavior.\n public var strict: Bool\n }\n\n /// Implementation information\n public struct Info: Hashable, Codable, Sendable {\n /// The server name\n public let name: String\n /// The server version\n public let version: String\n\n public init(name: String, version: String) {\n self.name = name\n self.version = version\n }\n }\n\n /// Server capabilities\n public struct Capabilities: Hashable, Codable, Sendable {\n /// Resources capabilities\n public struct Resources: Hashable, Codable, Sendable {\n /// Whether the resource can be subscribed to\n public var subscribe: Bool?\n /// Whether the list of resources has changed\n public var listChanged: Bool?\n\n public init(\n subscribe: Bool? = nil,\n listChanged: Bool? = nil\n ) {\n self.subscribe = subscribe\n self.listChanged = listChanged\n }\n }\n\n /// Tools capabilities\n public struct Tools: Hashable, Codable, Sendable {\n /// Whether the server notifies clients when tools change\n public var listChanged: Bool?\n\n public init(listChanged: Bool? = nil) {\n self.listChanged = listChanged\n }\n }\n\n /// Prompts capabilities\n public struct Prompts: Hashable, Codable, Sendable {\n /// Whether the server notifies clients when prompts change\n public var listChanged: Bool?\n\n public init(listChanged: Bool? = nil) {\n self.listChanged = listChanged\n }\n }\n\n /// Logging capabilities\n public struct Logging: Hashable, Codable, Sendable {\n public init() {}\n }\n\n /// Sampling capabilities\n public struct Sampling: Hashable, Codable, Sendable {\n public init() {}\n }\n\n /// Logging capabilities\n public var logging: Logging?\n /// Prompts capabilities\n public var prompts: Prompts?\n /// Resources capabilities\n public var resources: Resources?\n /// Sampling capabilities\n public var sampling: Sampling?\n /// Tools capabilities\n public var tools: Tools?\n\n public init(\n logging: Logging? = nil,\n prompts: Prompts? = nil,\n resources: Resources? = nil,\n sampling: Sampling? = nil,\n tools: Tools? = nil\n ) {\n self.logging = logging\n self.prompts = prompts\n self.resources = resources\n self.sampling = sampling\n self.tools = tools\n }\n }\n\n /// Server information\n private let serverInfo: Server.Info\n /// The server connection\n private var connection: (any Transport)?\n /// The server logger\n private var logger: Logger? {\n get async {\n await connection?.logger\n }\n }\n\n /// The server name\n public nonisolated var name: String { serverInfo.name }\n /// The server version\n public nonisolated var version: String { serverInfo.version }\n /// The server capabilities\n public var capabilities: Capabilities\n /// The server configuration\n public var configuration: Configuration\n\n /// Request handlers\n private var methodHandlers: [String: RequestHandlerBox] = [:]\n /// Notification handlers\n private var notificationHandlers: [String: [NotificationHandlerBox]] = [:]\n\n /// Whether the server is initialized\n private var isInitialized = false\n /// The client information\n private var clientInfo: Client.Info?\n /// The client capabilities\n private var clientCapabilities: Client.Capabilities?\n /// The protocol version\n private var protocolVersion: String?\n /// The list of subscriptions\n private var subscriptions: [String: Set] = [:]\n /// The task for the message handling loop\n private var task: Task?\n\n public init(\n name: String,\n version: String,\n capabilities: Server.Capabilities = .init(),\n configuration: Configuration = .default\n ) {\n self.serverInfo = Server.Info(name: name, version: version)\n self.capabilities = capabilities\n self.configuration = configuration\n }\n\n /// Start the server\n /// - Parameters:\n /// - transport: The transport to use for the server\n /// - initializeHook: An optional hook that runs when the client sends an initialize request\n public func start(\n transport: any Transport,\n initializeHook: (@Sendable (Client.Info, Client.Capabilities) async throws -> Void)? = nil\n ) async throws {\n self.connection = transport\n registerDefaultHandlers(initializeHook: initializeHook)\n try await transport.connect()\n\n await logger?.info(\n \"Server started\", metadata: [\"name\": \"\\(name)\", \"version\": \"\\(version)\"])\n\n // Start message handling loop\n task = Task {\n do {\n let stream = await transport.receive()\n for try await data in stream {\n if Task.isCancelled { break } // Check cancellation inside loop\n\n var requestID: ID?\n do {\n // Attempt to decode as batch first, then as individual request or notification\n let decoder = JSONDecoder()\n if let batch = try? decoder.decode(Server.Batch.self, from: data) {\n try await handleBatch(batch)\n } else if let request = try? decoder.decode(AnyRequest.self, from: data) {\n _ = try await handleRequest(request, sendResponse: true)\n } else if let message = try? decoder.decode(AnyMessage.self, from: data) {\n try await handleMessage(message)\n } else {\n // Try to extract request ID from raw JSON if possible\n if let json = try? JSONDecoder().decode(\n [String: Value].self, from: data),\n let idValue = json[\"id\"]\n {\n if let strValue = idValue.stringValue {\n requestID = .string(strValue)\n } else if let intValue = idValue.intValue {\n requestID = .number(intValue)\n }\n }\n throw MCPError.parseError(\"Invalid message format\")\n }\n } catch let error where MCPError.isResourceTemporarilyUnavailable(error) {\n // Resource temporarily unavailable, retry after a short delay\n try? await Task.sleep(for: .milliseconds(10))\n continue\n } catch {\n await logger?.error(\n \"Error processing message\", metadata: [\"error\": \"\\(error)\"])\n let response = AnyMethod.response(\n id: requestID ?? .random,\n error: error as? MCPError\n ?? MCPError.internalError(error.localizedDescription)\n )\n try? await send(response)\n }\n }\n } catch {\n await logger?.error(\n \"Fatal error in message handling loop\", metadata: [\"error\": \"\\(error)\"])\n }\n await logger?.info(\"Server finished\", metadata: [:])\n }\n }\n\n /// Stop the server\n public func stop() async {\n task?.cancel()\n task = nil\n if let connection = connection {\n await connection.disconnect()\n }\n connection = nil\n }\n\n public func waitUntilCompleted() async {\n await task?.value\n }\n\n // MARK: - Registration\n\n /// Register a method handler\n @discardableResult\n public func withMethodHandler(\n _ type: M.Type,\n handler: @escaping @Sendable (M.Parameters) async throws -> M.Result\n ) -> Self {\n methodHandlers[M.name] = TypedRequestHandler { (request: Request) -> Response in\n let result = try await handler(request.params)\n return Response(id: request.id, result: result)\n }\n return self\n }\n\n /// Register a notification handler\n @discardableResult\n public func onNotification(\n _ type: N.Type,\n handler: @escaping @Sendable (Message) async throws -> Void\n ) -> Self {\n let handlers = notificationHandlers[N.name, default: []]\n notificationHandlers[N.name] = handlers + [TypedNotificationHandler(handler)]\n return self\n }\n\n // MARK: - Sending\n\n /// Send a response to a request\n public func send(_ response: Response) async throws {\n guard let connection = connection else {\n throw MCPError.internalError(\"Server connection not initialized\")\n }\n\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]\n\n let responseData = try encoder.encode(response)\n try await connection.send(responseData)\n }\n\n /// Send a notification to connected clients\n public func notify(_ notification: Message) async throws {\n guard let connection = connection else {\n throw MCPError.internalError(\"Server connection not initialized\")\n }\n\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]\n\n let notificationData = try encoder.encode(notification)\n try await connection.send(notificationData)\n }\n\n // MARK: - Sampling\n\n /// Request sampling from the connected client\n ///\n /// Sampling allows servers to request LLM completions through the client,\n /// enabling sophisticated agentic behaviors while maintaining human-in-the-loop control.\n ///\n /// The sampling flow follows these steps:\n /// 1. Server sends a `sampling/createMessage` request to the client\n /// 2. Client reviews the request and can modify it\n /// 3. Client samples from an LLM\n /// 4. Client reviews the completion\n /// 5. Client returns the result to the server\n ///\n /// - Parameters:\n /// - messages: The conversation history to send to the LLM\n /// - modelPreferences: Model selection preferences\n /// - systemPrompt: Optional system prompt\n /// - includeContext: What MCP context to include\n /// - temperature: Controls randomness (0.0 to 1.0)\n /// - maxTokens: Maximum tokens to generate\n /// - stopSequences: Array of sequences that stop generation\n /// - metadata: Additional provider-specific parameters\n /// - Returns: The sampling result containing the model used, stop reason, role, and content\n /// - Throws: MCPError if the request fails\n /// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/sampling#how-sampling-works\n public func requestSampling(\n messages: [Sampling.Message],\n modelPreferences: Sampling.ModelPreferences? = nil,\n systemPrompt: String? = nil,\n includeContext: Sampling.ContextInclusion? = nil,\n temperature: Double? = nil,\n maxTokens: Int,\n stopSequences: [String]? = nil,\n metadata: [String: Value]? = nil\n ) async throws -> CreateSamplingMessage.Result {\n guard connection != nil else {\n throw MCPError.internalError(\"Server connection not initialized\")\n }\n\n // Note: This is a conceptual implementation. The actual implementation would require\n // bidirectional communication support in the transport layer, allowing servers to\n // send requests to clients and receive responses.\n\n _ = CreateSamplingMessage.request(\n .init(\n messages: messages,\n modelPreferences: modelPreferences,\n systemPrompt: systemPrompt,\n includeContext: includeContext,\n temperature: temperature,\n maxTokens: maxTokens,\n stopSequences: stopSequences,\n metadata: metadata\n )\n )\n\n // This would need to be implemented with proper request/response handling\n // similar to how the client sends requests to servers\n throw MCPError.internalError(\n \"Bidirectional sampling requests not yet implemented in transport layer\")\n }\n\n /// A JSON-RPC batch containing multiple requests and/or notifications\n struct Batch: Sendable {\n /// An item in a JSON-RPC batch\n enum Item: Sendable {\n case request(Request)\n case notification(Message)\n\n }\n\n var items: [Item]\n\n init(items: [Item]) {\n self.items = items\n }\n }\n\n /// Process a batch of requests and/or notifications\n private func handleBatch(_ batch: Batch) async throws {\n await logger?.trace(\"Processing batch request\", metadata: [\"size\": \"\\(batch.items.count)\"])\n\n if batch.items.isEmpty {\n // Empty batch is invalid according to JSON-RPC spec\n let error = MCPError.invalidRequest(\"Batch array must not be empty\")\n let response = AnyMethod.response(id: .random, error: error)\n try await send(response)\n return\n }\n\n // Process each item in the batch and collect responses\n var responses: [Response] = []\n\n for item in batch.items {\n do {\n switch item {\n case .request(let request):\n // For batched requests, collect responses instead of sending immediately\n if let response = try await handleRequest(request, sendResponse: false) {\n responses.append(response)\n }\n\n case .notification(let notification):\n // Handle notification (no response needed)\n try await handleMessage(notification)\n }\n } catch {\n // Only add errors to response for requests (notifications don't have responses)\n if case .request(let request) = item {\n let mcpError =\n error as? MCPError ?? MCPError.internalError(error.localizedDescription)\n responses.append(AnyMethod.response(id: request.id, error: mcpError))\n }\n }\n }\n\n // Send collected responses if any\n if !responses.isEmpty {\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]\n let responseData = try encoder.encode(responses)\n\n guard let connection = connection else {\n throw MCPError.internalError(\"Server connection not initialized\")\n }\n\n try await connection.send(responseData)\n }\n }\n\n // MARK: - Request and Message Handling\n\n /// Handle a request and either send the response immediately or return it\n ///\n /// - Parameters:\n /// - request: The request to handle\n /// - sendResponse: Whether to send the response immediately (true) or return it (false)\n /// - Returns: The response when sendResponse is false\n private func handleRequest(_ request: Request, sendResponse: Bool = true)\n async throws -> Response?\n {\n // Check if this is a pre-processed error request (empty method)\n if request.method.isEmpty && !sendResponse {\n // This is a placeholder for an invalid request that couldn't be parsed in batch mode\n return AnyMethod.response(\n id: request.id,\n error: MCPError.invalidRequest(\"Invalid batch item format\")\n )\n }\n\n await logger?.trace(\n \"Processing request\",\n metadata: [\n \"method\": \"\\(request.method)\",\n \"id\": \"\\(request.id)\",\n ])\n\n if configuration.strict {\n // The client SHOULD NOT send requests other than pings\n // before the server has responded to the initialize request.\n switch request.method {\n case Initialize.name, Ping.name:\n break\n default:\n try checkInitialized()\n }\n }\n\n // Find handler for method name\n guard let handler = methodHandlers[request.method] else {\n let error = MCPError.methodNotFound(\"Unknown method: \\(request.method)\")\n let response = AnyMethod.response(id: request.id, error: error)\n\n if sendResponse {\n try await send(response)\n return nil\n }\n\n return response\n }\n\n do {\n // Handle request and get response\n let response = try await handler(request)\n\n if sendResponse {\n try await send(response)\n return nil\n }\n\n return response\n } catch {\n let mcpError = error as? MCPError ?? MCPError.internalError(error.localizedDescription)\n let response = AnyMethod.response(id: request.id, error: mcpError)\n\n if sendResponse {\n try await send(response)\n return nil\n }\n\n return response\n }\n }\n\n private func handleMessage(_ message: Message) async throws {\n await logger?.trace(\n \"Processing notification\",\n metadata: [\"method\": \"\\(message.method)\"])\n\n if configuration.strict {\n // Check initialization state unless this is an initialized notification\n if message.method != InitializedNotification.name {\n try checkInitialized()\n }\n }\n\n // Find notification handlers for this method\n guard let handlers = notificationHandlers[message.method] else { return }\n\n // Convert notification parameters to concrete type and call handlers\n for handler in handlers {\n do {\n try await handler(message)\n } catch {\n await logger?.error(\n \"Error handling notification\",\n metadata: [\n \"method\": \"\\(message.method)\",\n \"error\": \"\\(error)\",\n ])\n }\n }\n }\n\n private func checkInitialized() throws {\n guard isInitialized else {\n throw MCPError.invalidRequest(\"Server is not initialized\")\n }\n }\n\n private func registerDefaultHandlers(\n initializeHook: (@Sendable (Client.Info, Client.Capabilities) async throws -> Void)?\n ) {\n // Initialize\n withMethodHandler(Initialize.self) { [weak self] params in\n guard let self = self else {\n throw MCPError.internalError(\"Server was deallocated\")\n }\n\n guard await !self.isInitialized else {\n throw MCPError.invalidRequest(\"Server is already initialized\")\n }\n\n // Call initialization hook if registered\n if let hook = initializeHook {\n try await hook(params.clientInfo, params.capabilities)\n }\n\n // Perform version negotiation\n let clientRequestedVersion = params.protocolVersion\n let negotiatedProtocolVersion = Version.negotiate(\n clientRequestedVersion: clientRequestedVersion)\n\n // Set initial state with the negotiated protocol version\n await self.setInitialState(\n clientInfo: params.clientInfo,\n clientCapabilities: params.capabilities,\n protocolVersion: negotiatedProtocolVersion\n )\n\n return Initialize.Result(\n protocolVersion: negotiatedProtocolVersion,\n capabilities: await self.capabilities,\n serverInfo: self.serverInfo,\n instructions: nil\n )\n }\n\n // Ping\n withMethodHandler(Ping.self) { _ in return Empty() }\n }\n\n private func setInitialState(\n clientInfo: Client.Info,\n clientCapabilities: Client.Capabilities,\n protocolVersion: String\n ) async {\n self.clientInfo = clientInfo\n self.clientCapabilities = clientCapabilities\n self.protocolVersion = protocolVersion\n self.isInitialized = true\n }\n}\n\nextension Server.Batch: Codable {\n init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n\n let encoder = JSONEncoder()\n let decoder = JSONDecoder()\n\n var items: [Item] = []\n for item in try container.decode([Value].self) {\n let data = try encoder.encode(item)\n try items.append(decoder.decode(Item.self, from: data))\n }\n\n self.items = items\n }\n\n func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n try container.encode(items)\n }\n}\n\nextension Server.Batch.Item: Codable {\n private enum CodingKeys: String, CodingKey {\n case id\n }\n\n init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n // Check if it's a request (has id) or notification (no id)\n if container.contains(.id) {\n self = .request(try Request(from: decoder))\n } else {\n self = .notification(try Message(from: decoder))\n }\n }\n\n func encode(to encoder: Encoder) throws {\n switch self {\n case .request(let request):\n try request.encode(to: encoder)\n case .notification(let notification):\n try notification.encode(to: encoder)\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Transports/HTTPClientTransport.swift", "import Foundation\nimport Logging\n\n#if !os(Linux)\n import EventSource\n#endif\n\n#if canImport(FoundationNetworking)\n import FoundationNetworking\n#endif\n\n/// An implementation of the MCP Streamable HTTP transport protocol for clients.\n///\n/// This transport implements the [Streamable HTTP transport](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http)\n/// specification from the Model Context Protocol.\n///\n/// It supports:\n/// - Sending JSON-RPC messages via HTTP POST requests\n/// - Receiving responses via both direct JSON responses and SSE streams\n/// - Session management using the `Mcp-Session-Id` header\n/// - Automatic reconnection for dropped SSE streams\n/// - Platform-specific optimizations for different operating systems\n///\n/// The transport supports two modes:\n/// - Regular HTTP (`streaming=false`): Simple request/response pattern\n/// - Streaming HTTP with SSE (`streaming=true`): Enables server-to-client push messages\n///\n/// - Important: Server-Sent Events (SSE) functionality is not supported on Linux platforms.\n///\n/// ## Example Usage\n///\n/// ```swift\n/// import MCP\n///\n/// // Create a streaming HTTP transport\n/// let transport = HTTPClientTransport(\n/// endpoint: URL(string: \"http://localhost:8080\")!,\n/// )\n///\n/// // Initialize the client with streaming transport\n/// let client = Client(name: \"MyApp\", version: \"1.0.0\")\n/// try await client.connect(transport: transport)\n///\n/// // The transport will automatically handle SSE events\n/// // and deliver them through the client's notification handlers\n/// ```\npublic actor HTTPClientTransport: Transport {\n /// The server endpoint URL to connect to\n public let endpoint: URL\n private let session: URLSession\n\n /// The session ID assigned by the server, used for maintaining state across requests\n public private(set) var sessionID: String?\n private let streaming: Bool\n private var streamingTask: Task?\n\n /// Logger instance for transport-related events\n public nonisolated let logger: Logger\n\n /// Maximum time to wait for a session ID before proceeding with SSE connection\n public let sseInitializationTimeout: TimeInterval\n\n private var isConnected = false\n private let messageStream: AsyncThrowingStream\n private let messageContinuation: AsyncThrowingStream.Continuation\n\n private var initialSessionIDSignalTask: Task?\n private var initialSessionIDContinuation: CheckedContinuation?\n\n /// Creates a new HTTP transport client with the specified endpoint\n ///\n /// - Parameters:\n /// - endpoint: The server URL to connect to\n /// - configuration: URLSession configuration to use for HTTP requests\n /// - streaming: Whether to enable SSE streaming mode (default: true)\n /// - sseInitializationTimeout: Maximum time to wait for session ID before proceeding with SSE (default: 10 seconds)\n /// - logger: Optional logger instance for transport events\n public init(\n endpoint: URL,\n configuration: URLSessionConfiguration = .default,\n streaming: Bool = true,\n sseInitializationTimeout: TimeInterval = 10,\n logger: Logger? = nil\n ) {\n self.init(\n endpoint: endpoint,\n session: URLSession(configuration: configuration),\n streaming: streaming,\n sseInitializationTimeout: sseInitializationTimeout,\n logger: logger\n )\n }\n\n internal init(\n endpoint: URL,\n session: URLSession,\n streaming: Bool = false,\n sseInitializationTimeout: TimeInterval = 10,\n logger: Logger? = nil\n ) {\n self.endpoint = endpoint\n self.session = session\n self.streaming = streaming\n self.sseInitializationTimeout = sseInitializationTimeout\n\n // Create message stream\n var continuation: AsyncThrowingStream.Continuation!\n self.messageStream = AsyncThrowingStream { continuation = $0 }\n self.messageContinuation = continuation\n\n self.logger =\n logger\n ?? Logger(\n label: \"mcp.transport.http.client\",\n factory: { _ in SwiftLogNoOpLogHandler() }\n )\n }\n\n // Setup the initial session ID signal\n private func setupInitialSessionIDSignal() {\n self.initialSessionIDSignalTask = Task {\n await withCheckedContinuation { continuation in\n self.initialSessionIDContinuation = continuation\n // This task will suspend here until continuation.resume() is called\n }\n }\n }\n\n // Trigger the initial session ID signal when a session ID is established\n private func triggerInitialSessionIDSignal() {\n if let continuation = self.initialSessionIDContinuation {\n continuation.resume()\n self.initialSessionIDContinuation = nil // Consume the continuation\n logger.trace(\"Initial session ID signal triggered for SSE task.\")\n }\n }\n\n /// Establishes connection with the transport\n ///\n /// This prepares the transport for communication and sets up SSE streaming\n /// if streaming mode is enabled. The actual HTTP connection happens with the\n /// first message sent.\n public func connect() async throws {\n guard !isConnected else { return }\n isConnected = true\n\n // Setup initial session ID signal\n setupInitialSessionIDSignal()\n\n if streaming {\n // Start listening to server events\n streamingTask = Task { await startListeningForServerEvents() }\n }\n\n logger.info(\"HTTP transport connected\")\n }\n\n /// Disconnects from the transport\n ///\n /// This terminates any active connections, cancels the streaming task,\n /// and releases any resources being used by the transport.\n public func disconnect() async {\n guard isConnected else { return }\n isConnected = false\n\n // Cancel streaming task if active\n streamingTask?.cancel()\n streamingTask = nil\n\n // Cancel any in-progress requests\n session.invalidateAndCancel()\n\n // Clean up message stream\n messageContinuation.finish()\n\n // Cancel the initial session ID signal task if active\n initialSessionIDSignalTask?.cancel()\n initialSessionIDSignalTask = nil\n // Resume the continuation if it's still pending to avoid leaks\n initialSessionIDContinuation?.resume()\n initialSessionIDContinuation = nil\n\n logger.info(\"HTTP clienttransport disconnected\")\n }\n\n /// Sends data through an HTTP POST request\n ///\n /// This sends a JSON-RPC message to the server via HTTP POST and processes\n /// the response according to the MCP Streamable HTTP specification. It handles:\n ///\n /// - Adding appropriate Accept headers for both JSON and SSE\n /// - Including the session ID in requests if one has been established\n /// - Processing different response types (JSON vs SSE)\n /// - Handling HTTP error codes according to the specification\n ///\n /// - Parameter data: The JSON-RPC message to send\n /// - Throws: MCPError for transport failures or server errors\n public func send(_ data: Data) async throws {\n guard isConnected else {\n throw MCPError.internalError(\"Transport not connected\")\n }\n\n var request = URLRequest(url: endpoint)\n request.httpMethod = \"POST\"\n request.addValue(\"application/json, text/event-stream\", forHTTPHeaderField: \"Accept\")\n request.addValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\n request.httpBody = data\n\n // Add session ID if available\n if let sessionID = sessionID {\n request.addValue(sessionID, forHTTPHeaderField: \"Mcp-Session-Id\")\n }\n\n #if os(Linux)\n // Linux implementation using data(for:) instead of bytes(for:)\n let (responseData, response) = try await session.data(for: request)\n try await processResponse(response: response, data: responseData)\n #else\n // macOS and other platforms with bytes(for:) support\n let (responseStream, response) = try await session.bytes(for: request)\n try await processResponse(response: response, stream: responseStream)\n #endif\n }\n\n #if os(Linux)\n // Process response with data payload (Linux)\n private func processResponse(response: URLResponse, data: Data) async throws {\n guard let httpResponse = response as? HTTPURLResponse else {\n throw MCPError.internalError(\"Invalid HTTP response\")\n }\n\n // Process the response based on content type and status code\n let contentType = httpResponse.value(forHTTPHeaderField: \"Content-Type\") ?? \"\"\n\n // Extract session ID if present\n if let newSessionID = httpResponse.value(forHTTPHeaderField: \"Mcp-Session-Id\") {\n let wasSessionIDNil = (self.sessionID == nil)\n self.sessionID = newSessionID\n if wasSessionIDNil {\n // Trigger signal on first session ID\n triggerInitialSessionIDSignal()\n }\n logger.debug(\"Session ID received\", metadata: [\"sessionID\": \"\\(newSessionID)\"])\n }\n\n try processHTTPResponse(httpResponse, contentType: contentType)\n guard case 200..<300 = httpResponse.statusCode else { return }\n\n // For JSON responses, yield the data\n if contentType.contains(\"text/event-stream\") {\n logger.warning(\"SSE responses aren't fully supported on Linux\")\n messageContinuation.yield(data)\n } else if contentType.contains(\"application/json\") {\n logger.trace(\"Received JSON response\", metadata: [\"size\": \"\\(data.count)\"])\n messageContinuation.yield(data)\n } else {\n logger.warning(\"Unexpected content type: \\(contentType)\")\n }\n }\n #else\n // Process response with byte stream (macOS, iOS, etc.)\n private func processResponse(response: URLResponse, stream: URLSession.AsyncBytes)\n async throws\n {\n guard let httpResponse = response as? HTTPURLResponse else {\n throw MCPError.internalError(\"Invalid HTTP response\")\n }\n\n // Process the response based on content type and status code\n let contentType = httpResponse.value(forHTTPHeaderField: \"Content-Type\") ?? \"\"\n\n // Extract session ID if present\n if let newSessionID = httpResponse.value(forHTTPHeaderField: \"Mcp-Session-Id\") {\n let wasSessionIDNil = (self.sessionID == nil)\n self.sessionID = newSessionID\n if wasSessionIDNil {\n // Trigger signal on first session ID\n triggerInitialSessionIDSignal()\n }\n logger.debug(\"Session ID received\", metadata: [\"sessionID\": \"\\(newSessionID)\"])\n }\n\n try processHTTPResponse(httpResponse, contentType: contentType)\n guard case 200..<300 = httpResponse.statusCode else { return }\n\n if contentType.contains(\"text/event-stream\") {\n // For SSE, processing happens via the stream\n logger.trace(\"Received SSE response, processing in streaming task\")\n try await self.processSSE(stream)\n } else if contentType.contains(\"application/json\") {\n // For JSON responses, collect and deliver the data\n var buffer = Data()\n for try await byte in stream {\n buffer.append(byte)\n }\n logger.trace(\"Received JSON response\", metadata: [\"size\": \"\\(buffer.count)\"])\n messageContinuation.yield(buffer)\n } else {\n logger.warning(\"Unexpected content type: \\(contentType)\")\n }\n }\n #endif\n\n // Common HTTP response handling for all platforms\n private func processHTTPResponse(_ response: HTTPURLResponse, contentType: String) throws {\n // Handle status codes according to HTTP semantics\n switch response.statusCode {\n case 200..<300:\n // Success range - these are handled by the platform-specific code\n return\n\n case 400:\n throw MCPError.internalError(\"Bad request\")\n\n case 401:\n throw MCPError.internalError(\"Authentication required\")\n\n case 403:\n throw MCPError.internalError(\"Access forbidden\")\n\n case 404:\n // If we get a 404 with a session ID, it means our session is invalid\n if sessionID != nil {\n logger.warning(\"Session has expired\")\n sessionID = nil\n throw MCPError.internalError(\"Session expired\")\n }\n throw MCPError.internalError(\"Endpoint not found\")\n\n case 405:\n // If we get a 405, it means the server does not support the requested method\n // If streaming was requested, we should cancel the streaming task\n if streaming {\n self.streamingTask?.cancel()\n throw MCPError.internalError(\"Server does not support streaming\")\n }\n throw MCPError.internalError(\"Method not allowed\")\n\n case 408:\n throw MCPError.internalError(\"Request timeout\")\n\n case 429:\n throw MCPError.internalError(\"Too many requests\")\n\n case 500..<600:\n // Server error range\n throw MCPError.internalError(\"Server error: \\(response.statusCode)\")\n\n default:\n throw MCPError.internalError(\n \"Unexpected HTTP response: \\(response.statusCode) (\\(contentType))\")\n }\n }\n\n /// Receives data in an async sequence\n ///\n /// This returns an AsyncThrowingStream that emits Data objects representing\n /// each JSON-RPC message received from the server. This includes:\n ///\n /// - Direct responses to client requests\n /// - Server-initiated messages delivered via SSE streams\n ///\n /// - Returns: An AsyncThrowingStream of Data objects\n public func receive() -> AsyncThrowingStream {\n return messageStream\n }\n\n // MARK: - SSE\n\n /// Starts listening for server events using SSE\n ///\n /// This establishes a long-lived HTTP connection using Server-Sent Events (SSE)\n /// to enable server-to-client push messaging. It handles:\n ///\n /// - Waiting for session ID if needed\n /// - Opening the SSE connection\n /// - Automatic reconnection on connection drops\n /// - Processing received events\n private func startListeningForServerEvents() async {\n #if os(Linux)\n // SSE is not fully supported on Linux\n if streaming {\n logger.warning(\n \"SSE streaming was requested but is not fully supported on Linux. SSE connection will not be attempted.\"\n )\n }\n #else\n // This is the original code for platforms that support SSE\n guard isConnected else { return }\n\n // Wait for the initial session ID signal, but only if sessionID isn't already set\n if self.sessionID == nil, let signalTask = self.initialSessionIDSignalTask {\n logger.trace(\"SSE streaming task waiting for initial sessionID signal...\")\n\n // Race the signalTask against a timeout\n let timeoutTask = Task {\n try? await Task.sleep(for: .seconds(self.sseInitializationTimeout))\n return false\n }\n\n let signalCompletionTask = Task {\n await signalTask.value\n return true // Indicates signal received\n }\n\n // Use TaskGroup to race the two tasks\n var signalReceived = false\n do {\n signalReceived = try await withThrowingTaskGroup(of: Bool.self) { group in\n group.addTask {\n await signalCompletionTask.value\n }\n group.addTask {\n await timeoutTask.value\n }\n\n // Take the first result and cancel the other task\n if let firstResult = try await group.next() {\n group.cancelAll()\n return firstResult\n }\n return false\n }\n } catch {\n logger.error(\"Error while waiting for session ID signal: \\(error)\")\n }\n\n // Clean up tasks\n timeoutTask.cancel()\n\n if signalReceived {\n logger.trace(\"SSE streaming task proceeding after initial sessionID signal.\")\n } else {\n logger.warning(\n \"Timeout waiting for initial sessionID signal. SSE stream will proceed (sessionID might be nil).\"\n )\n }\n } else if self.sessionID != nil {\n logger.trace(\n \"Initial sessionID already available. Proceeding with SSE streaming task immediately.\"\n )\n } else {\n logger.info(\n \"Proceeding with SSE connection attempt; sessionID is nil. This might be expected for stateless servers or if initialize hasn't provided one yet.\"\n )\n }\n\n // Retry loop for connection drops\n while isConnected && !Task.isCancelled {\n do {\n try await connectToEventStream()\n } catch {\n if !Task.isCancelled {\n logger.error(\"SSE connection error: \\(error)\")\n // Wait before retrying\n try? await Task.sleep(for: .seconds(1))\n }\n }\n }\n #endif\n }\n\n #if !os(Linux)\n /// Establishes an SSE connection to the server\n ///\n /// This initiates a GET request to the server endpoint with appropriate\n /// headers to establish an SSE stream according to the MCP specification.\n ///\n /// - Throws: MCPError for connection failures or server errors\n private func connectToEventStream() async throws {\n guard isConnected else { return }\n\n var request = URLRequest(url: endpoint)\n request.httpMethod = \"GET\"\n request.addValue(\"text/event-stream\", forHTTPHeaderField: \"Accept\")\n request.addValue(\"no-cache\", forHTTPHeaderField: \"Cache-Control\")\n\n // Add session ID if available\n if let sessionID = sessionID {\n request.addValue(sessionID, forHTTPHeaderField: \"Mcp-Session-Id\")\n }\n\n logger.debug(\"Starting SSE connection\")\n\n // Create URLSession task for SSE\n let (stream, response) = try await session.bytes(for: request)\n\n guard let httpResponse = response as? HTTPURLResponse else {\n throw MCPError.internalError(\"Invalid HTTP response\")\n }\n\n // Check response status\n guard httpResponse.statusCode == 200 else {\n // If the server returns 405 Method Not Allowed,\n // it indicates that the server doesn't support SSE streaming.\n // We should cancel the task instead of retrying the connection.\n if httpResponse.statusCode == 405 {\n self.streamingTask?.cancel()\n }\n throw MCPError.internalError(\"HTTP error: \\(httpResponse.statusCode)\")\n }\n\n // Extract session ID if present\n if let newSessionID = httpResponse.value(forHTTPHeaderField: \"Mcp-Session-Id\") {\n let wasSessionIDNil = (self.sessionID == nil)\n self.sessionID = newSessionID\n if wasSessionIDNil {\n // Trigger signal on first session ID, though this is unlikely to happen here\n // as GET usually follows a POST that would have already set the session ID\n triggerInitialSessionIDSignal()\n }\n logger.debug(\"Session ID received\", metadata: [\"sessionID\": \"\\(newSessionID)\"])\n }\n\n try await self.processSSE(stream)\n }\n\n /// Processes an SSE byte stream, extracting events and delivering them\n ///\n /// - Parameter stream: The URLSession.AsyncBytes stream to process\n /// - Throws: Error for stream processing failures\n private func processSSE(_ stream: URLSession.AsyncBytes) async throws {\n do {\n for try await event in stream.events {\n // Check if task has been cancelled\n if Task.isCancelled { break }\n\n logger.trace(\n \"SSE event received\",\n metadata: [\n \"type\": \"\\(event.event ?? \"message\")\",\n \"id\": \"\\(event.id ?? \"none\")\",\n ]\n )\n\n // Convert the event data to Data and yield it to the message stream\n if !event.data.isEmpty, let data = event.data.data(using: .utf8) {\n messageContinuation.yield(data)\n }\n }\n } catch {\n logger.error(\"Error processing SSE events: \\(error)\")\n throw error\n }\n }\n #endif\n}\n"], ["/swift-sdk/Sources/MCP/Client/Client.swift", "import Logging\n\nimport struct Foundation.Data\nimport struct Foundation.Date\nimport class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\n/// Model Context Protocol client\npublic actor Client {\n /// The client configuration\n public struct Configuration: Hashable, Codable, Sendable {\n /// The default configuration.\n public static let `default` = Configuration(strict: false)\n\n /// The strict configuration.\n public static let strict = Configuration(strict: true)\n\n /// When strict mode is enabled, the client:\n /// - Requires server capabilities to be initialized before making requests\n /// - Rejects all requests that require capabilities before initialization\n ///\n /// While the MCP specification requires servers to respond to initialize requests\n /// with their capabilities, some implementations may not follow this.\n /// Disabling strict mode allows the client to be more lenient with non-compliant\n /// servers, though this may lead to undefined behavior.\n public var strict: Bool\n\n public init(strict: Bool = false) {\n self.strict = strict\n }\n }\n\n /// Implementation information\n public struct Info: Hashable, Codable, Sendable {\n /// The client name\n public var name: String\n /// The client version\n public var version: String\n\n public init(name: String, version: String) {\n self.name = name\n self.version = version\n }\n }\n\n /// The client capabilities\n public struct Capabilities: Hashable, Codable, Sendable {\n /// The roots capabilities\n public struct Roots: Hashable, Codable, Sendable {\n /// Whether the list of roots has changed\n public var listChanged: Bool?\n\n public init(listChanged: Bool? = nil) {\n self.listChanged = listChanged\n }\n }\n\n /// The sampling capabilities\n public struct Sampling: Hashable, Codable, Sendable {\n public init() {}\n }\n\n /// Whether the client supports sampling\n public var sampling: Sampling?\n /// Experimental features supported by the client\n public var experimental: [String: String]?\n /// Whether the client supports roots\n public var roots: Capabilities.Roots?\n\n public init(\n sampling: Sampling? = nil,\n experimental: [String: String]? = nil,\n roots: Capabilities.Roots? = nil\n ) {\n self.sampling = sampling\n self.experimental = experimental\n self.roots = roots\n }\n }\n\n /// The connection to the server\n private var connection: (any Transport)?\n /// The logger for the client\n private var logger: Logger? {\n get async {\n await connection?.logger\n }\n }\n\n /// The client information\n private let clientInfo: Client.Info\n /// The client name\n public nonisolated var name: String { clientInfo.name }\n /// The client version\n public nonisolated var version: String { clientInfo.version }\n\n /// The client capabilities\n public var capabilities: Client.Capabilities\n /// The client configuration\n public var configuration: Configuration\n\n /// The server capabilities\n private var serverCapabilities: Server.Capabilities?\n /// The server version\n private var serverVersion: String?\n /// The server instructions\n private var instructions: String?\n\n /// A dictionary of type-erased notification handlers, keyed by method name\n private var notificationHandlers: [String: [NotificationHandlerBox]] = [:]\n /// The task for the message handling loop\n private var task: Task?\n\n /// An error indicating a type mismatch when decoding a pending request\n private struct TypeMismatchError: Swift.Error {}\n\n /// A pending request with a continuation for the result\n private struct PendingRequest {\n let continuation: CheckedContinuation\n }\n\n /// A type-erased pending request\n private struct AnyPendingRequest {\n private let _resume: (Result) -> Void\n\n init(_ request: PendingRequest) {\n _resume = { result in\n switch result {\n case .success(let value):\n if let typedValue = value as? T {\n request.continuation.resume(returning: typedValue)\n } else if let value = value as? Value,\n let data = try? JSONEncoder().encode(value),\n let decoded = try? JSONDecoder().decode(T.self, from: data)\n {\n request.continuation.resume(returning: decoded)\n } else {\n request.continuation.resume(throwing: TypeMismatchError())\n }\n case .failure(let error):\n request.continuation.resume(throwing: error)\n }\n }\n }\n func resume(returning value: Any) {\n _resume(.success(value))\n }\n\n func resume(throwing error: Swift.Error) {\n _resume(.failure(error))\n }\n }\n\n /// A dictionary of type-erased pending requests, keyed by request ID\n private var pendingRequests: [ID: AnyPendingRequest] = [:]\n // Add reusable JSON encoder/decoder\n private let encoder = JSONEncoder()\n private let decoder = JSONDecoder()\n\n public init(\n name: String,\n version: String,\n configuration: Configuration = .default\n ) {\n self.clientInfo = Client.Info(name: name, version: version)\n self.capabilities = Capabilities()\n self.configuration = configuration\n }\n\n /// Connect to the server using the given transport\n @discardableResult\n public func connect(transport: any Transport) async throws -> Initialize.Result {\n self.connection = transport\n try await self.connection?.connect()\n\n await logger?.info(\n \"Client connected\", metadata: [\"name\": \"\\(name)\", \"version\": \"\\(version)\"])\n\n // Start message handling loop\n task = Task {\n guard let connection = self.connection else { return }\n repeat {\n // Check for cancellation before starting the iteration\n if Task.isCancelled { break }\n\n do {\n let stream = await connection.receive()\n for try await data in stream {\n if Task.isCancelled { break } // Check inside loop too\n\n // Attempt to decode data\n // Try decoding as a batch response first\n if let batchResponse = try? decoder.decode([AnyResponse].self, from: data) {\n await handleBatchResponse(batchResponse)\n } else if let response = try? decoder.decode(AnyResponse.self, from: data) {\n await handleResponse(response)\n } else if let message = try? decoder.decode(AnyMessage.self, from: data) {\n await handleMessage(message)\n } else {\n var metadata: Logger.Metadata = [:]\n if let string = String(data: data, encoding: .utf8) {\n metadata[\"message\"] = .string(string)\n }\n await logger?.warning(\n \"Unexpected message received by client (not single/batch response or notification)\",\n metadata: metadata\n )\n }\n }\n } catch let error where MCPError.isResourceTemporarilyUnavailable(error) {\n try? await Task.sleep(for: .milliseconds(10))\n continue\n } catch {\n await logger?.error(\n \"Error in message handling loop\", metadata: [\"error\": \"\\(error)\"])\n break\n }\n } while true\n await self.logger?.info(\"Client message handling loop task is terminating.\")\n }\n\n // Automatically initialize after connecting\n return try await _initialize()\n }\n\n /// Disconnect the client and cancel all pending requests\n public func disconnect() async {\n await logger?.info(\"Initiating client disconnect...\")\n\n // Part 1: Inside actor - Grab state and clear internal references\n let taskToCancel = self.task\n let connectionToDisconnect = self.connection\n let pendingRequestsToCancel = self.pendingRequests\n\n self.task = nil\n self.connection = nil\n self.pendingRequests = [:] // Use empty dictionary literal\n\n // Part 2: Outside actor - Resume continuations, disconnect transport, await task\n\n // Resume continuations first\n for (_, request) in pendingRequestsToCancel {\n request.resume(throwing: MCPError.internalError(\"Client disconnected\"))\n }\n await logger?.info(\"Pending requests cancelled.\")\n\n // Cancel the task\n taskToCancel?.cancel()\n await logger?.info(\"Message loop task cancellation requested.\")\n\n // Disconnect the transport *before* awaiting the task\n // This should ensure the transport stream is finished, unblocking the loop.\n if let conn = connectionToDisconnect {\n await conn.disconnect()\n await logger?.info(\"Transport disconnected.\")\n } else {\n await logger?.info(\"No active transport connection to disconnect.\")\n }\n\n // Await the task completion *after* transport disconnect\n _ = await taskToCancel?.value\n await logger?.info(\"Client message loop task finished.\")\n\n await logger?.info(\"Client disconnect complete.\")\n }\n\n // MARK: - Registration\n\n /// Register a handler for a notification\n @discardableResult\n public func onNotification(\n _ type: N.Type,\n handler: @escaping @Sendable (Message) async throws -> Void\n ) async -> Self {\n let handlers = notificationHandlers[N.name, default: []]\n notificationHandlers[N.name] = handlers + [TypedNotificationHandler(handler)]\n return self\n }\n\n /// Send a notification to the server\n public func notify(_ notification: Message) async throws {\n guard let connection = connection else {\n throw MCPError.internalError(\"Client connection not initialized\")\n }\n\n let notificationData = try encoder.encode(notification)\n try await connection.send(notificationData)\n }\n\n // MARK: - Requests\n\n /// Send a request and receive its response\n public func send(_ request: Request) async throws -> M.Result {\n guard let connection = connection else {\n throw MCPError.internalError(\"Client connection not initialized\")\n }\n\n let requestData = try encoder.encode(request)\n\n // Store the pending request first\n return try await withCheckedThrowingContinuation { continuation in\n Task {\n // Add the pending request before attempting to send\n self.addPendingRequest(\n id: request.id,\n continuation: continuation,\n type: M.Result.self\n )\n\n // Send the request data\n do {\n // Use the existing connection send\n try await connection.send(requestData)\n } catch {\n // If send fails, try to remove the pending request.\n // Resume with the send error only if we successfully removed the request,\n // indicating the response handler hasn't processed it yet.\n if self.removePendingRequest(id: request.id) != nil {\n continuation.resume(throwing: error)\n }\n // Otherwise, the request was already removed by the response handler\n // or by disconnect, so the continuation was already resumed.\n // Do nothing here.\n }\n }\n }\n }\n\n private func addPendingRequest(\n id: ID,\n continuation: CheckedContinuation,\n type: T.Type // Keep type for AnyPendingRequest internal logic\n ) {\n pendingRequests[id] = AnyPendingRequest(PendingRequest(continuation: continuation))\n }\n\n private func removePendingRequest(id: ID) -> AnyPendingRequest? {\n return pendingRequests.removeValue(forKey: id)\n }\n\n // MARK: - Batching\n\n /// A batch of requests.\n ///\n /// Objects of this type are passed as an argument to the closure\n /// of the ``Client/withBatch(_:)`` method.\n public actor Batch {\n unowned let client: Client\n var requests: [AnyRequest] = []\n\n init(client: Client) {\n self.client = client\n }\n\n /// Adds a request to the batch and prepares its expected response task.\n /// The actual sending happens when the `withBatch` scope completes.\n /// - Returns: A `Task` that will eventually produce the result or throw an error.\n public func addRequest(_ request: Request) async throws -> Task<\n M.Result, Swift.Error\n > {\n requests.append(try AnyRequest(request))\n\n // Return a Task that registers the pending request and awaits its result.\n // The continuation is resumed when the response arrives.\n return Task {\n try await withCheckedThrowingContinuation { continuation in\n // We are already inside a Task, but need another Task\n // to bridge to the client actor's context.\n Task {\n await client.addPendingRequest(\n id: request.id,\n continuation: continuation,\n type: M.Result.self\n )\n }\n }\n }\n }\n }\n\n /// Executes multiple requests in a single batch.\n ///\n /// This method allows you to group multiple MCP requests together,\n /// which are then sent to the server as a single JSON array.\n /// The server processes these requests and sends back a corresponding\n /// JSON array of responses.\n ///\n /// Within the `body` closure, use the provided `Batch` actor to add\n /// requests using `batch.addRequest(_:)`. Each call to `addRequest`\n /// returns a `Task` handle representing the asynchronous operation\n /// for that specific request's result.\n ///\n /// It's recommended to collect these `Task` handles into an array\n /// within the `body` closure`. After the `withBatch` method returns\n /// (meaning the batch request has been sent), you can then process\n /// the results by awaiting each `Task` in the collected array.\n ///\n /// Example 1: Batching multiple tool calls and collecting typed tasks:\n /// ```swift\n /// // Array to hold the task handles for each tool call\n /// var toolTasks: [Task] = []\n /// try await client.withBatch { batch in\n /// for i in 0..<10 {\n /// toolTasks.append(\n /// try await batch.addRequest(\n /// CallTool.request(.init(name: \"square\", arguments: [\"n\": i]))\n /// )\n /// )\n /// }\n /// }\n ///\n /// // Process results after the batch is sent\n /// print(\"Processing \\(toolTasks.count) tool results...\")\n /// for (index, task) in toolTasks.enumerated() {\n /// do {\n /// let result = try await task.value\n /// print(\"\\(index): \\(result.content)\")\n /// } catch {\n /// print(\"\\(index) failed: \\(error)\")\n /// }\n /// }\n /// ```\n ///\n /// Example 2: Batching different request types and awaiting individual tasks:\n /// ```swift\n /// // Declare optional task variables beforehand\n /// var pingTask: Task?\n /// var promptTask: Task?\n ///\n /// try await client.withBatch { batch in\n /// // Assign the tasks within the batch closure\n /// pingTask = try await batch.addRequest(Ping.request())\n /// promptTask = try await batch.addRequest(GetPrompt.request(.init(name: \"greeting\")))\n /// }\n ///\n /// // Await the results after the batch is sent\n /// do {\n /// if let pingTask = pingTask {\n /// try await pingTask.value // Await ping result (throws if ping failed)\n /// print(\"Ping successful\")\n /// }\n /// if let promptTask = promptTask {\n /// let promptResult = try await promptTask.value // Await prompt result\n /// print(\"Prompt description: \\(promptResult.description ?? \"None\")\")\n /// }\n /// } catch {\n /// print(\"Error processing batch results: \\(error)\")\n /// }\n /// ```\n ///\n /// - Parameter body: An asynchronous closure that takes a `Batch` object as input.\n /// Use this object to add requests to the batch.\n /// - Throws: `MCPError.internalError` if the client is not connected.\n /// Can also rethrow errors from the `body` closure or from sending the batch request.\n public func withBatch(body: @escaping (Batch) async throws -> Void) async throws {\n guard let connection = connection else {\n throw MCPError.internalError(\"Client connection not initialized\")\n }\n\n // Create Batch actor, passing self (Client)\n let batch = Batch(client: self)\n\n // Populate the batch actor by calling the user's closure.\n try await body(batch)\n\n // Get the collected requests from the batch actor\n let requests = await batch.requests\n\n // Check if there are any requests to send\n guard !requests.isEmpty else {\n await logger?.info(\"Batch requested but no requests were added.\")\n return // Nothing to send\n }\n\n await logger?.debug(\n \"Sending batch request\", metadata: [\"count\": \"\\(requests.count)\"])\n\n // Encode the array of AnyMethod requests into a single JSON payload\n let data = try encoder.encode(requests)\n try await connection.send(data)\n\n // Responses will be handled asynchronously by the message loop and handleBatchResponse/handleResponse.\n }\n\n // MARK: - Lifecycle\n\n /// Initialize the connection with the server.\n ///\n /// - Important: This method is deprecated. Initialization now happens automatically\n /// when calling `connect(transport:)`. You should use that method instead.\n ///\n /// - Returns: The server's initialization response containing capabilities and server info\n @available(\n *, deprecated,\n message:\n \"Initialization now happens automatically during connect. Use connect(transport:) instead.\"\n )\n public func initialize() async throws -> Initialize.Result {\n return try await _initialize()\n }\n\n /// Internal initialization implementation\n private func _initialize() async throws -> Initialize.Result {\n let request = Initialize.request(\n .init(\n protocolVersion: Version.latest,\n capabilities: capabilities,\n clientInfo: clientInfo\n ))\n\n let result = try await send(request)\n\n self.serverCapabilities = result.capabilities\n self.serverVersion = result.protocolVersion\n self.instructions = result.instructions\n\n try await notify(InitializedNotification.message())\n\n return result\n }\n\n public func ping() async throws {\n let request = Ping.request()\n _ = try await send(request)\n }\n\n // MARK: - Prompts\n\n public func getPrompt(name: String, arguments: [String: Value]? = nil) async throws\n -> (description: String?, messages: [Prompt.Message])\n {\n try validateServerCapability(\\.prompts, \"Prompts\")\n let request = GetPrompt.request(.init(name: name, arguments: arguments))\n let result = try await send(request)\n return (description: result.description, messages: result.messages)\n }\n\n public func listPrompts(cursor: String? = nil) async throws\n -> (prompts: [Prompt], nextCursor: String?)\n {\n try validateServerCapability(\\.prompts, \"Prompts\")\n let request: Request\n if let cursor = cursor {\n request = ListPrompts.request(.init(cursor: cursor))\n } else {\n request = ListPrompts.request(.init())\n }\n let result = try await send(request)\n return (prompts: result.prompts, nextCursor: result.nextCursor)\n }\n\n // MARK: - Resources\n\n public func readResource(uri: String) async throws -> [Resource.Content] {\n try validateServerCapability(\\.resources, \"Resources\")\n let request = ReadResource.request(.init(uri: uri))\n let result = try await send(request)\n return result.contents\n }\n\n public func listResources(cursor: String? = nil) async throws -> (\n resources: [Resource], nextCursor: String?\n ) {\n try validateServerCapability(\\.resources, \"Resources\")\n let request: Request\n if let cursor = cursor {\n request = ListResources.request(.init(cursor: cursor))\n } else {\n request = ListResources.request(.init())\n }\n let result = try await send(request)\n return (resources: result.resources, nextCursor: result.nextCursor)\n }\n\n public func subscribeToResource(uri: String) async throws {\n try validateServerCapability(\\.resources?.subscribe, \"Resource subscription\")\n let request = ResourceSubscribe.request(.init(uri: uri))\n _ = try await send(request)\n }\n\n public func listResourceTemplates(cursor: String? = nil) async throws -> (\n templates: [Resource.Template], nextCursor: String?\n ) {\n try validateServerCapability(\\.resources, \"Resources\")\n let request: Request\n if let cursor = cursor {\n request = ListResourceTemplates.request(.init(cursor: cursor))\n } else {\n request = ListResourceTemplates.request(.init())\n }\n let result = try await send(request)\n return (templates: result.templates, nextCursor: result.nextCursor)\n }\n\n // MARK: - Tools\n\n public func listTools(cursor: String? = nil) async throws -> (\n tools: [Tool], nextCursor: String?\n ) {\n try validateServerCapability(\\.tools, \"Tools\")\n let request: Request\n if let cursor = cursor {\n request = ListTools.request(.init(cursor: cursor))\n } else {\n request = ListTools.request(.init())\n }\n let result = try await send(request)\n return (tools: result.tools, nextCursor: result.nextCursor)\n }\n\n public func callTool(name: String, arguments: [String: Value]? = nil) async throws -> (\n content: [Tool.Content], isError: Bool?\n ) {\n try validateServerCapability(\\.tools, \"Tools\")\n let request = CallTool.request(.init(name: name, arguments: arguments))\n let result = try await send(request)\n return (content: result.content, isError: result.isError)\n }\n\n // MARK: - Sampling\n\n /// Register a handler for sampling requests from servers\n ///\n /// Sampling allows servers to request LLM completions through the client,\n /// enabling sophisticated agentic behaviors while maintaining human-in-the-loop control.\n ///\n /// The sampling flow follows these steps:\n /// 1. Server sends a `sampling/createMessage` request to the client\n /// 2. Client reviews the request and can modify it (via this handler)\n /// 3. Client samples from an LLM (via this handler)\n /// 4. Client reviews the completion (via this handler)\n /// 5. Client returns the result to the server\n ///\n /// - Parameter handler: A closure that processes sampling requests and returns completions\n /// - Returns: Self for method chaining\n /// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/sampling#how-sampling-works\n @discardableResult\n public func withSamplingHandler(\n _ handler: @escaping @Sendable (CreateSamplingMessage.Parameters) async throws ->\n CreateSamplingMessage.Result\n ) -> Self {\n // Note: This would require extending the client architecture to handle incoming requests from servers.\n // The current MCP Swift SDK architecture assumes clients only send requests to servers,\n // but sampling requires bidirectional communication where servers can send requests to clients.\n //\n // A full implementation would need:\n // 1. Request handlers in the client (similar to how servers handle requests)\n // 2. Bidirectional transport support\n // 3. Request/response correlation for server-to-client requests\n //\n // For now, this serves as the correct API design for when bidirectional support is added.\n\n // This would register the handler similar to how servers register method handlers:\n // methodHandlers[CreateSamplingMessage.name] = TypedRequestHandler(handler)\n\n return self\n }\n\n // MARK: -\n\n private func handleResponse(_ response: Response) async {\n await logger?.trace(\n \"Processing response\",\n metadata: [\"id\": \"\\(response.id)\"])\n\n // Attempt to remove the pending request using the response ID.\n // Resume with the response only if it hadn't yet been removed.\n if let removedRequest = self.removePendingRequest(id: response.id) {\n // If we successfully removed it, resume its continuation.\n switch response.result {\n case .success(let value):\n removedRequest.resume(returning: value)\n case .failure(let error):\n removedRequest.resume(throwing: error)\n }\n } else {\n // Request was already removed (e.g., by send error handler or disconnect).\n // Log this, but it's not an error in race condition scenarios.\n await logger?.warning(\n \"Attempted to handle response for already removed request\",\n metadata: [\"id\": \"\\(response.id)\"]\n )\n }\n }\n\n private func handleMessage(_ message: Message) async {\n await logger?.trace(\n \"Processing notification\",\n metadata: [\"method\": \"\\(message.method)\"])\n\n // Find notification handlers for this method\n guard let handlers = notificationHandlers[message.method] else { return }\n\n // Convert notification parameters to concrete type and call handlers\n for handler in handlers {\n do {\n try await handler(message)\n } catch {\n await logger?.error(\n \"Error handling notification\",\n metadata: [\n \"method\": \"\\(message.method)\",\n \"error\": \"\\(error)\",\n ])\n }\n }\n }\n\n // MARK: -\n\n /// Validate the server capabilities.\n /// Throws an error if the client is configured to be strict and the capability is not supported.\n private func validateServerCapability(\n _ keyPath: KeyPath,\n _ name: String\n )\n throws\n {\n if configuration.strict {\n guard let capabilities = serverCapabilities else {\n throw MCPError.methodNotFound(\"Server capabilities not initialized\")\n }\n guard capabilities[keyPath: keyPath] != nil else {\n throw MCPError.methodNotFound(\"\\(name) is not supported by the server\")\n }\n }\n }\n\n // Add handler for batch responses\n private func handleBatchResponse(_ responses: [AnyResponse]) async {\n await logger?.trace(\"Processing batch response\", metadata: [\"count\": \"\\(responses.count)\"])\n for response in responses {\n // Attempt to remove the pending request.\n // If successful, pendingRequest contains the request.\n if let pendingRequest = self.removePendingRequest(id: response.id) {\n // If we successfully removed it, handle the response using the pending request.\n switch response.result {\n case .success(let value):\n pendingRequest.resume(returning: value)\n case .failure(let error):\n pendingRequest.resume(throwing: error)\n }\n } else {\n // If removal failed, it means the request ID was not found (or already handled).\n // Log a warning.\n await logger?.warning(\n \"Received response in batch for unknown or already handled request ID\",\n metadata: [\"id\": \"\\(response.id)\"]\n )\n }\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Transports/NetworkTransport.swift", "import Foundation\nimport Logging\n\n#if canImport(Network)\n import Network\n\n /// Protocol that abstracts the Network.NWConnection functionality needed for NetworkTransport\n @preconcurrency protocol NetworkConnectionProtocol {\n var state: NWConnection.State { get }\n var stateUpdateHandler: ((@Sendable (NWConnection.State) -> Void))? { get set }\n\n func start(queue: DispatchQueue)\n func cancel()\n func send(\n content: Data?, contentContext: NWConnection.ContentContext, isComplete: Bool,\n completion: NWConnection.SendCompletion)\n func receive(\n minimumIncompleteLength: Int, maximumLength: Int,\n completion: @escaping @Sendable (\n Data?, NWConnection.ContentContext?, Bool, NWError?\n ) -> Void)\n }\n\n /// Extension to conform NWConnection to internal NetworkConnectionProtocol\n extension NWConnection: NetworkConnectionProtocol {}\n\n /// An implementation of a custom MCP transport using Apple's Network framework.\n ///\n /// This transport allows MCP clients and servers to communicate over TCP/UDP connections\n /// using Apple's Network framework.\n ///\n /// - Important: This transport is available exclusively on Apple platforms\n /// (macOS, iOS, watchOS, tvOS, visionOS) as it depends on the Network framework.\n ///\n /// ## Example Usage\n ///\n /// ```swift\n /// import MCP\n /// import Network\n ///\n /// // Create a TCP connection to a server\n /// let connection = NWConnection(\n /// host: NWEndpoint.Host(\"localhost\"),\n /// port: NWEndpoint.Port(8080)!,\n /// using: .tcp\n /// )\n ///\n /// // Initialize the transport with the connection\n /// let transport = NetworkTransport(connection: connection)\n ///\n /// // For large messages (e.g., images), configure unlimited buffer size\n /// let largeBufferTransport = NetworkTransport(\n /// connection: connection,\n /// bufferConfig: .unlimited\n /// )\n ///\n /// // Use the transport with an MCP client\n /// let client = Client(name: \"MyApp\", version: \"1.0.0\")\n /// try await client.connect(transport: transport)\n /// ```\n public actor NetworkTransport: Transport {\n /// Represents a heartbeat message for connection health monitoring.\n public struct Heartbeat: RawRepresentable, Hashable, Sendable {\n /// Magic bytes used to identify a heartbeat message.\n private static let magicBytes: [UInt8] = [0xF0, 0x9F, 0x92, 0x93]\n\n /// The timestamp of when the heartbeat was created.\n public let timestamp: Date\n\n /// Creates a new heartbeat with the current timestamp.\n public init() {\n self.timestamp = Date()\n }\n\n /// Creates a heartbeat with a specific timestamp.\n ///\n /// - Parameter timestamp: The timestamp for the heartbeat.\n public init(timestamp: Date) {\n self.timestamp = timestamp\n }\n\n // MARK: - RawRepresentable\n\n public typealias RawValue = [UInt8]\n\n /// Creates a heartbeat from its raw representation.\n ///\n /// - Parameter rawValue: The raw bytes of the heartbeat message.\n /// - Returns: A heartbeat if the raw value is valid, nil otherwise.\n public init?(rawValue: [UInt8]) {\n // Check if the data has the correct format (magic bytes + timestamp)\n guard rawValue.count >= 12,\n rawValue.prefix(4).elementsEqual(Self.magicBytes)\n else {\n return nil\n }\n\n // Extract the timestamp\n let timestampData = Data(rawValue[4..<12])\n let timestamp = timestampData.withUnsafeBytes {\n $0.load(as: UInt64.self)\n }\n\n self.timestamp = Date(\n timeIntervalSinceReferenceDate: TimeInterval(timestamp) / 1000.0)\n }\n\n /// Converts the heartbeat to its raw representation.\n public var rawValue: [UInt8] {\n var result = Data(Self.magicBytes)\n\n // Add timestamp (milliseconds since reference date)\n let timestamp = UInt64(self.timestamp.timeIntervalSinceReferenceDate * 1000)\n withUnsafeBytes(of: timestamp) { buffer in\n result.append(contentsOf: buffer)\n }\n\n return Array(result)\n }\n\n /// Converts the heartbeat to Data.\n public var data: Data {\n return Data(self.rawValue)\n }\n\n /// Checks if the given data represents a heartbeat message.\n ///\n /// - Parameter data: The data to check.\n /// - Returns: true if the data is a heartbeat message, false otherwise.\n public static func isHeartbeat(_ data: Data) -> Bool {\n guard data.count >= 4 else {\n return false\n }\n\n return data.prefix(4).elementsEqual(Self.magicBytes)\n }\n\n /// Attempts to parse a heartbeat from the given data.\n ///\n /// - Parameter data: The data to parse.\n /// - Returns: A heartbeat if the data is valid, nil otherwise.\n public static func from(data: Data) -> Heartbeat? {\n guard data.count >= 12 else {\n return nil\n }\n\n return Heartbeat(rawValue: Array(data))\n }\n }\n\n /// Configuration for heartbeat behavior.\n public struct HeartbeatConfiguration: Hashable, Sendable {\n /// Whether heartbeats are enabled.\n public let enabled: Bool\n /// Interval between heartbeats in seconds.\n public let interval: TimeInterval\n\n /// Creates a new heartbeat configuration.\n ///\n /// - Parameters:\n /// - enabled: Whether heartbeats are enabled (default: true)\n /// - interval: Interval in seconds between heartbeats (default: 15.0)\n public init(enabled: Bool = true, interval: TimeInterval = 15.0) {\n self.enabled = enabled\n self.interval = interval\n }\n\n /// Default heartbeat configuration.\n public static let `default` = HeartbeatConfiguration()\n\n /// Configuration with heartbeats disabled.\n public static let disabled = HeartbeatConfiguration(enabled: false)\n }\n\n /// Configuration for connection retry behavior.\n public struct ReconnectionConfiguration: Hashable, Sendable {\n /// Whether the transport should attempt to reconnect on failure.\n public let enabled: Bool\n /// Maximum number of reconnection attempts.\n public let maxAttempts: Int\n /// Multiplier for exponential backoff on reconnect.\n public let backoffMultiplier: Double\n\n /// Creates a new reconnection configuration.\n ///\n /// - Parameters:\n /// - enabled: Whether reconnection should be attempted on failure (default: true)\n /// - maxAttempts: Maximum number of reconnection attempts (default: 5)\n /// - backoffMultiplier: Multiplier for exponential backoff on reconnect (default: 1.5)\n public init(\n enabled: Bool = true,\n maxAttempts: Int = 5,\n backoffMultiplier: Double = 1.5\n ) {\n self.enabled = enabled\n self.maxAttempts = maxAttempts\n self.backoffMultiplier = backoffMultiplier\n }\n\n /// Default reconnection configuration.\n public static let `default` = ReconnectionConfiguration()\n\n /// Configuration with reconnection disabled.\n public static let disabled = ReconnectionConfiguration(enabled: false)\n\n /// Calculates the backoff delay for a given attempt number.\n ///\n /// - Parameter attempt: The current attempt number (1-based)\n /// - Returns: The delay in seconds before the next attempt\n public func backoffDelay(for attempt: Int) -> TimeInterval {\n let baseDelay = 0.5 // 500ms\n return baseDelay * pow(backoffMultiplier, Double(attempt - 1))\n }\n }\n\n /// Configuration for buffer behavior.\n public struct BufferConfiguration: Hashable, Sendable {\n /// Maximum buffer size for receiving data chunks.\n /// Set to nil for unlimited (uses system default).\n public let maxReceiveBufferSize: Int?\n\n /// Creates a new buffer configuration.\n ///\n /// - Parameter maxReceiveBufferSize: Maximum buffer size in bytes (default: 10MB, nil for unlimited)\n public init(maxReceiveBufferSize: Int? = 10 * 1024 * 1024) {\n self.maxReceiveBufferSize = maxReceiveBufferSize\n }\n\n /// Default buffer configuration with 10MB limit.\n public static let `default` = BufferConfiguration()\n\n /// Configuration with no buffer size limit.\n public static let unlimited = BufferConfiguration(maxReceiveBufferSize: nil)\n }\n\n // State tracking\n private var isConnected = false\n private var isStopping = false\n private var reconnectAttempt = 0\n private var heartbeatTask: Task?\n private var lastHeartbeatTime: Date?\n private let messageStream: AsyncThrowingStream\n private let messageContinuation: AsyncThrowingStream.Continuation\n\n // Track connection state for continuations\n private var connectionContinuationResumed = false\n\n // Connection is marked nonisolated(unsafe) to allow access from closures\n private nonisolated(unsafe) var connection: NetworkConnectionProtocol\n\n /// Logger instance for transport-related events\n public nonisolated let logger: Logger\n\n // Configuration\n private let heartbeatConfig: HeartbeatConfiguration\n private let reconnectionConfig: ReconnectionConfiguration\n private let bufferConfig: BufferConfiguration\n\n /// Creates a new NetworkTransport with the specified NWConnection\n ///\n /// - Parameters:\n /// - connection: The NWConnection to use for communication\n /// - logger: Optional logger instance for transport events\n /// - reconnectionConfig: Configuration for reconnection behavior (default: .default)\n /// - heartbeatConfig: Configuration for heartbeat behavior (default: .default)\n /// - bufferConfig: Configuration for buffer behavior (default: .default)\n public init(\n connection: NWConnection,\n logger: Logger? = nil,\n heartbeatConfig: HeartbeatConfiguration = .default,\n reconnectionConfig: ReconnectionConfiguration = .default,\n bufferConfig: BufferConfiguration = .default\n ) {\n self.init(\n connection,\n logger: logger,\n heartbeatConfig: heartbeatConfig,\n reconnectionConfig: reconnectionConfig,\n bufferConfig: bufferConfig\n )\n }\n\n init(\n _ connection: NetworkConnectionProtocol,\n logger: Logger? = nil,\n heartbeatConfig: HeartbeatConfiguration = .default,\n reconnectionConfig: ReconnectionConfiguration = .default,\n bufferConfig: BufferConfiguration = .default\n ) {\n self.connection = connection\n self.logger =\n logger\n ?? Logger(\n label: \"mcp.transport.network\",\n factory: { _ in SwiftLogNoOpLogHandler() }\n )\n self.reconnectionConfig = reconnectionConfig\n self.heartbeatConfig = heartbeatConfig\n self.bufferConfig = bufferConfig\n\n // Create message stream\n var continuation: AsyncThrowingStream.Continuation!\n self.messageStream = AsyncThrowingStream { continuation = $0 }\n self.messageContinuation = continuation\n }\n\n /// Establishes connection with the transport\n ///\n /// This initiates the NWConnection and waits for it to become ready.\n /// Once the connection is established, it starts the message receiving loop.\n ///\n /// - Throws: Error if the connection fails to establish\n public func connect() async throws {\n guard !isConnected else { return }\n\n // Reset state for fresh connection\n isStopping = false\n reconnectAttempt = 0\n\n // Reset continuation state\n connectionContinuationResumed = false\n\n // Wait for connection to be ready\n try await withCheckedThrowingContinuation {\n [weak self] (continuation: CheckedContinuation) in\n guard let self = self else {\n continuation.resume(throwing: MCPError.internalError(\"Transport deallocated\"))\n return\n }\n\n connection.stateUpdateHandler = { [weak self] state in\n guard let self = self else { return }\n\n Task { @MainActor in\n switch state {\n case .ready:\n await self.handleConnectionReady(continuation: continuation)\n case .failed(let error):\n await self.handleConnectionFailed(\n error: error, continuation: continuation)\n case .cancelled:\n await self.handleConnectionCancelled(continuation: continuation)\n case .waiting(let error):\n self.logger.debug(\"Connection waiting: \\(error)\")\n case .preparing:\n self.logger.debug(\"Connection preparing...\")\n case .setup:\n self.logger.debug(\"Connection setup...\")\n @unknown default:\n self.logger.warning(\"Unknown connection state\")\n }\n }\n }\n\n connection.start(queue: .main)\n }\n }\n\n /// Handles when the connection reaches the ready state\n ///\n /// - Parameter continuation: The continuation to resume when connection is ready\n private func handleConnectionReady(continuation: CheckedContinuation)\n async\n {\n if !connectionContinuationResumed {\n connectionContinuationResumed = true\n isConnected = true\n\n // Reset reconnect attempt counter on successful connection\n reconnectAttempt = 0\n logger.info(\"Network transport connected successfully\")\n continuation.resume()\n\n // Start the receive loop after connection is established\n Task { await self.receiveLoop() }\n\n // Start heartbeat task if enabled\n if heartbeatConfig.enabled {\n startHeartbeat()\n }\n }\n }\n\n /// Starts a task to periodically send heartbeats to check connection health\n private func startHeartbeat() {\n // Cancel any existing heartbeat task\n heartbeatTask?.cancel()\n\n // Start a new heartbeat task\n heartbeatTask = Task { [weak self] in\n guard let self = self else { return }\n\n // Initial delay before starting heartbeats\n try? await Task.sleep(for: .seconds(1))\n\n while !Task.isCancelled {\n do {\n // Check actor-isolated properties first\n let isStopping = await self.isStopping\n let isConnected = await self.isConnected\n\n guard !isStopping && isConnected else { break }\n\n try await self.sendHeartbeat()\n try await Task.sleep(for: .seconds(self.heartbeatConfig.interval))\n } catch {\n // If heartbeat fails, log and retry after a shorter interval\n self.logger.warning(\"Heartbeat failed: \\(error)\")\n try? await Task.sleep(for: .seconds(2))\n }\n }\n }\n }\n\n /// Sends a heartbeat message to verify connection health\n private func sendHeartbeat() async throws {\n guard isConnected && !isStopping else { return }\n\n // Try to send the heartbeat (without the newline delimiter used for normal messages)\n try await withCheckedThrowingContinuation {\n [weak self] (continuation: CheckedContinuation) in\n guard let self = self else {\n continuation.resume(throwing: MCPError.internalError(\"Transport deallocated\"))\n return\n }\n\n connection.send(\n content: Heartbeat().data,\n contentContext: .defaultMessage,\n isComplete: true,\n completion: .contentProcessed { [weak self] error in\n if let error = error {\n continuation.resume(throwing: error)\n } else {\n Task { [weak self] in\n await self?.setLastHeartbeatTime(Date())\n }\n continuation.resume()\n }\n })\n }\n\n logger.trace(\"Heartbeat sent\")\n }\n\n /// Handles connection failure\n ///\n /// - Parameters:\n /// - error: The error that caused the connection to fail\n /// - continuation: The continuation to resume with the error\n private func handleConnectionFailed(\n error: Swift.Error, continuation: CheckedContinuation\n ) async {\n if !connectionContinuationResumed {\n connectionContinuationResumed = true\n logger.error(\"Connection failed: \\(error)\")\n\n await handleReconnection(\n error: error,\n continuation: continuation,\n context: \"failure\"\n )\n }\n }\n\n /// Handles connection cancellation\n ///\n /// - Parameter continuation: The continuation to resume with cancellation error\n private func handleConnectionCancelled(continuation: CheckedContinuation)\n async\n {\n if !connectionContinuationResumed {\n connectionContinuationResumed = true\n logger.warning(\"Connection cancelled\")\n\n await handleReconnection(\n error: MCPError.internalError(\"Connection cancelled\"),\n continuation: continuation,\n context: \"cancellation\"\n )\n }\n }\n\n /// Common reconnection handling logic\n ///\n /// - Parameters:\n /// - error: The error that triggered the reconnection\n /// - continuation: The continuation to resume with the error\n /// - context: The context of the reconnection (for logging)\n private func handleReconnection(\n error: Swift.Error,\n continuation: CheckedContinuation,\n context: String\n ) async {\n if !isStopping,\n reconnectionConfig.enabled,\n reconnectAttempt < reconnectionConfig.maxAttempts\n {\n // Try to reconnect with exponential backoff\n reconnectAttempt += 1\n logger.info(\n \"Attempting reconnection after \\(context) (\\(reconnectAttempt)/\\(reconnectionConfig.maxAttempts))...\"\n )\n\n // Calculate backoff delay\n let delay = reconnectionConfig.backoffDelay(for: reconnectAttempt)\n\n // Schedule reconnection attempt after delay\n Task {\n try? await Task.sleep(for: .seconds(delay))\n if !isStopping {\n // Cancel the current connection before attempting to reconnect.\n self.connection.cancel()\n // Resume original continuation with error; outer logic or a new call to connect() will handle retry.\n continuation.resume(throwing: error)\n } else {\n continuation.resume(throwing: error) // Stopping, so fail.\n }\n }\n } else {\n // Not configured to reconnect, exceeded max attempts, or stopping\n self.connection.cancel() // Ensure connection is cancelled\n continuation.resume(throwing: error)\n }\n }\n\n /// Disconnects from the transport\n ///\n /// This cancels the NWConnection, finalizes the message stream,\n /// and releases associated resources.\n public func disconnect() async {\n guard isConnected else { return }\n\n // Mark as stopping to prevent reconnection attempts during disconnect\n isStopping = true\n isConnected = false\n\n // Cancel heartbeat task if it exists\n heartbeatTask?.cancel()\n heartbeatTask = nil\n\n connection.cancel()\n messageContinuation.finish()\n logger.info(\"Network transport disconnected\")\n }\n\n /// Sends data through the network connection\n ///\n /// This sends a JSON-RPC message through the NWConnection, adding a newline\n /// delimiter to mark the end of the message.\n ///\n /// - Parameter message: The JSON-RPC message to send\n /// - Throws: MCPError for transport failures or connection issues\n public func send(_ message: Data) async throws {\n guard isConnected else {\n throw MCPError.internalError(\"Transport not connected\")\n }\n\n // Add newline as delimiter\n var messageWithNewline = message\n messageWithNewline.append(UInt8(ascii: \"\\n\"))\n\n // Use a local actor-isolated variable to track continuation state\n var sendContinuationResumed = false\n\n try await withCheckedThrowingContinuation {\n [weak self] (continuation: CheckedContinuation) in\n guard let self = self else {\n continuation.resume(throwing: MCPError.internalError(\"Transport deallocated\"))\n return\n }\n\n connection.send(\n content: messageWithNewline,\n contentContext: .defaultMessage,\n isComplete: true,\n completion: .contentProcessed { [weak self] error in\n guard let self = self else { return }\n\n Task { @MainActor in\n if !sendContinuationResumed {\n sendContinuationResumed = true\n if let error = error {\n self.logger.error(\"Send error: \\(error)\")\n\n // Check if we should attempt to reconnect on send failure\n let isStopping = await self.isStopping // Await actor-isolated property\n if !isStopping && self.reconnectionConfig.enabled {\n let isConnected = await self.isConnected\n if isConnected {\n if error.isConnectionLost {\n self.logger.warning(\n \"Connection appears broken, will attempt to reconnect...\"\n )\n\n // Schedule connection restart\n Task { [weak self] in // Operate on self's executor\n guard let self = self else { return }\n\n await self.setIsConnected(false)\n\n try? await Task.sleep(for: .milliseconds(500))\n\n let currentIsStopping = await self.isStopping\n if !currentIsStopping {\n // Cancel the connection, then attempt to reconnect fully.\n self.connection.cancel()\n try? await self.connect()\n }\n }\n }\n }\n }\n\n continuation.resume(\n throwing: MCPError.internalError(\"Send error: \\(error)\"))\n } else {\n continuation.resume()\n }\n }\n }\n })\n }\n }\n\n /// Receives data in an async sequence\n ///\n /// This returns an AsyncThrowingStream that emits Data objects representing\n /// each JSON-RPC message received from the network connection.\n ///\n /// - Returns: An AsyncThrowingStream of Data objects\n public func receive() -> AsyncThrowingStream {\n return messageStream\n }\n\n /// Continuous loop to receive and process incoming messages\n ///\n /// This method runs continuously while the connection is active,\n /// receiving data and yielding complete messages to the message stream.\n /// Messages are delimited by newline characters.\n private func receiveLoop() async {\n var buffer = Data()\n var consecutiveEmptyReads = 0\n let maxConsecutiveEmptyReads = 5\n\n while isConnected && !Task.isCancelled && !isStopping {\n do {\n let newData = try await receiveData()\n\n // Check for EOF or empty data\n if newData.isEmpty {\n consecutiveEmptyReads += 1\n\n if consecutiveEmptyReads >= maxConsecutiveEmptyReads {\n logger.warning(\n \"Multiple consecutive empty reads (\\(consecutiveEmptyReads)), possible connection issue\"\n )\n\n // Check connection state\n if connection.state != .ready {\n logger.info(\"Connection no longer ready, exiting receive loop\")\n break\n }\n }\n\n // Brief pause before retry\n try await Task.sleep(for: .milliseconds(100))\n continue\n }\n\n // Check if this is a heartbeat message\n if Heartbeat.isHeartbeat(newData) {\n logger.trace(\"Received heartbeat from peer\")\n\n // Extract timestamp if available\n if let heartbeat = Heartbeat.from(data: newData) {\n logger.trace(\"Heartbeat timestamp: \\(heartbeat.timestamp)\")\n }\n\n // Reset the counter since we got valid data\n consecutiveEmptyReads = 0\n continue // Skip regular message processing for heartbeats\n }\n\n // Reset counter on successful data read\n consecutiveEmptyReads = 0\n buffer.append(newData)\n\n // Process complete messages\n while let newlineIndex = buffer.firstIndex(of: UInt8(ascii: \"\\n\")) {\n let messageData = buffer[.. Data {\n var receiveContinuationResumed = false\n\n return try await withCheckedThrowingContinuation {\n [weak self] (continuation: CheckedContinuation) in\n guard let self = self else {\n continuation.resume(throwing: MCPError.internalError(\"Transport deallocated\"))\n return\n }\n\n let maxLength = bufferConfig.maxReceiveBufferSize ?? Int.max\n connection.receive(minimumIncompleteLength: 1, maximumLength: maxLength) {\n content, _, isComplete, error in\n Task { @MainActor in\n if !receiveContinuationResumed {\n receiveContinuationResumed = true\n if let error = error {\n continuation.resume(throwing: MCPError.transportError(error))\n } else if let content = content {\n continuation.resume(returning: content)\n } else if isComplete {\n self.logger.trace(\"Connection completed by peer\")\n continuation.resume(throwing: MCPError.connectionClosed)\n } else {\n // EOF: Resume with empty data instead of throwing an error\n continuation.resume(returning: Data())\n }\n }\n }\n }\n }\n }\n\n private func setLastHeartbeatTime(_ time: Date) {\n self.lastHeartbeatTime = time\n }\n\n private func setIsConnected(_ connected: Bool) {\n self.isConnected = connected\n }\n }\n\n extension NWError {\n /// Whether this error indicates a connection has been lost or reset.\n fileprivate var isConnectionLost: Bool {\n let nsError = self as NSError\n return nsError.code == 57 // Socket is not connected (EHOSTUNREACH or ENOTCONN)\n || nsError.code == 54 // Connection reset by peer (ECONNRESET)\n }\n }\n#endif\n"], ["/swift-sdk/Sources/MCP/Base/Messages.swift", "import class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\nprivate let jsonrpc = \"2.0\"\n\npublic protocol NotRequired {\n init()\n}\n\npublic struct Empty: NotRequired, Hashable, Codable, Sendable {\n public init() {}\n}\n\nextension Value: NotRequired {\n public init() {\n self = .null\n }\n}\n\n// MARK: -\n\n/// A method that can be used to send requests and receive responses.\npublic protocol Method {\n /// The parameters of the method.\n associatedtype Parameters: Codable, Hashable, Sendable = Empty\n /// The result of the method.\n associatedtype Result: Codable, Hashable, Sendable = Empty\n /// The name of the method.\n static var name: String { get }\n}\n\n/// Type-erased method for request/response handling\nstruct AnyMethod: Method, Sendable {\n static var name: String { \"\" }\n typealias Parameters = Value\n typealias Result = Value\n}\n\nextension Method where Parameters == Empty {\n public static func request(id: ID = .random) -> Request {\n Request(id: id, method: name, params: Empty())\n }\n}\n\nextension Method where Result == Empty {\n public static func response(id: ID) -> Response {\n Response(id: id, result: Empty())\n }\n}\n\nextension Method {\n /// Create a request with the given parameters.\n public static func request(id: ID = .random, _ parameters: Self.Parameters) -> Request {\n Request(id: id, method: name, params: parameters)\n }\n\n /// Create a response with the given result.\n public static func response(id: ID, result: Self.Result) -> Response {\n Response(id: id, result: result)\n }\n\n /// Create a response with the given error.\n public static func response(id: ID, error: MCPError) -> Response {\n Response(id: id, error: error)\n }\n}\n\n// MARK: -\n\n/// A request message.\npublic struct Request: Hashable, Identifiable, Codable, Sendable {\n /// The request ID.\n public let id: ID\n /// The method name.\n public let method: String\n /// The request parameters.\n public let params: M.Parameters\n\n init(id: ID = .random, method: String, params: M.Parameters) {\n self.id = id\n self.method = method\n self.params = params\n }\n\n private enum CodingKeys: String, CodingKey {\n case jsonrpc, id, method, params\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(jsonrpc, forKey: .jsonrpc)\n try container.encode(id, forKey: .id)\n try container.encode(method, forKey: .method)\n try container.encode(params, forKey: .params)\n }\n}\n\nextension Request {\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let version = try container.decode(String.self, forKey: .jsonrpc)\n guard version == jsonrpc else {\n throw DecodingError.dataCorruptedError(\n forKey: .jsonrpc, in: container, debugDescription: \"Invalid JSON-RPC version\")\n }\n id = try container.decode(ID.self, forKey: .id)\n method = try container.decode(String.self, forKey: .method)\n\n if M.Parameters.self is NotRequired.Type {\n // For NotRequired parameters, use decodeIfPresent or init()\n params =\n (try container.decodeIfPresent(M.Parameters.self, forKey: .params)\n ?? (M.Parameters.self as! NotRequired.Type).init() as! M.Parameters)\n } else if let value = try? container.decode(M.Parameters.self, forKey: .params) {\n // If params exists and can be decoded, use it\n params = value\n } else if !container.contains(.params)\n || (try? container.decodeNil(forKey: .params)) == true\n {\n // If params is missing or explicitly null, use Empty for Empty parameters\n // or throw for non-Empty parameters\n if M.Parameters.self == Empty.self {\n params = Empty() as! M.Parameters\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Missing required params field\"))\n }\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Invalid params field\"))\n }\n }\n}\n\n/// A type-erased request for request/response handling\ntypealias AnyRequest = Request\n\nextension AnyRequest {\n init(_ request: Request) throws {\n let encoder = JSONEncoder()\n let decoder = JSONDecoder()\n\n let data = try encoder.encode(request)\n self = try decoder.decode(AnyRequest.self, from: data)\n }\n}\n\n/// A box for request handlers that can be type-erased\nclass RequestHandlerBox: @unchecked Sendable {\n func callAsFunction(_ request: AnyRequest) async throws -> AnyResponse {\n fatalError(\"Must override\")\n }\n}\n\n/// A typed request handler that can be used to handle requests of a specific type\nfinal class TypedRequestHandler: RequestHandlerBox, @unchecked Sendable {\n private let _handle: @Sendable (Request) async throws -> Response\n\n init(_ handler: @escaping @Sendable (Request) async throws -> Response) {\n self._handle = handler\n super.init()\n }\n\n override func callAsFunction(_ request: AnyRequest) async throws -> AnyResponse {\n let encoder = JSONEncoder()\n let decoder = JSONDecoder()\n\n // Create a concrete request from the type-erased one\n let data = try encoder.encode(request)\n let request = try decoder.decode(Request.self, from: data)\n\n // Handle with concrete type\n let response = try await _handle(request)\n\n // Convert result to AnyMethod response\n switch response.result {\n case .success(let result):\n let resultData = try encoder.encode(result)\n let resultValue = try decoder.decode(Value.self, from: resultData)\n return Response(id: response.id, result: resultValue)\n case .failure(let error):\n return Response(id: response.id, error: error)\n }\n }\n}\n\n// MARK: -\n\n/// A response message.\npublic struct Response: Hashable, Identifiable, Codable, Sendable {\n /// The response ID.\n public let id: ID\n /// The response result.\n public let result: Swift.Result\n\n public init(id: ID, result: M.Result) {\n self.id = id\n self.result = .success(result)\n }\n\n public init(id: ID, error: MCPError) {\n self.id = id\n self.result = .failure(error)\n }\n\n private enum CodingKeys: String, CodingKey {\n case jsonrpc, id, result, error\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(jsonrpc, forKey: .jsonrpc)\n try container.encode(id, forKey: .id)\n switch result {\n case .success(let result):\n try container.encode(result, forKey: .result)\n case .failure(let error):\n try container.encode(error, forKey: .error)\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let version = try container.decode(String.self, forKey: .jsonrpc)\n guard version == jsonrpc else {\n throw DecodingError.dataCorruptedError(\n forKey: .jsonrpc, in: container, debugDescription: \"Invalid JSON-RPC version\")\n }\n id = try container.decode(ID.self, forKey: .id)\n if let result = try? container.decode(M.Result.self, forKey: .result) {\n self.result = .success(result)\n } else if let error = try? container.decode(MCPError.self, forKey: .error) {\n self.result = .failure(error)\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Invalid response\"))\n }\n }\n}\n\n/// A type-erased response for request/response handling\ntypealias AnyResponse = Response\n\nextension AnyResponse {\n init(_ response: Response) throws {\n // Instead of re-encoding/decoding which might double-wrap the error,\n // directly transfer the properties\n self.id = response.id\n switch response.result {\n case .success(let result):\n // For success, we still need to convert the result to a Value\n let data = try JSONEncoder().encode(result)\n let resultValue = try JSONDecoder().decode(Value.self, from: data)\n self.result = .success(resultValue)\n case .failure(let error):\n // Keep the original error without re-encoding/decoding\n self.result = .failure(error)\n }\n }\n}\n\n// MARK: -\n\n/// A notification message.\npublic protocol Notification: Hashable, Codable, Sendable {\n /// The parameters of the notification.\n associatedtype Parameters: Hashable, Codable, Sendable = Empty\n /// The name of the notification.\n static var name: String { get }\n}\n\n/// A type-erased notification for message handling\nstruct AnyNotification: Notification, Sendable {\n static var name: String { \"\" }\n typealias Parameters = Value\n}\n\nextension AnyNotification {\n init(_ notification: some Notification) throws {\n let encoder = JSONEncoder()\n let decoder = JSONDecoder()\n\n let data = try encoder.encode(notification)\n self = try decoder.decode(AnyNotification.self, from: data)\n }\n}\n\n/// A message that can be used to send notifications.\npublic struct Message: Hashable, Codable, Sendable {\n /// The method name.\n public let method: String\n /// The notification parameters.\n public let params: N.Parameters\n\n public init(method: String, params: N.Parameters) {\n self.method = method\n self.params = params\n }\n\n private enum CodingKeys: String, CodingKey {\n case jsonrpc, method, params\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(jsonrpc, forKey: .jsonrpc)\n try container.encode(method, forKey: .method)\n if N.Parameters.self != Empty.self {\n try container.encode(params, forKey: .params)\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let version = try container.decode(String.self, forKey: .jsonrpc)\n guard version == jsonrpc else {\n throw DecodingError.dataCorruptedError(\n forKey: .jsonrpc, in: container, debugDescription: \"Invalid JSON-RPC version\")\n }\n method = try container.decode(String.self, forKey: .method)\n\n if N.Parameters.self is NotRequired.Type {\n // For NotRequired parameters, use decodeIfPresent or init()\n params =\n (try container.decodeIfPresent(N.Parameters.self, forKey: .params)\n ?? (N.Parameters.self as! NotRequired.Type).init() as! N.Parameters)\n } else if let value = try? container.decode(N.Parameters.self, forKey: .params) {\n // If params exists and can be decoded, use it\n params = value\n } else if !container.contains(.params)\n || (try? container.decodeNil(forKey: .params)) == true\n {\n // If params is missing or explicitly null, use Empty for Empty parameters\n // or throw for non-Empty parameters\n if N.Parameters.self == Empty.self {\n params = Empty() as! N.Parameters\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Missing required params field\"))\n }\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Invalid params field\"))\n }\n }\n}\n\n/// A type-erased message for message handling\ntypealias AnyMessage = Message\n\nextension Notification where Parameters == Empty {\n /// Create a message with empty parameters.\n public static func message() -> Message {\n Message(method: name, params: Empty())\n }\n}\n\nextension Notification {\n /// Create a message with the given parameters.\n public static func message(_ parameters: Parameters) -> Message {\n Message(method: name, params: parameters)\n }\n}\n\n/// A box for notification handlers that can be type-erased\nclass NotificationHandlerBox: @unchecked Sendable {\n func callAsFunction(_ notification: Message) async throws {}\n}\n\n/// A typed notification handler that can be used to handle notifications of a specific type\nfinal class TypedNotificationHandler: NotificationHandlerBox,\n @unchecked Sendable\n{\n private let _handle: @Sendable (Message) async throws -> Void\n\n init(_ handler: @escaping @Sendable (Message) async throws -> Void) {\n self._handle = handler\n super.init()\n }\n\n override func callAsFunction(_ notification: Message) async throws {\n // Create a concrete notification from the type-erased one\n let data = try JSONEncoder().encode(notification)\n let typedNotification = try JSONDecoder().decode(Message.self, from: data)\n\n try await _handle(typedNotification)\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Transports/StdioTransport.swift", "import Logging\n\nimport struct Foundation.Data\n\n#if canImport(System)\n import System\n#else\n @preconcurrency import SystemPackage\n#endif\n\n// Import for specific low-level operations not yet in Swift System\n#if canImport(Darwin)\n import Darwin.POSIX\n#elseif canImport(Glibc)\n import Glibc\n#endif\n\n#if canImport(Darwin) || canImport(Glibc)\n /// An implementation of the MCP stdio transport protocol.\n ///\n /// This transport implements the [stdio transport](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#stdio)\n /// specification from the Model Context Protocol.\n ///\n /// The stdio transport works by:\n /// - Reading JSON-RPC messages from standard input\n /// - Writing JSON-RPC messages to standard output\n /// - Using newline characters as message delimiters\n /// - Supporting non-blocking I/O operations\n ///\n /// This transport is the recommended option for most MCP applications due to its\n /// simplicity and broad platform support.\n ///\n /// - Important: This transport is available on Apple platforms and Linux distributions with glibc\n /// (Ubuntu, Debian, Fedora, CentOS, RHEL).\n ///\n /// ## Example Usage\n ///\n /// ```swift\n /// import MCP\n ///\n /// // Initialize the client\n /// let client = Client(name: \"MyApp\", version: \"1.0.0\")\n ///\n /// // Create a transport and connect\n /// let transport = StdioTransport()\n /// try await client.connect(transport: transport)\n /// ```\n public actor StdioTransport: Transport {\n private let input: FileDescriptor\n private let output: FileDescriptor\n /// Logger instance for transport-related events\n public nonisolated let logger: Logger\n\n private var isConnected = false\n private let messageStream: AsyncThrowingStream\n private let messageContinuation: AsyncThrowingStream.Continuation\n\n /// Creates a new stdio transport with the specified file descriptors\n ///\n /// - Parameters:\n /// - input: File descriptor for reading (defaults to standard input)\n /// - output: File descriptor for writing (defaults to standard output)\n /// - logger: Optional logger instance for transport events\n public init(\n input: FileDescriptor = FileDescriptor.standardInput,\n output: FileDescriptor = FileDescriptor.standardOutput,\n logger: Logger? = nil\n ) {\n self.input = input\n self.output = output\n self.logger =\n logger\n ?? Logger(\n label: \"mcp.transport.stdio\",\n factory: { _ in SwiftLogNoOpLogHandler() })\n\n // Create message stream\n var continuation: AsyncThrowingStream.Continuation!\n self.messageStream = AsyncThrowingStream { continuation = $0 }\n self.messageContinuation = continuation\n }\n\n /// Establishes connection with the transport\n ///\n /// This method configures the file descriptors for non-blocking I/O\n /// and starts the background message reading loop.\n ///\n /// - Throws: Error if the file descriptors cannot be configured\n public func connect() async throws {\n guard !isConnected else { return }\n\n // Set non-blocking mode\n try setNonBlocking(fileDescriptor: input)\n try setNonBlocking(fileDescriptor: output)\n\n isConnected = true\n logger.info(\"Transport connected successfully\")\n\n // Start reading loop in background\n Task {\n await readLoop()\n }\n }\n\n /// Configures a file descriptor for non-blocking I/O\n ///\n /// - Parameter fileDescriptor: The file descriptor to configure\n /// - Throws: Error if the operation fails\n private func setNonBlocking(fileDescriptor: FileDescriptor) throws {\n #if canImport(Darwin) || canImport(Glibc)\n // Get current flags\n let flags = fcntl(fileDescriptor.rawValue, F_GETFL)\n guard flags >= 0 else {\n throw MCPError.transportError(Errno(rawValue: CInt(errno)))\n }\n\n // Set non-blocking flag\n let result = fcntl(fileDescriptor.rawValue, F_SETFL, flags | O_NONBLOCK)\n guard result >= 0 else {\n throw MCPError.transportError(Errno(rawValue: CInt(errno)))\n }\n #else\n // For platforms where non-blocking operations aren't supported\n throw MCPError.internalError(\n \"Setting non-blocking mode not supported on this platform\")\n #endif\n }\n\n /// Continuous loop that reads and processes incoming messages\n ///\n /// This method runs in the background while the transport is connected,\n /// parsing complete messages delimited by newlines and yielding them\n /// to the message stream.\n private func readLoop() async {\n let bufferSize = 4096\n var buffer = [UInt8](repeating: 0, count: bufferSize)\n var pendingData = Data()\n\n while isConnected && !Task.isCancelled {\n do {\n let bytesRead = try buffer.withUnsafeMutableBufferPointer { pointer in\n try input.read(into: UnsafeMutableRawBufferPointer(pointer))\n }\n\n if bytesRead == 0 {\n logger.notice(\"EOF received\")\n break\n }\n\n pendingData.append(Data(buffer[.. 0 {\n remaining = remaining.dropFirst(written)\n }\n } catch let error where MCPError.isResourceTemporarilyUnavailable(error) {\n try await Task.sleep(for: .milliseconds(10))\n continue\n } catch {\n throw MCPError.transportError(error)\n }\n }\n }\n\n /// Receives messages from the transport.\n ///\n /// Messages may be individual JSON-RPC requests, notifications, responses,\n /// or batches containing multiple requests/notifications encoded as JSON arrays.\n /// Each message is guaranteed to be a complete JSON object or array.\n ///\n /// - Returns: An AsyncThrowingStream of Data objects representing JSON-RPC messages\n public func receive() -> AsyncThrowingStream {\n return messageStream\n }\n }\n#endif\n"], ["/swift-sdk/Sources/MCP/Base/Value.swift", "import struct Foundation.Data\nimport class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\n/// A codable value.\npublic enum Value: Hashable, Sendable {\n case null\n case bool(Bool)\n case int(Int)\n case double(Double)\n case string(String)\n case data(mimeType: String? = nil, Data)\n case array([Value])\n case object([String: Value])\n\n /// Create a `Value` from a `Codable` value.\n /// - Parameter value: The codable value\n /// - Returns: A value\n public init(_ value: T) throws {\n if let valueAsValue = value as? Value {\n self = valueAsValue\n } else {\n let data = try JSONEncoder().encode(value)\n self = try JSONDecoder().decode(Value.self, from: data)\n }\n }\n\n /// Returns whether the value is `null`.\n public var isNull: Bool {\n return self == .null\n }\n\n /// Returns the `Bool` value if the value is a `bool`,\n /// otherwise returns `nil`.\n public var boolValue: Bool? {\n guard case let .bool(value) = self else { return nil }\n return value\n }\n\n /// Returns the `Int` value if the value is an `integer`,\n /// otherwise returns `nil`.\n public var intValue: Int? {\n guard case let .int(value) = self else { return nil }\n return value\n }\n\n /// Returns the `Double` value if the value is a `double`,\n /// otherwise returns `nil`.\n public var doubleValue: Double? {\n guard case let .double(value) = self else { return nil }\n return value\n }\n\n /// Returns the `String` value if the value is a `string`,\n /// otherwise returns `nil`.\n public var stringValue: String? {\n guard case let .string(value) = self else { return nil }\n return value\n }\n\n /// Returns the data value and optional MIME type if the value is `data`,\n /// otherwise returns `nil`.\n public var dataValue: (mimeType: String?, Data)? {\n guard case let .data(mimeType: mimeType, data) = self else { return nil }\n return (mimeType: mimeType, data)\n }\n\n /// Returns the `[Value]` value if the value is an `array`,\n /// otherwise returns `nil`.\n public var arrayValue: [Value]? {\n guard case let .array(value) = self else { return nil }\n return value\n }\n\n /// Returns the `[String: Value]` value if the value is an `object`,\n /// otherwise returns `nil`.\n public var objectValue: [String: Value]? {\n guard case let .object(value) = self else { return nil }\n return value\n }\n}\n\n// MARK: - Codable\n\nextension Value: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n\n if container.decodeNil() {\n self = .null\n } else if let value = try? container.decode(Bool.self) {\n self = .bool(value)\n } else if let value = try? container.decode(Int.self) {\n self = .int(value)\n } else if let value = try? container.decode(Double.self) {\n self = .double(value)\n } else if let value = try? container.decode(String.self) {\n if Data.isDataURL(string: value),\n case let (mimeType, data)? = Data.parseDataURL(value)\n {\n self = .data(mimeType: mimeType, data)\n } else {\n self = .string(value)\n }\n } else if let value = try? container.decode([Value].self) {\n self = .array(value)\n } else if let value = try? container.decode([String: Value].self) {\n self = .object(value)\n } else {\n throw DecodingError.dataCorruptedError(\n in: container, debugDescription: \"Value type not found\")\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n\n switch self {\n case .null:\n try container.encodeNil()\n case .bool(let value):\n try container.encode(value)\n case .int(let value):\n try container.encode(value)\n case .double(let value):\n try container.encode(value)\n case .string(let value):\n try container.encode(value)\n case let .data(mimeType, value):\n try container.encode(value.dataURLEncoded(mimeType: mimeType))\n case .array(let value):\n try container.encode(value)\n case .object(let value):\n try container.encode(value)\n }\n }\n}\n\nextension Value: CustomStringConvertible {\n public var description: String {\n switch self {\n case .null:\n return \"\"\n case .bool(let value):\n return value.description\n case .int(let value):\n return value.description\n case .double(let value):\n return value.description\n case .string(let value):\n return value.description\n case let .data(mimeType, value):\n return value.dataURLEncoded(mimeType: mimeType)\n case .array(let value):\n return value.description\n case .object(let value):\n return value.description\n }\n }\n}\n\n// MARK: - ExpressibleByNilLiteral\n\nextension Value: ExpressibleByNilLiteral {\n public init(nilLiteral: ()) {\n self = .null\n }\n}\n\n// MARK: - ExpressibleByBooleanLiteral\n\nextension Value: ExpressibleByBooleanLiteral {\n public init(booleanLiteral value: Bool) {\n self = .bool(value)\n }\n}\n\n// MARK: - ExpressibleByIntegerLiteral\n\nextension Value: ExpressibleByIntegerLiteral {\n public init(integerLiteral value: Int) {\n self = .int(value)\n }\n}\n\n// MARK: - ExpressibleByFloatLiteral\n\nextension Value: ExpressibleByFloatLiteral {\n public init(floatLiteral value: Double) {\n self = .double(value)\n }\n}\n\n// MARK: - ExpressibleByStringLiteral\n\nextension Value: ExpressibleByStringLiteral {\n public init(stringLiteral value: String) {\n self = .string(value)\n }\n}\n\n// MARK: - ExpressibleByArrayLiteral\n\nextension Value: ExpressibleByArrayLiteral {\n public init(arrayLiteral elements: Value...) {\n self = .array(elements)\n }\n}\n\n// MARK: - ExpressibleByDictionaryLiteral\n\nextension Value: ExpressibleByDictionaryLiteral {\n public init(dictionaryLiteral elements: (String, Value)...) {\n var dictionary: [String: Value] = [:]\n for (key, value) in elements {\n dictionary[key] = value\n }\n self = .object(dictionary)\n }\n}\n\n// MARK: - ExpressibleByStringInterpolation\n\nextension Value: ExpressibleByStringInterpolation {\n public struct StringInterpolation: StringInterpolationProtocol {\n var stringValue: String\n\n public init(literalCapacity: Int, interpolationCount: Int) {\n self.stringValue = \"\"\n self.stringValue.reserveCapacity(literalCapacity + interpolationCount)\n }\n\n public mutating func appendLiteral(_ literal: String) {\n self.stringValue.append(literal)\n }\n\n public mutating func appendInterpolation(_ value: T) {\n self.stringValue.append(value.description)\n }\n }\n\n public init(stringInterpolation: StringInterpolation) {\n self = .string(stringInterpolation.stringValue)\n }\n}\n\n// MARK: - Standard Library Type Extensions\n\nextension Bool {\n /// Creates a boolean value from a `Value` instance.\n ///\n /// In strict mode, only `.bool` values are converted. In non-strict mode, the following conversions are supported:\n /// - Integers: `1` is `true`, `0` is `false`\n /// - Doubles: `1.0` is `true`, `0.0` is `false`\n /// - Strings (lowercase only):\n /// - `true`: \"true\", \"t\", \"yes\", \"y\", \"on\", \"1\"\n /// - `false`: \"false\", \"f\", \"no\", \"n\", \"off\", \"0\"\n ///\n /// - Parameters:\n /// - value: The `Value` to convert\n /// - strict: When `true`, only converts from `.bool` values. Defaults to `true`\n /// - Returns: A boolean value if conversion is possible, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// Bool(Value.bool(true)) // Returns true\n /// Bool(Value.int(1), strict: false) // Returns true\n /// Bool(Value.string(\"yes\"), strict: false) // Returns true\n /// ```\n public init?(_ value: Value, strict: Bool = true) {\n switch value {\n case .bool(let b):\n self = b\n case .int(let i) where !strict:\n switch i {\n case 0: self = false\n case 1: self = true\n default: return nil\n }\n case .double(let d) where !strict:\n switch d {\n case 0.0: self = false\n case 1.0: self = true\n default: return nil\n }\n case .string(let s) where !strict:\n switch s {\n case \"true\", \"t\", \"yes\", \"y\", \"on\", \"1\":\n self = true\n case \"false\", \"f\", \"no\", \"n\", \"off\", \"0\":\n self = false\n default:\n return nil\n }\n default:\n return nil\n }\n }\n}\n\nextension Int {\n /// Creates an integer value from a `Value` instance.\n ///\n /// In strict mode, only `.int` values are converted. In non-strict mode, the following conversions are supported:\n /// - Doubles: Converted if they can be represented exactly as integers\n /// - Strings: Parsed if they contain a valid integer representation\n ///\n /// - Parameters:\n /// - value: The `Value` to convert\n /// - strict: When `true`, only converts from `.int` values. Defaults to `true`\n /// - Returns: An integer value if conversion is possible, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// Int(Value.int(42)) // Returns 42\n /// Int(Value.double(42.0), strict: false) // Returns 42\n /// Int(Value.string(\"42\"), strict: false) // Returns 42\n /// Int(Value.double(42.5), strict: false) // Returns nil\n /// ```\n public init?(_ value: Value, strict: Bool = true) {\n switch value {\n case .int(let i):\n self = i\n case .double(let d) where !strict:\n guard let intValue = Int(exactly: d) else { return nil }\n self = intValue\n case .string(let s) where !strict:\n guard let intValue = Int(s) else { return nil }\n self = intValue\n default:\n return nil\n }\n }\n}\n\nextension Double {\n /// Creates a double value from a `Value` instance.\n ///\n /// In strict mode, converts from `.double` and `.int` values. In non-strict mode, the following conversions are supported:\n /// - Integers: Converted to their double representation\n /// - Strings: Parsed if they contain a valid floating-point representation\n ///\n /// - Parameters:\n /// - value: The `Value` to convert\n /// - strict: When `true`, only converts from `.double` and `.int` values. Defaults to `true`\n /// - Returns: A double value if conversion is possible, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// Double(Value.double(42.5)) // Returns 42.5\n /// Double(Value.int(42)) // Returns 42.0\n /// Double(Value.string(\"42.5\"), strict: false) // Returns 42.5\n /// ```\n public init?(_ value: Value, strict: Bool = true) {\n switch value {\n case .double(let d):\n self = d\n case .int(let i):\n self = Double(i)\n case .string(let s) where !strict:\n guard let doubleValue = Double(s) else { return nil }\n self = doubleValue\n default:\n return nil\n }\n }\n}\n\nextension String {\n /// Creates a string value from a `Value` instance.\n ///\n /// In strict mode, only `.string` values are converted. In non-strict mode, the following conversions are supported:\n /// - Integers: Converted to their string representation\n /// - Doubles: Converted to their string representation\n /// - Booleans: Converted to \"true\" or \"false\"\n ///\n /// - Parameters:\n /// - value: The `Value` to convert\n /// - strict: When `true`, only converts from `.string` values. Defaults to `true`\n /// - Returns: A string value if conversion is possible, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// String(Value.string(\"hello\")) // Returns \"hello\"\n /// String(Value.int(42), strict: false) // Returns \"42\"\n /// String(Value.bool(true), strict: false) // Returns \"true\"\n /// ```\n public init?(_ value: Value, strict: Bool = true) {\n switch value {\n case .string(let s):\n self = s\n case .int(let i) where !strict:\n self = String(i)\n case .double(let d) where !strict:\n self = String(d)\n case .bool(let b) where !strict:\n self = String(b)\n default:\n return nil\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Server/Tools.swift", "import Foundation\n\n/// The Model Context Protocol (MCP) allows servers to expose tools\n/// that can be invoked by language models.\n/// Tools enable models to interact with external systems, such as\n/// querying databases, calling APIs, or performing computations.\n/// Each tool is uniquely identified by a name and includes metadata\n/// describing its schema.\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/\npublic struct Tool: Hashable, Codable, Sendable {\n /// The tool name\n public let name: String\n /// The tool description\n public let description: String\n /// The tool input schema\n public let inputSchema: Value?\n\n /// Annotations that provide display-facing and operational information for a Tool.\n ///\n /// - Note: All properties in `ToolAnnotations` are **hints**.\n /// They are not guaranteed to provide a faithful description of\n /// tool behavior (including descriptive properties like `title`).\n ///\n /// Clients should never make tool use decisions based on `ToolAnnotations`\n /// received from untrusted servers.\n public struct Annotations: Hashable, Codable, Sendable, ExpressibleByNilLiteral {\n /// A human-readable title for the tool\n public var title: String?\n\n /// If true, the tool may perform destructive updates to its environment.\n /// If false, the tool performs only additive updates.\n /// (This property is meaningful only when `readOnlyHint == false`)\n ///\n /// When unspecified, the implicit default is `true`.\n public var destructiveHint: Bool?\n\n /// If true, calling the tool repeatedly with the same arguments\n /// will have no additional effect on its environment.\n /// (This property is meaningful only when `readOnlyHint == false`)\n ///\n /// When unspecified, the implicit default is `false`.\n public var idempotentHint: Bool?\n\n /// If true, this tool may interact with an \"open world\" of external\n /// entities. If false, the tool's domain of interaction is closed.\n /// For example, the world of a web search tool is open, whereas that\n /// of a memory tool is not.\n ///\n /// When unspecified, the implicit default is `true`.\n public var openWorldHint: Bool?\n\n /// If true, the tool does not modify its environment.\n ///\n /// When unspecified, the implicit default is `false`.\n public var readOnlyHint: Bool?\n\n /// Returns true if all properties are nil\n public var isEmpty: Bool {\n title == nil && readOnlyHint == nil && destructiveHint == nil && idempotentHint == nil\n && openWorldHint == nil\n }\n\n public init(\n title: String? = nil,\n readOnlyHint: Bool? = nil,\n destructiveHint: Bool? = nil,\n idempotentHint: Bool? = nil,\n openWorldHint: Bool? = nil\n ) {\n self.title = title\n self.readOnlyHint = readOnlyHint\n self.destructiveHint = destructiveHint\n self.idempotentHint = idempotentHint\n self.openWorldHint = openWorldHint\n }\n\n /// Initialize an empty annotations object\n public init(nilLiteral: ()) {}\n }\n\n /// Annotations that provide display-facing and operational information\n public var annotations: Annotations\n\n /// Initialize a tool with a name, description, input schema, and annotations\n public init(\n name: String,\n description: String,\n inputSchema: Value? = nil,\n annotations: Annotations = nil\n ) {\n self.name = name\n self.description = description\n self.inputSchema = inputSchema\n self.annotations = annotations\n }\n\n /// Content types that can be returned by a tool\n public enum Content: Hashable, Codable, Sendable {\n /// Text content\n case text(String)\n /// Image content\n case image(data: String, mimeType: String, metadata: [String: String]?)\n /// Audio content\n case audio(data: String, mimeType: String)\n /// Embedded resource content\n case resource(uri: String, mimeType: String, text: String?)\n\n private enum CodingKeys: String, CodingKey {\n case type\n case text\n case image\n case resource\n case audio\n case uri\n case mimeType\n case data\n case metadata\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let type = try container.decode(String.self, forKey: .type)\n\n switch type {\n case \"text\":\n let text = try container.decode(String.self, forKey: .text)\n self = .text(text)\n case \"image\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n let metadata = try container.decodeIfPresent(\n [String: String].self, forKey: .metadata)\n self = .image(data: data, mimeType: mimeType, metadata: metadata)\n case \"audio\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n self = .audio(data: data, mimeType: mimeType)\n case \"resource\":\n let uri = try container.decode(String.self, forKey: .uri)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n let text = try container.decodeIfPresent(String.self, forKey: .text)\n self = .resource(uri: uri, mimeType: mimeType, text: text)\n default:\n throw DecodingError.dataCorruptedError(\n forKey: .type, in: container, debugDescription: \"Unknown tool content type\")\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n\n switch self {\n case .text(let text):\n try container.encode(\"text\", forKey: .type)\n try container.encode(text, forKey: .text)\n case .image(let data, let mimeType, let metadata):\n try container.encode(\"image\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n try container.encodeIfPresent(metadata, forKey: .metadata)\n case .audio(let data, let mimeType):\n try container.encode(\"audio\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n case .resource(let uri, let mimeType, let text):\n try container.encode(\"resource\", forKey: .type)\n try container.encode(uri, forKey: .uri)\n try container.encode(mimeType, forKey: .mimeType)\n try container.encodeIfPresent(text, forKey: .text)\n }\n }\n }\n\n private enum CodingKeys: String, CodingKey {\n case name\n case description\n case inputSchema\n case annotations\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n name = try container.decode(String.self, forKey: .name)\n description = try container.decode(String.self, forKey: .description)\n inputSchema = try container.decodeIfPresent(Value.self, forKey: .inputSchema)\n annotations =\n try container.decodeIfPresent(Tool.Annotations.self, forKey: .annotations) ?? .init()\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(name, forKey: .name)\n try container.encode(description, forKey: .description)\n if let schema = inputSchema {\n try container.encode(schema, forKey: .inputSchema)\n }\n if !annotations.isEmpty {\n try container.encode(annotations, forKey: .annotations)\n }\n }\n}\n\n// MARK: -\n\n/// To discover available tools, clients send a `tools/list` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/#listing-tools\npublic enum ListTools: Method {\n public static let name = \"tools/list\"\n\n public struct Parameters: NotRequired, Hashable, Codable, Sendable {\n public let cursor: String?\n\n public init() {\n self.cursor = nil\n }\n\n public init(cursor: String) {\n self.cursor = cursor\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let tools: [Tool]\n public let nextCursor: String?\n\n public init(tools: [Tool], nextCursor: String? = nil) {\n self.tools = tools\n self.nextCursor = nextCursor\n }\n }\n}\n\n/// To call a tool, clients send a `tools/call` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/#calling-tools\npublic enum CallTool: Method {\n public static let name = \"tools/call\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let name: String\n public let arguments: [String: Value]?\n\n public init(name: String, arguments: [String: Value]? = nil) {\n self.name = name\n self.arguments = arguments\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let content: [Tool.Content]\n public let isError: Bool?\n\n public init(content: [Tool.Content], isError: Bool? = nil) {\n self.content = content\n self.isError = isError\n }\n }\n}\n\n/// When the list of available tools changes, servers that declared the listChanged capability SHOULD send a notification:\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/#list-changed-notification\npublic struct ToolListChangedNotification: Notification {\n public static let name: String = \"notifications/tools/list_changed\"\n}\n"], ["/swift-sdk/Sources/MCP/Client/Sampling.swift", "import Foundation\n\n/// The Model Context Protocol (MCP) allows servers to request LLM completions\n/// through the client, enabling sophisticated agentic behaviors while maintaining\n/// security and privacy.\n///\n/// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/sampling#how-sampling-works\npublic enum Sampling {\n /// A message in the conversation history.\n public struct Message: Hashable, Codable, Sendable {\n /// The message role\n public enum Role: String, Hashable, Codable, Sendable {\n /// A user message\n case user\n /// An assistant message\n case assistant\n }\n\n /// The message role\n public let role: Role\n /// The message content\n public let content: Content\n\n /// Creates a message with the specified role and content\n @available(\n *, deprecated, message: \"Use static factory methods .user(_:) or .assistant(_:) instead\"\n )\n public init(role: Role, content: Content) {\n self.role = role\n self.content = content\n }\n\n /// Private initializer for convenience methods to avoid deprecation warnings\n private init(_role role: Role, _content content: Content) {\n self.role = role\n self.content = content\n }\n\n /// Creates a user message with the specified content\n public static func user(_ content: Content) -> Message {\n return Message(_role: .user, _content: content)\n }\n\n /// Creates an assistant message with the specified content\n public static func assistant(_ content: Content) -> Message {\n return Message(_role: .assistant, _content: content)\n }\n\n /// Content types for sampling messages\n public enum Content: Hashable, Sendable {\n /// Text content\n case text(String)\n /// Image content\n case image(data: String, mimeType: String)\n }\n }\n\n /// Model preferences for sampling requests\n public struct ModelPreferences: Hashable, Codable, Sendable {\n /// Model hints for selection\n public struct Hint: Hashable, Codable, Sendable {\n /// Suggested model name/family\n public let name: String?\n\n public init(name: String? = nil) {\n self.name = name\n }\n }\n\n /// Array of model name suggestions that clients can use to select an appropriate model\n public let hints: [Hint]?\n /// Importance of minimizing costs (0-1 normalized)\n public let costPriority: UnitInterval?\n /// Importance of low latency response (0-1 normalized)\n public let speedPriority: UnitInterval?\n /// Importance of advanced model capabilities (0-1 normalized)\n public let intelligencePriority: UnitInterval?\n\n public init(\n hints: [Hint]? = nil,\n costPriority: UnitInterval? = nil,\n speedPriority: UnitInterval? = nil,\n intelligencePriority: UnitInterval? = nil\n ) {\n self.hints = hints\n self.costPriority = costPriority\n self.speedPriority = speedPriority\n self.intelligencePriority = intelligencePriority\n }\n }\n\n /// Context inclusion options for sampling requests\n public enum ContextInclusion: String, Hashable, Codable, Sendable {\n /// No additional context\n case none\n /// Include context from the requesting server\n case thisServer\n /// Include context from all connected MCP servers\n case allServers\n }\n\n /// Stop reason for sampling completion\n public enum StopReason: String, Hashable, Codable, Sendable {\n /// Natural end of turn\n case endTurn\n /// Hit a stop sequence\n case stopSequence\n /// Reached maximum tokens\n case maxTokens\n }\n}\n\n// MARK: - Codable\n\nextension Sampling.Message.Content: Codable {\n private enum CodingKeys: String, CodingKey {\n case type, text, data, mimeType\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let type = try container.decode(String.self, forKey: .type)\n\n switch type {\n case \"text\":\n let text = try container.decode(String.self, forKey: .text)\n self = .text(text)\n case \"image\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n self = .image(data: data, mimeType: mimeType)\n default:\n throw DecodingError.dataCorruptedError(\n forKey: .type, in: container,\n debugDescription: \"Unknown sampling message content type\")\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n\n switch self {\n case .text(let text):\n try container.encode(\"text\", forKey: .type)\n try container.encode(text, forKey: .text)\n case .image(let data, let mimeType):\n try container.encode(\"image\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n }\n }\n}\n\n// MARK: - ExpressibleByStringLiteral\n\nextension Sampling.Message.Content: ExpressibleByStringLiteral {\n public init(stringLiteral value: String) {\n self = .text(value)\n }\n}\n\n// MARK: - ExpressibleByStringInterpolation\n\nextension Sampling.Message.Content: ExpressibleByStringInterpolation {\n public init(stringInterpolation: DefaultStringInterpolation) {\n self = .text(String(stringInterpolation: stringInterpolation))\n }\n}\n\n// MARK: -\n\n/// To request sampling from a client, servers send a `sampling/createMessage` request.\n/// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/sampling#how-sampling-works\npublic enum CreateSamplingMessage: Method {\n public static let name = \"sampling/createMessage\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n /// The conversation history to send to the LLM\n public let messages: [Sampling.Message]\n /// Model selection preferences\n public let modelPreferences: Sampling.ModelPreferences?\n /// Optional system prompt\n public let systemPrompt: String?\n /// What MCP context to include\n public let includeContext: Sampling.ContextInclusion?\n /// Controls randomness (0.0 to 1.0)\n public let temperature: Double?\n /// Maximum tokens to generate\n public let maxTokens: Int\n /// Array of sequences that stop generation\n public let stopSequences: [String]?\n /// Additional provider-specific parameters\n public let metadata: [String: Value]?\n\n public init(\n messages: [Sampling.Message],\n modelPreferences: Sampling.ModelPreferences? = nil,\n systemPrompt: String? = nil,\n includeContext: Sampling.ContextInclusion? = nil,\n temperature: Double? = nil,\n maxTokens: Int,\n stopSequences: [String]? = nil,\n metadata: [String: Value]? = nil\n ) {\n self.messages = messages\n self.modelPreferences = modelPreferences\n self.systemPrompt = systemPrompt\n self.includeContext = includeContext\n self.temperature = temperature\n self.maxTokens = maxTokens\n self.stopSequences = stopSequences\n self.metadata = metadata\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n /// Name of the model used\n public let model: String\n /// Why sampling stopped\n public let stopReason: Sampling.StopReason?\n /// The role of the completion\n public let role: Sampling.Message.Role\n /// The completion content\n public let content: Sampling.Message.Content\n\n public init(\n model: String,\n stopReason: Sampling.StopReason? = nil,\n role: Sampling.Message.Role,\n content: Sampling.Message.Content\n ) {\n self.model = model\n self.stopReason = stopReason\n self.role = role\n self.content = content\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Server/Prompts.swift", "import Foundation\n\n/// The Model Context Protocol (MCP) provides a standardized way\n/// for servers to expose prompt templates to clients.\n/// Prompts allow servers to provide structured messages and instructions\n/// for interacting with language models.\n/// Clients can discover available prompts, retrieve their contents,\n/// and provide arguments to customize them.\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/\npublic struct Prompt: Hashable, Codable, Sendable {\n /// The prompt name\n public let name: String\n /// The prompt description\n public let description: String?\n /// The prompt arguments\n public let arguments: [Argument]?\n\n public init(name: String, description: String? = nil, arguments: [Argument]? = nil) {\n self.name = name\n self.description = description\n self.arguments = arguments\n }\n\n /// An argument for a prompt\n public struct Argument: Hashable, Codable, Sendable {\n /// The argument name\n public let name: String\n /// The argument description\n public let description: String?\n /// Whether the argument is required\n public let required: Bool?\n\n public init(name: String, description: String? = nil, required: Bool? = nil) {\n self.name = name\n self.description = description\n self.required = required\n }\n }\n\n /// A message in a prompt\n public struct Message: Hashable, Codable, Sendable {\n /// The message role\n public enum Role: String, Hashable, Codable, Sendable {\n /// A user message\n case user\n /// An assistant message\n case assistant\n }\n\n /// The message role\n public let role: Role\n /// The message content\n public let content: Content\n\n /// Creates a message with the specified role and content\n @available(\n *, deprecated, message: \"Use static factory methods .user(_:) or .assistant(_:) instead\"\n )\n public init(role: Role, content: Content) {\n self.role = role\n self.content = content\n }\n\n /// Private initializer for convenience methods to avoid deprecation warnings\n private init(_role role: Role, _content content: Content) {\n self.role = role\n self.content = content\n }\n\n /// Creates a user message with the specified content\n public static func user(_ content: Content) -> Message {\n return Message(_role: .user, _content: content)\n }\n\n /// Creates an assistant message with the specified content\n public static func assistant(_ content: Content) -> Message {\n return Message(_role: .assistant, _content: content)\n }\n\n /// Content types for messages\n public enum Content: Hashable, Sendable {\n /// Text content\n case text(text: String)\n /// Image content\n case image(data: String, mimeType: String)\n /// Audio content\n case audio(data: String, mimeType: String)\n /// Embedded resource content\n case resource(uri: String, mimeType: String, text: String?, blob: String?)\n }\n }\n\n /// Reference type for prompts\n public struct Reference: Hashable, Codable, Sendable {\n /// The prompt reference name\n public let name: String\n\n public init(name: String) {\n self.name = name\n }\n\n private enum CodingKeys: String, CodingKey {\n case type, name\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(\"ref/prompt\", forKey: .type)\n try container.encode(name, forKey: .name)\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n _ = try container.decode(String.self, forKey: .type)\n name = try container.decode(String.self, forKey: .name)\n }\n }\n}\n\n// MARK: - Codable\n\nextension Prompt.Message.Content: Codable {\n private enum CodingKeys: String, CodingKey {\n case type, text, data, mimeType, uri, blob\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n\n switch self {\n case .text(let text):\n try container.encode(\"text\", forKey: .type)\n try container.encode(text, forKey: .text)\n case .image(let data, let mimeType):\n try container.encode(\"image\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n case .audio(let data, let mimeType):\n try container.encode(\"audio\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n case .resource(let uri, let mimeType, let text, let blob):\n try container.encode(\"resource\", forKey: .type)\n try container.encode(uri, forKey: .uri)\n try container.encode(mimeType, forKey: .mimeType)\n try container.encodeIfPresent(text, forKey: .text)\n try container.encodeIfPresent(blob, forKey: .blob)\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let type = try container.decode(String.self, forKey: .type)\n\n switch type {\n case \"text\":\n let text = try container.decode(String.self, forKey: .text)\n self = .text(text: text)\n case \"image\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n self = .image(data: data, mimeType: mimeType)\n case \"audio\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n self = .audio(data: data, mimeType: mimeType)\n case \"resource\":\n let uri = try container.decode(String.self, forKey: .uri)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n let text = try container.decodeIfPresent(String.self, forKey: .text)\n let blob = try container.decodeIfPresent(String.self, forKey: .blob)\n self = .resource(uri: uri, mimeType: mimeType, text: text, blob: blob)\n default:\n throw DecodingError.dataCorruptedError(\n forKey: .type,\n in: container,\n debugDescription: \"Unknown content type\")\n }\n }\n}\n\n// MARK: - ExpressibleByStringLiteral\n\nextension Prompt.Message.Content: ExpressibleByStringLiteral {\n public init(stringLiteral value: String) {\n self = .text(text: value)\n }\n}\n\n// MARK: - ExpressibleByStringInterpolation\n\nextension Prompt.Message.Content: ExpressibleByStringInterpolation {\n public init(stringInterpolation: DefaultStringInterpolation) {\n self = .text(text: String(stringInterpolation: stringInterpolation))\n }\n}\n\n// MARK: -\n\n/// To retrieve available prompts, clients send a `prompts/list` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/#listing-prompts\npublic enum ListPrompts: Method {\n public static let name: String = \"prompts/list\"\n\n public struct Parameters: NotRequired, Hashable, Codable, Sendable {\n public let cursor: String?\n\n public init() {\n self.cursor = nil\n }\n\n public init(cursor: String) {\n self.cursor = cursor\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let prompts: [Prompt]\n public let nextCursor: String?\n\n public init(prompts: [Prompt], nextCursor: String? = nil) {\n self.prompts = prompts\n self.nextCursor = nextCursor\n }\n }\n}\n\n/// To retrieve a specific prompt, clients send a `prompts/get` request.\n/// Arguments may be auto-completed through the completion API.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/#getting-a-prompt\npublic enum GetPrompt: Method {\n public static let name: String = \"prompts/get\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let name: String\n public let arguments: [String: Value]?\n\n public init(name: String, arguments: [String: Value]? = nil) {\n self.name = name\n self.arguments = arguments\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let description: String?\n public let messages: [Prompt.Message]\n\n public init(description: String?, messages: [Prompt.Message]) {\n self.description = description\n self.messages = messages\n }\n }\n}\n\n/// When the list of available prompts changes, servers that declared the listChanged capability SHOULD send a notification.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/#list-changed-notification\npublic struct PromptListChangedNotification: Notification {\n public static let name: String = \"notifications/prompts/list_changed\"\n}\n"], ["/swift-sdk/Sources/MCP/Base/UnitInterval.swift", "/// A value constrained to the range 0.0 to 1.0, inclusive.\n///\n/// `UnitInterval` represents a normalized value that is guaranteed to be within\n/// the unit interval [0, 1]. This type is commonly used for representing\n/// priorities in sampling request model preferences.\n///\n/// The type provides safe initialization that returns `nil` for values outside\n/// the valid range, ensuring that all instances contain valid unit interval values.\n///\n/// - Example:\n/// ```swift\n/// let zero: UnitInterval = 0 // 0.0\n/// let half = UnitInterval(0.5)! // 0.5\n/// let one: UnitInterval = 1.0 // 1.0\n/// let invalid = UnitInterval(1.5) // nil\n/// ```\npublic struct UnitInterval: Hashable, Sendable {\n private let value: Double\n\n /// Creates a unit interval value from a `Double`.\n ///\n /// - Parameter value: A double value that must be in the range 0.0...1.0\n /// - Returns: A `UnitInterval` instance if the value is valid, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// let valid = UnitInterval(0.75) // Optional(0.75)\n /// let invalid = UnitInterval(-0.1) // nil\n /// let boundary = UnitInterval(1.0) // Optional(1.0)\n /// ```\n public init?(_ value: Double) {\n guard (0...1).contains(value) else { return nil }\n self.value = value\n }\n\n /// The underlying double value.\n ///\n /// This property provides access to the raw double value that is guaranteed\n /// to be within the range [0, 1].\n ///\n /// - Returns: The double value between 0.0 and 1.0, inclusive\n public var doubleValue: Double { value }\n}\n\n// MARK: - Comparable\n\nextension UnitInterval: Comparable {\n public static func < (lhs: UnitInterval, rhs: UnitInterval) -> Bool {\n lhs.value < rhs.value\n }\n}\n\n// MARK: - CustomStringConvertible\n\nextension UnitInterval: CustomStringConvertible {\n public var description: String { \"\\(value)\" }\n}\n\n// MARK: - Codable\n\nextension UnitInterval: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let doubleValue = try container.decode(Double.self)\n guard let interval = UnitInterval(doubleValue) else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: decoder.codingPath,\n debugDescription: \"Value \\(doubleValue) is not in range 0...1\")\n )\n }\n self = interval\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n try container.encode(value)\n }\n}\n\n// MARK: - ExpressibleByFloatLiteral\n\nextension UnitInterval: ExpressibleByFloatLiteral {\n /// Creates a unit interval from a floating-point literal.\n ///\n /// This initializer allows you to create `UnitInterval` instances using\n /// floating-point literals. The literal value must be in the range [0, 1]\n /// or a runtime error will occur.\n ///\n /// - Parameter value: A floating-point literal between 0.0 and 1.0\n ///\n /// - Warning: This initializer will crash if the literal is outside the valid range.\n /// Use the failable initializer `init(_:)` for runtime validation.\n ///\n /// - Example:\n /// ```swift\n /// let quarter: UnitInterval = 0.25\n /// let half: UnitInterval = 0.5\n /// ```\n public init(floatLiteral value: Double) {\n self.init(value)!\n }\n}\n\n// MARK: - ExpressibleByIntegerLiteral\n\nextension UnitInterval: ExpressibleByIntegerLiteral {\n /// Creates a unit interval from an integer literal.\n ///\n /// This initializer allows you to create `UnitInterval` instances using\n /// integer literals. Only the values 0 and 1 are valid.\n ///\n /// - Parameter value: An integer literal, either 0 or 1\n ///\n /// - Warning: This initializer will crash if the literal is outside the valid range.\n /// Use the failable initializer `init(_:)` for runtime validation.\n ///\n /// - Example:\n /// ```swift\n /// let zero: UnitInterval = 0\n /// let one: UnitInterval = 1\n /// ```\n public init(integerLiteral value: Int) {\n self.init(Double(value))!\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/ID.swift", "import struct Foundation.UUID\n\n/// A unique identifier for a request.\npublic enum ID: Hashable, Sendable {\n /// A string ID.\n case string(String)\n\n /// A number ID.\n case number(Int)\n\n /// Generates a random string ID.\n public static var random: ID {\n return .string(UUID().uuidString)\n }\n}\n\n// MARK: - ExpressibleByStringLiteral\n\nextension ID: ExpressibleByStringLiteral {\n public init(stringLiteral value: String) {\n self = .string(value)\n }\n}\n\n// MARK: - ExpressibleByIntegerLiteral\n\nextension ID: ExpressibleByIntegerLiteral {\n public init(integerLiteral value: Int) {\n self = .number(value)\n }\n}\n\n// MARK: - CustomStringConvertible\n\nextension ID: CustomStringConvertible {\n public var description: String {\n switch self {\n case .string(let str): return str\n case .number(let num): return String(num)\n }\n }\n}\n\n// MARK: - Codable\n\nextension ID: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n if let string = try? container.decode(String.self) {\n self = .string(string)\n } else if let number = try? container.decode(Int.self) {\n self = .number(number)\n } else if container.decodeNil() {\n // Handle unspecified/null IDs as empty string\n self = .string(\"\")\n } else {\n throw DecodingError.dataCorruptedError(\n in: container, debugDescription: \"ID must be string or number\")\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n switch self {\n case .string(let str): try container.encode(str)\n case .number(let num): try container.encode(num)\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Extensions/Data+Extensions.swift", "import Foundation\nimport RegexBuilder\n\nextension Data {\n /// Regex pattern for data URLs\n @inline(__always) private static var dataURLRegex:\n Regex<(Substring, Substring, Substring?, Substring)>\n {\n Regex {\n \"data:\"\n Capture {\n ZeroOrMore(.reluctant) {\n CharacterClass.anyOf(\",;\").inverted\n }\n }\n Optionally {\n \";charset=\"\n Capture {\n OneOrMore(.reluctant) {\n CharacterClass.anyOf(\",;\").inverted\n }\n }\n }\n Optionally { \";base64\" }\n \",\"\n Capture {\n ZeroOrMore { .any }\n }\n }\n }\n\n /// Checks if a given string is a valid data URL.\n ///\n /// - Parameter string: The string to check.\n /// - Returns: `true` if the string is a valid data URL, otherwise `false`.\n /// - SeeAlso: [RFC 2397](https://www.rfc-editor.org/rfc/rfc2397.html)\n public static func isDataURL(string: String) -> Bool {\n return string.wholeMatch(of: dataURLRegex) != nil\n }\n\n /// Parses a data URL string into its MIME type and data components.\n ///\n /// - Parameter string: The data URL string to parse.\n /// - Returns: A tuple containing the MIME type and decoded data, or `nil` if parsing fails.\n /// - SeeAlso: [RFC 2397](https://www.rfc-editor.org/rfc/rfc2397.html)\n public static func parseDataURL(_ string: String) -> (mimeType: String, data: Data)? {\n guard let match = string.wholeMatch(of: dataURLRegex) else {\n return nil\n }\n\n // Extract components using strongly typed captures\n let (_, mediatype, charset, encodedData) = match.output\n\n let isBase64 = string.contains(\";base64,\")\n\n // Process MIME type\n var mimeType = mediatype.isEmpty ? \"text/plain\" : String(mediatype)\n if let charset = charset, !charset.isEmpty, mimeType.starts(with: \"text/\") {\n mimeType += \";charset=\\(charset)\"\n }\n\n // Decode data\n let decodedData: Data\n if isBase64 {\n guard let base64Data = Data(base64Encoded: String(encodedData)) else { return nil }\n decodedData = base64Data\n } else {\n guard\n let percentDecodedData = String(encodedData).removingPercentEncoding?.data(\n using: .utf8)\n else { return nil }\n decodedData = percentDecodedData\n }\n\n return (mimeType: mimeType, data: decodedData)\n }\n\n /// Encodes the data as a data URL string with an optional MIME type.\n ///\n /// - Parameter mimeType: The MIME type of the data. If `nil`, \"text/plain\" will be used.\n /// - Returns: A data URL string representation of the data.\n /// - SeeAlso: [RFC 2397](https://www.rfc-editor.org/rfc/rfc2397.html)\n public func dataURLEncoded(mimeType: String? = nil) -> String {\n let base64Data = self.base64EncodedString()\n return \"data:\\(mimeType ?? \"text/plain\");base64,\\(base64Data)\"\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Lifecycle.swift", "/// The initialization phase MUST be the first interaction between client and server.\n/// During this phase, the client and server:\n/// - Establish protocol version compatibility\n/// - Exchange and negotiate capabilities\n/// - Share implementation details\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle/#initialization\npublic enum Initialize: Method {\n public static let name: String = \"initialize\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let protocolVersion: String\n public let capabilities: Client.Capabilities\n public let clientInfo: Client.Info\n\n public init(\n protocolVersion: String = Version.latest,\n capabilities: Client.Capabilities,\n clientInfo: Client.Info\n ) {\n self.protocolVersion = protocolVersion\n self.capabilities = capabilities\n self.clientInfo = clientInfo\n }\n\n private enum CodingKeys: String, CodingKey {\n case protocolVersion, capabilities, clientInfo\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n protocolVersion =\n try container.decodeIfPresent(String.self, forKey: .protocolVersion)\n ?? Version.latest\n capabilities =\n try container.decodeIfPresent(Client.Capabilities.self, forKey: .capabilities)\n ?? .init()\n clientInfo =\n try container.decodeIfPresent(Client.Info.self, forKey: .clientInfo)\n ?? .init(name: \"unknown\", version: \"0.0.0\")\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let protocolVersion: String\n public let capabilities: Server.Capabilities\n public let serverInfo: Server.Info\n public let instructions: String?\n }\n}\n\n/// After successful initialization, the client MUST send an initialized notification to indicate it is ready to begin normal operations.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle/#initialization\npublic struct InitializedNotification: Notification {\n public static let name: String = \"notifications/initialized\"\n}\n"], ["/swift-sdk/Sources/MCP/Server/Resources.swift", "import Foundation\n\n/// The Model Context Protocol (MCP) provides a standardized way\n/// for servers to expose resources to clients.\n/// Resources allow servers to share data that provides context to language models,\n/// such as files, database schemas, or application-specific information.\n/// Each resource is uniquely identified by a URI.\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/\npublic struct Resource: Hashable, Codable, Sendable {\n /// The resource name\n public var name: String\n /// The resource URI\n public var uri: String\n /// The resource description\n public var description: String?\n /// The resource MIME type\n public var mimeType: String?\n /// The resource metadata\n public var metadata: [String: String]?\n\n public init(\n name: String,\n uri: String,\n description: String? = nil,\n mimeType: String? = nil,\n metadata: [String: String]? = nil\n ) {\n self.name = name\n self.uri = uri\n self.description = description\n self.mimeType = mimeType\n self.metadata = metadata\n }\n\n /// Content of a resource.\n public struct Content: Hashable, Codable, Sendable {\n /// The resource URI\n public let uri: String\n /// The resource MIME type\n public let mimeType: String?\n /// The resource text content\n public let text: String?\n /// The resource binary content\n public let blob: String?\n\n public static func text(_ content: String, uri: String, mimeType: String? = nil) -> Self {\n .init(uri: uri, mimeType: mimeType, text: content)\n }\n\n public static func binary(_ data: Data, uri: String, mimeType: String? = nil) -> Self {\n .init(uri: uri, mimeType: mimeType, blob: data.base64EncodedString())\n }\n\n private init(uri: String, mimeType: String? = nil, text: String? = nil) {\n self.uri = uri\n self.mimeType = mimeType\n self.text = text\n self.blob = nil\n }\n\n private init(uri: String, mimeType: String? = nil, blob: String) {\n self.uri = uri\n self.mimeType = mimeType\n self.text = nil\n self.blob = blob\n }\n }\n\n /// A resource template.\n public struct Template: Hashable, Codable, Sendable {\n /// The URI template pattern\n public var uriTemplate: String\n /// The template name\n public var name: String\n /// The template description\n public var description: String?\n /// The resource MIME type\n public var mimeType: String?\n\n public init(\n uriTemplate: String,\n name: String,\n description: String? = nil,\n mimeType: String? = nil\n ) {\n self.uriTemplate = uriTemplate\n self.name = name\n self.description = description\n self.mimeType = mimeType\n }\n }\n}\n\n// MARK: -\n\n/// To discover available resources, clients send a `resources/list` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#listing-resources\npublic enum ListResources: Method {\n public static let name: String = \"resources/list\"\n\n public struct Parameters: NotRequired, Hashable, Codable, Sendable {\n public let cursor: String?\n\n public init() {\n self.cursor = nil\n }\n \n public init(cursor: String) {\n self.cursor = cursor\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let resources: [Resource]\n public let nextCursor: String?\n\n public init(resources: [Resource], nextCursor: String? = nil) {\n self.resources = resources\n self.nextCursor = nextCursor\n }\n }\n}\n\n/// To retrieve resource contents, clients send a `resources/read` request:\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#reading-resources\npublic enum ReadResource: Method {\n public static let name: String = \"resources/read\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let uri: String\n\n public init(uri: String) {\n self.uri = uri\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let contents: [Resource.Content]\n\n public init(contents: [Resource.Content]) {\n self.contents = contents\n }\n }\n}\n\n/// To discover available resource templates, clients send a `resources/templates/list` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#resource-templates\npublic enum ListResourceTemplates: Method {\n public static let name: String = \"resources/templates/list\"\n\n public struct Parameters: NotRequired, Hashable, Codable, Sendable {\n public let cursor: String?\n\n public init() {\n self.cursor = nil\n }\n \n public init(cursor: String) {\n self.cursor = cursor\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let templates: [Resource.Template]\n public let nextCursor: String?\n\n public init(templates: [Resource.Template], nextCursor: String? = nil) {\n self.templates = templates\n self.nextCursor = nextCursor\n }\n\n private enum CodingKeys: String, CodingKey {\n case templates = \"resourceTemplates\"\n case nextCursor\n }\n }\n}\n\n/// When the list of available resources changes, servers that declared the listChanged capability SHOULD send a notification.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#list-changed-notification\npublic struct ResourceListChangedNotification: Notification {\n public static let name: String = \"notifications/resources/list_changed\"\n\n public typealias Parameters = Empty\n}\n\n/// Clients can subscribe to specific resources and receive notifications when they change.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#subscriptions\npublic enum ResourceSubscribe: Method {\n public static let name: String = \"resources/subscribe\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let uri: String\n }\n\n public typealias Result = Empty\n}\n\n/// When a resource changes, servers that declared the updated capability SHOULD send a notification to subscribed clients.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#subscriptions\npublic struct ResourceUpdatedNotification: Notification {\n public static let name: String = \"notifications/resources/updated\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let uri: String\n\n public init(uri: String) {\n self.uri = uri\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Versioning.swift", "import Foundation\n\n/// The Model Context Protocol uses string-based version identifiers\n/// following the format YYYY-MM-DD, to indicate\n/// the last date backwards incompatible changes were made.\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2025-03-26/\npublic enum Version {\n /// All protocol versions supported by this implementation, ordered from newest to oldest.\n static let supported: Set = [\n \"2025-03-26\",\n \"2024-11-05\",\n ]\n\n /// The latest protocol version supported by this implementation.\n public static let latest = supported.max()!\n\n /// Negotiates the protocol version based on the client's request and server's capabilities.\n /// - Parameter clientRequestedVersion: The protocol version requested by the client.\n /// - Returns: The negotiated protocol version. If the client's requested version is supported,\n /// that version is returned. Otherwise, the server's latest supported version is returned.\n static func negotiate(clientRequestedVersion: String) -> String {\n if supported.contains(clientRequestedVersion) {\n return clientRequestedVersion\n }\n return latest\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Utilities/Ping.swift", "/// The Model Context Protocol includes an optional ping mechanism that allows either party to verify that their counterpart is still responsive and the connection is alive.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/utilities/ping\npublic enum Ping: Method {\n public static let name: String = \"ping\"\n}\n"], ["/swift-sdk/Sources/MCP/Base/Transport.swift", "import Logging\n\nimport struct Foundation.Data\n\n/// Protocol defining the transport layer for MCP communication\npublic protocol Transport: Actor {\n var logger: Logger { get }\n\n /// Establishes connection with the transport\n func connect() async throws\n\n /// Disconnects from the transport\n func disconnect() async\n\n /// Sends data\n func send(_ data: Data) async throws\n\n /// Receives data in an async sequence\n func receive() -> AsyncThrowingStream\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 03:25:14", "created_task_model": "DeepSeek-R1", "function_skeleton": "public func encode ( to encoder: Encoder ) throws { }", "code_description": "This code segment functions to: Serialize error information into a structured format by encoding standard error properties and conditionally including supplementary details based on specific error types when available."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```swift\n[TASK_BEGIN]\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(code, forKey: .code)\n \n var message: String\n var data: [String: Value]?\n \n switch self {\n case .parseError(let detail):\n message = \"Parse error: Invalid JSON\"\n data = detail.map { [\"detail\": .string($0)] }\n \n case .invalidRequest(let detail):\n message = \"Invalid Request\"\n data = detail.map { [\"detail\": .string($0)] }\n \n case .methodNotFound(let detail):\n message = \"Method not found\"\n data = detail.map { [\"detail\": .string($0)] }\n \n case .invalidParams(let detail):\n message = \"Invalid params\"\n data = detail.map { [\"detail\": .string($0)] }\n \n case .internalError(let detail):\n message = \"Internal error\"\n data = detail.map { [\"detail\": .string($0)] }\n \n case .serverError(_, let message):\n message = message\n data = nil\n \n case .connectionClosed:\n message = \"Connection closed\"\n data = nil\n \n case .transportError(let error):\n message = \"Transport error: \\(error.localizedDescription)\"\n data = [\"error\": .string(error.localizedDescription)]\n }\n \n try container.encode(message, forKey: .message)\n try container.encodeIfPresent(data, forKey: .data)\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 03-26-04"}, "editdistance_info": {"edit_distance": 35.9736, "calculate_time": "2025-08-21 03:26:04", "true_code_clean": "public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(code, forKey: .code)\n try container.encode(errorDescription ?? \"Unknown error\", forKey: .message)\n switch self {\n case .parseError(let detail),\n .invalidRequest(let detail),\n .methodNotFound(let detail),\n .invalidParams(let detail),\n .internalError(let detail):\n if let detail = detail {\n try container.encode([\"detail\": detail], forKey: .data)\n }\n case .serverError(_, _):\n break\n case .connectionClosed:\n break\n case .transportError(let error):\n try container.encode(\n [\"error\": error.localizedDescription],\n forKey: .data\n )\n }\n }", "predict_code_clean": "public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(code, forKey: .code)\n var message: String\n var data: [String: Value]?\n switch self {\n case .parseError(let detail):\n message = \"Parse error: Invalid JSON\"\n data = detail.map { [\"detail\": .string($0)] }\n case .invalidRequest(let detail):\n message = \"Invalid Request\"\n data = detail.map { [\"detail\": .string($0)] }\n case .methodNotFound(let detail):\n message = \"Method not found\"\n data = detail.map { [\"detail\": .string($0)] }\n case .invalidParams(let detail):\n message = \"Invalid params\"\n data = detail.map { [\"detail\": .string($0)] }\n case .internalError(let detail):\n message = \"Internal error\"\n data = detail.map { [\"detail\": .string($0)] }\n case .serverError(_, let message):\n message = message\n data = nil\n case .connectionClosed:\n message = \"Connection closed\"\n data = nil\n case .transportError(let error):\n message = \"Transport error: \\(error.localizedDescription)\"\n data = [\"error\": .string(error.localizedDescription)]\n }\n try container.encode(message, forKey: .message)\n try container.encodeIfPresent(data, forKey: .data)\n }"}} +{"repo_name": "swift-sdk", "file_name": "/swift-sdk/Sources/MCP/Base/Transports/StdioTransport.swift", "inference_info": {"prefix_code": "import Logging\n\nimport struct Foundation.Data\n\n#if canImport(System)\n import System\n#else\n @preconcurrency import SystemPackage\n#endif\n\n// Import for specific low-level operations not yet in Swift System\n#if canImport(Darwin)\n import Darwin.POSIX\n#elseif canImport(Glibc)\n import Glibc\n#endif\n\n#if canImport(Darwin) || canImport(Glibc)\n /// An implementation of the MCP stdio transport protocol.\n ///\n /// This transport implements the [stdio transport](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#stdio)\n /// specification from the Model Context Protocol.\n ///\n /// The stdio transport works by:\n /// - Reading JSON-RPC messages from standard input\n /// - Writing JSON-RPC messages to standard output\n /// - Using newline characters as message delimiters\n /// - Supporting non-blocking I/O operations\n ///\n /// This transport is the recommended option for most MCP applications due to its\n /// simplicity and broad platform support.\n ///\n /// - Important: This transport is available on Apple platforms and Linux distributions with glibc\n /// (Ubuntu, Debian, Fedora, CentOS, RHEL).\n ///\n /// ## Example Usage\n ///\n /// ```swift\n /// import MCP\n ///\n /// // Initialize the client\n /// let client = Client(name: \"MyApp\", version: \"1.0.0\")\n ///\n /// // Create a transport and connect\n /// let transport = StdioTransport()\n /// try await client.connect(transport: transport)\n /// ```\n public actor StdioTransport: Transport {\n private let input: FileDescriptor\n private let output: FileDescriptor\n /// Logger instance for transport-related events\n public nonisolated let logger: Logger\n\n private var isConnected = false\n private let messageStream: AsyncThrowingStream\n private let messageContinuation: AsyncThrowingStream.Continuation\n\n /// Creates a new stdio transport with the specified file descriptors\n ///\n /// - Parameters:\n /// - input: File descriptor for reading (defaults to standard input)\n /// - output: File descriptor for writing (defaults to standard output)\n /// - logger: Optional logger instance for transport events\n public init(\n input: FileDescriptor = FileDescriptor.standardInput,\n output: FileDescriptor = FileDescriptor.standardOutput,\n logger: Logger? = nil\n ) {\n self.input = input\n self.output = output\n self.logger =\n logger\n ?? Logger(\n label: \"mcp.transport.stdio\",\n factory: { _ in SwiftLogNoOpLogHandler() })\n\n // Create message stream\n var continuation: AsyncThrowingStream.Continuation!\n self.messageStream = AsyncThrowingStream { continuation = $0 }\n self.messageContinuation = continuation\n }\n\n /// Establishes connection with the transport\n ///\n /// This method configures the file descriptors for non-blocking I/O\n /// and starts the background message reading loop.\n ///\n /// - Throws: Error if the file descriptors cannot be configured\n public func connect() async throws {\n guard !isConnected else { return }\n\n // Set non-blocking mode\n try setNonBlocking(fileDescriptor: input)\n try setNonBlocking(fileDescriptor: output)\n\n isConnected = true\n logger.info(\"Transport connected successfully\")\n\n // Start reading loop in background\n Task {\n await readLoop()\n }\n }\n\n /// Configures a file descriptor for non-blocking I/O\n ///\n /// - Parameter fileDescriptor: The file descriptor to configure\n /// - Throws: Error if the operation fails\n private func setNonBlocking(fileDescriptor: FileDescriptor) throws {\n #if canImport(Darwin) || canImport(Glibc)\n // Get current flags\n let flags = fcntl(fileDescriptor.rawValue, F_GETFL)\n guard flags >= 0 else {\n throw MCPError.transportError(Errno(rawValue: CInt(errno)))\n }\n\n // Set non-blocking flag\n let result = fcntl(fileDescriptor.rawValue, F_SETFL, flags | O_NONBLOCK)\n guard result >= 0 else {\n throw MCPError.transportError(Errno(rawValue: CInt(errno)))\n }\n #else\n // For platforms where non-blocking operations aren't supported\n throw MCPError.internalError(\n \"Setting non-blocking mode not supported on this platform\")\n #endif\n }\n\n /// Continuous loop that reads and processes incoming messages\n ///\n /// This method runs in the background while the transport is connected,\n /// parsing complete messages delimited by newlines and yielding them\n /// to the message stream.\n ", "suffix_code": "\n\n /// Disconnects from the transport\n ///\n /// This stops the message reading loop and releases associated resources.\n public func disconnect() async {\n guard isConnected else { return }\n isConnected = false\n messageContinuation.finish()\n logger.info(\"Transport disconnected\")\n }\n\n /// Sends a message over the transport.\n ///\n /// This method supports sending both individual JSON-RPC messages and JSON-RPC batches.\n /// Batches should be encoded as a JSON array containing multiple request/notification objects\n /// according to the JSON-RPC 2.0 specification.\n ///\n /// - Parameter message: The message data to send (without a trailing newline)\n /// - Throws: Error if the message cannot be sent\n public func send(_ message: Data) async throws {\n guard isConnected else {\n throw MCPError.transportError(Errno(rawValue: ENOTCONN))\n }\n\n // Add newline as delimiter\n var messageWithNewline = message\n messageWithNewline.append(UInt8(ascii: \"\\n\"))\n\n var remaining = messageWithNewline\n while !remaining.isEmpty {\n do {\n let written = try remaining.withUnsafeBytes { buffer in\n try output.write(UnsafeRawBufferPointer(buffer))\n }\n if written > 0 {\n remaining = remaining.dropFirst(written)\n }\n } catch let error where MCPError.isResourceTemporarilyUnavailable(error) {\n try await Task.sleep(for: .milliseconds(10))\n continue\n } catch {\n throw MCPError.transportError(error)\n }\n }\n }\n\n /// Receives messages from the transport.\n ///\n /// Messages may be individual JSON-RPC requests, notifications, responses,\n /// or batches containing multiple requests/notifications encoded as JSON arrays.\n /// Each message is guaranteed to be a complete JSON object or array.\n ///\n /// - Returns: An AsyncThrowingStream of Data objects representing JSON-RPC messages\n public func receive() -> AsyncThrowingStream {\n return messageStream\n }\n }\n#endif\n", "middle_code": "private func readLoop() async {\n let bufferSize = 4096\n var buffer = [UInt8](repeating: 0, count: bufferSize)\n var pendingData = Data()\n while isConnected && !Task.isCancelled {\n do {\n let bytesRead = try buffer.withUnsafeMutableBufferPointer { pointer in\n try input.read(into: UnsafeMutableRawBufferPointer(pointer))\n }\n if bytesRead == 0 {\n logger.notice(\"EOF received\")\n break\n }\n pendingData.append(Data(buffer[.. Void))? { get set }\n\n func start(queue: DispatchQueue)\n func cancel()\n func send(\n content: Data?, contentContext: NWConnection.ContentContext, isComplete: Bool,\n completion: NWConnection.SendCompletion)\n func receive(\n minimumIncompleteLength: Int, maximumLength: Int,\n completion: @escaping @Sendable (\n Data?, NWConnection.ContentContext?, Bool, NWError?\n ) -> Void)\n }\n\n /// Extension to conform NWConnection to internal NetworkConnectionProtocol\n extension NWConnection: NetworkConnectionProtocol {}\n\n /// An implementation of a custom MCP transport using Apple's Network framework.\n ///\n /// This transport allows MCP clients and servers to communicate over TCP/UDP connections\n /// using Apple's Network framework.\n ///\n /// - Important: This transport is available exclusively on Apple platforms\n /// (macOS, iOS, watchOS, tvOS, visionOS) as it depends on the Network framework.\n ///\n /// ## Example Usage\n ///\n /// ```swift\n /// import MCP\n /// import Network\n ///\n /// // Create a TCP connection to a server\n /// let connection = NWConnection(\n /// host: NWEndpoint.Host(\"localhost\"),\n /// port: NWEndpoint.Port(8080)!,\n /// using: .tcp\n /// )\n ///\n /// // Initialize the transport with the connection\n /// let transport = NetworkTransport(connection: connection)\n ///\n /// // For large messages (e.g., images), configure unlimited buffer size\n /// let largeBufferTransport = NetworkTransport(\n /// connection: connection,\n /// bufferConfig: .unlimited\n /// )\n ///\n /// // Use the transport with an MCP client\n /// let client = Client(name: \"MyApp\", version: \"1.0.0\")\n /// try await client.connect(transport: transport)\n /// ```\n public actor NetworkTransport: Transport {\n /// Represents a heartbeat message for connection health monitoring.\n public struct Heartbeat: RawRepresentable, Hashable, Sendable {\n /// Magic bytes used to identify a heartbeat message.\n private static let magicBytes: [UInt8] = [0xF0, 0x9F, 0x92, 0x93]\n\n /// The timestamp of when the heartbeat was created.\n public let timestamp: Date\n\n /// Creates a new heartbeat with the current timestamp.\n public init() {\n self.timestamp = Date()\n }\n\n /// Creates a heartbeat with a specific timestamp.\n ///\n /// - Parameter timestamp: The timestamp for the heartbeat.\n public init(timestamp: Date) {\n self.timestamp = timestamp\n }\n\n // MARK: - RawRepresentable\n\n public typealias RawValue = [UInt8]\n\n /// Creates a heartbeat from its raw representation.\n ///\n /// - Parameter rawValue: The raw bytes of the heartbeat message.\n /// - Returns: A heartbeat if the raw value is valid, nil otherwise.\n public init?(rawValue: [UInt8]) {\n // Check if the data has the correct format (magic bytes + timestamp)\n guard rawValue.count >= 12,\n rawValue.prefix(4).elementsEqual(Self.magicBytes)\n else {\n return nil\n }\n\n // Extract the timestamp\n let timestampData = Data(rawValue[4..<12])\n let timestamp = timestampData.withUnsafeBytes {\n $0.load(as: UInt64.self)\n }\n\n self.timestamp = Date(\n timeIntervalSinceReferenceDate: TimeInterval(timestamp) / 1000.0)\n }\n\n /// Converts the heartbeat to its raw representation.\n public var rawValue: [UInt8] {\n var result = Data(Self.magicBytes)\n\n // Add timestamp (milliseconds since reference date)\n let timestamp = UInt64(self.timestamp.timeIntervalSinceReferenceDate * 1000)\n withUnsafeBytes(of: timestamp) { buffer in\n result.append(contentsOf: buffer)\n }\n\n return Array(result)\n }\n\n /// Converts the heartbeat to Data.\n public var data: Data {\n return Data(self.rawValue)\n }\n\n /// Checks if the given data represents a heartbeat message.\n ///\n /// - Parameter data: The data to check.\n /// - Returns: true if the data is a heartbeat message, false otherwise.\n public static func isHeartbeat(_ data: Data) -> Bool {\n guard data.count >= 4 else {\n return false\n }\n\n return data.prefix(4).elementsEqual(Self.magicBytes)\n }\n\n /// Attempts to parse a heartbeat from the given data.\n ///\n /// - Parameter data: The data to parse.\n /// - Returns: A heartbeat if the data is valid, nil otherwise.\n public static func from(data: Data) -> Heartbeat? {\n guard data.count >= 12 else {\n return nil\n }\n\n return Heartbeat(rawValue: Array(data))\n }\n }\n\n /// Configuration for heartbeat behavior.\n public struct HeartbeatConfiguration: Hashable, Sendable {\n /// Whether heartbeats are enabled.\n public let enabled: Bool\n /// Interval between heartbeats in seconds.\n public let interval: TimeInterval\n\n /// Creates a new heartbeat configuration.\n ///\n /// - Parameters:\n /// - enabled: Whether heartbeats are enabled (default: true)\n /// - interval: Interval in seconds between heartbeats (default: 15.0)\n public init(enabled: Bool = true, interval: TimeInterval = 15.0) {\n self.enabled = enabled\n self.interval = interval\n }\n\n /// Default heartbeat configuration.\n public static let `default` = HeartbeatConfiguration()\n\n /// Configuration with heartbeats disabled.\n public static let disabled = HeartbeatConfiguration(enabled: false)\n }\n\n /// Configuration for connection retry behavior.\n public struct ReconnectionConfiguration: Hashable, Sendable {\n /// Whether the transport should attempt to reconnect on failure.\n public let enabled: Bool\n /// Maximum number of reconnection attempts.\n public let maxAttempts: Int\n /// Multiplier for exponential backoff on reconnect.\n public let backoffMultiplier: Double\n\n /// Creates a new reconnection configuration.\n ///\n /// - Parameters:\n /// - enabled: Whether reconnection should be attempted on failure (default: true)\n /// - maxAttempts: Maximum number of reconnection attempts (default: 5)\n /// - backoffMultiplier: Multiplier for exponential backoff on reconnect (default: 1.5)\n public init(\n enabled: Bool = true,\n maxAttempts: Int = 5,\n backoffMultiplier: Double = 1.5\n ) {\n self.enabled = enabled\n self.maxAttempts = maxAttempts\n self.backoffMultiplier = backoffMultiplier\n }\n\n /// Default reconnection configuration.\n public static let `default` = ReconnectionConfiguration()\n\n /// Configuration with reconnection disabled.\n public static let disabled = ReconnectionConfiguration(enabled: false)\n\n /// Calculates the backoff delay for a given attempt number.\n ///\n /// - Parameter attempt: The current attempt number (1-based)\n /// - Returns: The delay in seconds before the next attempt\n public func backoffDelay(for attempt: Int) -> TimeInterval {\n let baseDelay = 0.5 // 500ms\n return baseDelay * pow(backoffMultiplier, Double(attempt - 1))\n }\n }\n\n /// Configuration for buffer behavior.\n public struct BufferConfiguration: Hashable, Sendable {\n /// Maximum buffer size for receiving data chunks.\n /// Set to nil for unlimited (uses system default).\n public let maxReceiveBufferSize: Int?\n\n /// Creates a new buffer configuration.\n ///\n /// - Parameter maxReceiveBufferSize: Maximum buffer size in bytes (default: 10MB, nil for unlimited)\n public init(maxReceiveBufferSize: Int? = 10 * 1024 * 1024) {\n self.maxReceiveBufferSize = maxReceiveBufferSize\n }\n\n /// Default buffer configuration with 10MB limit.\n public static let `default` = BufferConfiguration()\n\n /// Configuration with no buffer size limit.\n public static let unlimited = BufferConfiguration(maxReceiveBufferSize: nil)\n }\n\n // State tracking\n private var isConnected = false\n private var isStopping = false\n private var reconnectAttempt = 0\n private var heartbeatTask: Task?\n private var lastHeartbeatTime: Date?\n private let messageStream: AsyncThrowingStream\n private let messageContinuation: AsyncThrowingStream.Continuation\n\n // Track connection state for continuations\n private var connectionContinuationResumed = false\n\n // Connection is marked nonisolated(unsafe) to allow access from closures\n private nonisolated(unsafe) var connection: NetworkConnectionProtocol\n\n /// Logger instance for transport-related events\n public nonisolated let logger: Logger\n\n // Configuration\n private let heartbeatConfig: HeartbeatConfiguration\n private let reconnectionConfig: ReconnectionConfiguration\n private let bufferConfig: BufferConfiguration\n\n /// Creates a new NetworkTransport with the specified NWConnection\n ///\n /// - Parameters:\n /// - connection: The NWConnection to use for communication\n /// - logger: Optional logger instance for transport events\n /// - reconnectionConfig: Configuration for reconnection behavior (default: .default)\n /// - heartbeatConfig: Configuration for heartbeat behavior (default: .default)\n /// - bufferConfig: Configuration for buffer behavior (default: .default)\n public init(\n connection: NWConnection,\n logger: Logger? = nil,\n heartbeatConfig: HeartbeatConfiguration = .default,\n reconnectionConfig: ReconnectionConfiguration = .default,\n bufferConfig: BufferConfiguration = .default\n ) {\n self.init(\n connection,\n logger: logger,\n heartbeatConfig: heartbeatConfig,\n reconnectionConfig: reconnectionConfig,\n bufferConfig: bufferConfig\n )\n }\n\n init(\n _ connection: NetworkConnectionProtocol,\n logger: Logger? = nil,\n heartbeatConfig: HeartbeatConfiguration = .default,\n reconnectionConfig: ReconnectionConfiguration = .default,\n bufferConfig: BufferConfiguration = .default\n ) {\n self.connection = connection\n self.logger =\n logger\n ?? Logger(\n label: \"mcp.transport.network\",\n factory: { _ in SwiftLogNoOpLogHandler() }\n )\n self.reconnectionConfig = reconnectionConfig\n self.heartbeatConfig = heartbeatConfig\n self.bufferConfig = bufferConfig\n\n // Create message stream\n var continuation: AsyncThrowingStream.Continuation!\n self.messageStream = AsyncThrowingStream { continuation = $0 }\n self.messageContinuation = continuation\n }\n\n /// Establishes connection with the transport\n ///\n /// This initiates the NWConnection and waits for it to become ready.\n /// Once the connection is established, it starts the message receiving loop.\n ///\n /// - Throws: Error if the connection fails to establish\n public func connect() async throws {\n guard !isConnected else { return }\n\n // Reset state for fresh connection\n isStopping = false\n reconnectAttempt = 0\n\n // Reset continuation state\n connectionContinuationResumed = false\n\n // Wait for connection to be ready\n try await withCheckedThrowingContinuation {\n [weak self] (continuation: CheckedContinuation) in\n guard let self = self else {\n continuation.resume(throwing: MCPError.internalError(\"Transport deallocated\"))\n return\n }\n\n connection.stateUpdateHandler = { [weak self] state in\n guard let self = self else { return }\n\n Task { @MainActor in\n switch state {\n case .ready:\n await self.handleConnectionReady(continuation: continuation)\n case .failed(let error):\n await self.handleConnectionFailed(\n error: error, continuation: continuation)\n case .cancelled:\n await self.handleConnectionCancelled(continuation: continuation)\n case .waiting(let error):\n self.logger.debug(\"Connection waiting: \\(error)\")\n case .preparing:\n self.logger.debug(\"Connection preparing...\")\n case .setup:\n self.logger.debug(\"Connection setup...\")\n @unknown default:\n self.logger.warning(\"Unknown connection state\")\n }\n }\n }\n\n connection.start(queue: .main)\n }\n }\n\n /// Handles when the connection reaches the ready state\n ///\n /// - Parameter continuation: The continuation to resume when connection is ready\n private func handleConnectionReady(continuation: CheckedContinuation)\n async\n {\n if !connectionContinuationResumed {\n connectionContinuationResumed = true\n isConnected = true\n\n // Reset reconnect attempt counter on successful connection\n reconnectAttempt = 0\n logger.info(\"Network transport connected successfully\")\n continuation.resume()\n\n // Start the receive loop after connection is established\n Task { await self.receiveLoop() }\n\n // Start heartbeat task if enabled\n if heartbeatConfig.enabled {\n startHeartbeat()\n }\n }\n }\n\n /// Starts a task to periodically send heartbeats to check connection health\n private func startHeartbeat() {\n // Cancel any existing heartbeat task\n heartbeatTask?.cancel()\n\n // Start a new heartbeat task\n heartbeatTask = Task { [weak self] in\n guard let self = self else { return }\n\n // Initial delay before starting heartbeats\n try? await Task.sleep(for: .seconds(1))\n\n while !Task.isCancelled {\n do {\n // Check actor-isolated properties first\n let isStopping = await self.isStopping\n let isConnected = await self.isConnected\n\n guard !isStopping && isConnected else { break }\n\n try await self.sendHeartbeat()\n try await Task.sleep(for: .seconds(self.heartbeatConfig.interval))\n } catch {\n // If heartbeat fails, log and retry after a shorter interval\n self.logger.warning(\"Heartbeat failed: \\(error)\")\n try? await Task.sleep(for: .seconds(2))\n }\n }\n }\n }\n\n /// Sends a heartbeat message to verify connection health\n private func sendHeartbeat() async throws {\n guard isConnected && !isStopping else { return }\n\n // Try to send the heartbeat (without the newline delimiter used for normal messages)\n try await withCheckedThrowingContinuation {\n [weak self] (continuation: CheckedContinuation) in\n guard let self = self else {\n continuation.resume(throwing: MCPError.internalError(\"Transport deallocated\"))\n return\n }\n\n connection.send(\n content: Heartbeat().data,\n contentContext: .defaultMessage,\n isComplete: true,\n completion: .contentProcessed { [weak self] error in\n if let error = error {\n continuation.resume(throwing: error)\n } else {\n Task { [weak self] in\n await self?.setLastHeartbeatTime(Date())\n }\n continuation.resume()\n }\n })\n }\n\n logger.trace(\"Heartbeat sent\")\n }\n\n /// Handles connection failure\n ///\n /// - Parameters:\n /// - error: The error that caused the connection to fail\n /// - continuation: The continuation to resume with the error\n private func handleConnectionFailed(\n error: Swift.Error, continuation: CheckedContinuation\n ) async {\n if !connectionContinuationResumed {\n connectionContinuationResumed = true\n logger.error(\"Connection failed: \\(error)\")\n\n await handleReconnection(\n error: error,\n continuation: continuation,\n context: \"failure\"\n )\n }\n }\n\n /// Handles connection cancellation\n ///\n /// - Parameter continuation: The continuation to resume with cancellation error\n private func handleConnectionCancelled(continuation: CheckedContinuation)\n async\n {\n if !connectionContinuationResumed {\n connectionContinuationResumed = true\n logger.warning(\"Connection cancelled\")\n\n await handleReconnection(\n error: MCPError.internalError(\"Connection cancelled\"),\n continuation: continuation,\n context: \"cancellation\"\n )\n }\n }\n\n /// Common reconnection handling logic\n ///\n /// - Parameters:\n /// - error: The error that triggered the reconnection\n /// - continuation: The continuation to resume with the error\n /// - context: The context of the reconnection (for logging)\n private func handleReconnection(\n error: Swift.Error,\n continuation: CheckedContinuation,\n context: String\n ) async {\n if !isStopping,\n reconnectionConfig.enabled,\n reconnectAttempt < reconnectionConfig.maxAttempts\n {\n // Try to reconnect with exponential backoff\n reconnectAttempt += 1\n logger.info(\n \"Attempting reconnection after \\(context) (\\(reconnectAttempt)/\\(reconnectionConfig.maxAttempts))...\"\n )\n\n // Calculate backoff delay\n let delay = reconnectionConfig.backoffDelay(for: reconnectAttempt)\n\n // Schedule reconnection attempt after delay\n Task {\n try? await Task.sleep(for: .seconds(delay))\n if !isStopping {\n // Cancel the current connection before attempting to reconnect.\n self.connection.cancel()\n // Resume original continuation with error; outer logic or a new call to connect() will handle retry.\n continuation.resume(throwing: error)\n } else {\n continuation.resume(throwing: error) // Stopping, so fail.\n }\n }\n } else {\n // Not configured to reconnect, exceeded max attempts, or stopping\n self.connection.cancel() // Ensure connection is cancelled\n continuation.resume(throwing: error)\n }\n }\n\n /// Disconnects from the transport\n ///\n /// This cancels the NWConnection, finalizes the message stream,\n /// and releases associated resources.\n public func disconnect() async {\n guard isConnected else { return }\n\n // Mark as stopping to prevent reconnection attempts during disconnect\n isStopping = true\n isConnected = false\n\n // Cancel heartbeat task if it exists\n heartbeatTask?.cancel()\n heartbeatTask = nil\n\n connection.cancel()\n messageContinuation.finish()\n logger.info(\"Network transport disconnected\")\n }\n\n /// Sends data through the network connection\n ///\n /// This sends a JSON-RPC message through the NWConnection, adding a newline\n /// delimiter to mark the end of the message.\n ///\n /// - Parameter message: The JSON-RPC message to send\n /// - Throws: MCPError for transport failures or connection issues\n public func send(_ message: Data) async throws {\n guard isConnected else {\n throw MCPError.internalError(\"Transport not connected\")\n }\n\n // Add newline as delimiter\n var messageWithNewline = message\n messageWithNewline.append(UInt8(ascii: \"\\n\"))\n\n // Use a local actor-isolated variable to track continuation state\n var sendContinuationResumed = false\n\n try await withCheckedThrowingContinuation {\n [weak self] (continuation: CheckedContinuation) in\n guard let self = self else {\n continuation.resume(throwing: MCPError.internalError(\"Transport deallocated\"))\n return\n }\n\n connection.send(\n content: messageWithNewline,\n contentContext: .defaultMessage,\n isComplete: true,\n completion: .contentProcessed { [weak self] error in\n guard let self = self else { return }\n\n Task { @MainActor in\n if !sendContinuationResumed {\n sendContinuationResumed = true\n if let error = error {\n self.logger.error(\"Send error: \\(error)\")\n\n // Check if we should attempt to reconnect on send failure\n let isStopping = await self.isStopping // Await actor-isolated property\n if !isStopping && self.reconnectionConfig.enabled {\n let isConnected = await self.isConnected\n if isConnected {\n if error.isConnectionLost {\n self.logger.warning(\n \"Connection appears broken, will attempt to reconnect...\"\n )\n\n // Schedule connection restart\n Task { [weak self] in // Operate on self's executor\n guard let self = self else { return }\n\n await self.setIsConnected(false)\n\n try? await Task.sleep(for: .milliseconds(500))\n\n let currentIsStopping = await self.isStopping\n if !currentIsStopping {\n // Cancel the connection, then attempt to reconnect fully.\n self.connection.cancel()\n try? await self.connect()\n }\n }\n }\n }\n }\n\n continuation.resume(\n throwing: MCPError.internalError(\"Send error: \\(error)\"))\n } else {\n continuation.resume()\n }\n }\n }\n })\n }\n }\n\n /// Receives data in an async sequence\n ///\n /// This returns an AsyncThrowingStream that emits Data objects representing\n /// each JSON-RPC message received from the network connection.\n ///\n /// - Returns: An AsyncThrowingStream of Data objects\n public func receive() -> AsyncThrowingStream {\n return messageStream\n }\n\n /// Continuous loop to receive and process incoming messages\n ///\n /// This method runs continuously while the connection is active,\n /// receiving data and yielding complete messages to the message stream.\n /// Messages are delimited by newline characters.\n private func receiveLoop() async {\n var buffer = Data()\n var consecutiveEmptyReads = 0\n let maxConsecutiveEmptyReads = 5\n\n while isConnected && !Task.isCancelled && !isStopping {\n do {\n let newData = try await receiveData()\n\n // Check for EOF or empty data\n if newData.isEmpty {\n consecutiveEmptyReads += 1\n\n if consecutiveEmptyReads >= maxConsecutiveEmptyReads {\n logger.warning(\n \"Multiple consecutive empty reads (\\(consecutiveEmptyReads)), possible connection issue\"\n )\n\n // Check connection state\n if connection.state != .ready {\n logger.info(\"Connection no longer ready, exiting receive loop\")\n break\n }\n }\n\n // Brief pause before retry\n try await Task.sleep(for: .milliseconds(100))\n continue\n }\n\n // Check if this is a heartbeat message\n if Heartbeat.isHeartbeat(newData) {\n logger.trace(\"Received heartbeat from peer\")\n\n // Extract timestamp if available\n if let heartbeat = Heartbeat.from(data: newData) {\n logger.trace(\"Heartbeat timestamp: \\(heartbeat.timestamp)\")\n }\n\n // Reset the counter since we got valid data\n consecutiveEmptyReads = 0\n continue // Skip regular message processing for heartbeats\n }\n\n // Reset counter on successful data read\n consecutiveEmptyReads = 0\n buffer.append(newData)\n\n // Process complete messages\n while let newlineIndex = buffer.firstIndex(of: UInt8(ascii: \"\\n\")) {\n let messageData = buffer[.. Data {\n var receiveContinuationResumed = false\n\n return try await withCheckedThrowingContinuation {\n [weak self] (continuation: CheckedContinuation) in\n guard let self = self else {\n continuation.resume(throwing: MCPError.internalError(\"Transport deallocated\"))\n return\n }\n\n let maxLength = bufferConfig.maxReceiveBufferSize ?? Int.max\n connection.receive(minimumIncompleteLength: 1, maximumLength: maxLength) {\n content, _, isComplete, error in\n Task { @MainActor in\n if !receiveContinuationResumed {\n receiveContinuationResumed = true\n if let error = error {\n continuation.resume(throwing: MCPError.transportError(error))\n } else if let content = content {\n continuation.resume(returning: content)\n } else if isComplete {\n self.logger.trace(\"Connection completed by peer\")\n continuation.resume(throwing: MCPError.connectionClosed)\n } else {\n // EOF: Resume with empty data instead of throwing an error\n continuation.resume(returning: Data())\n }\n }\n }\n }\n }\n }\n\n private func setLastHeartbeatTime(_ time: Date) {\n self.lastHeartbeatTime = time\n }\n\n private func setIsConnected(_ connected: Bool) {\n self.isConnected = connected\n }\n }\n\n extension NWError {\n /// Whether this error indicates a connection has been lost or reset.\n fileprivate var isConnectionLost: Bool {\n let nsError = self as NSError\n return nsError.code == 57 // Socket is not connected (EHOSTUNREACH or ENOTCONN)\n || nsError.code == 54 // Connection reset by peer (ECONNRESET)\n }\n }\n#endif\n"], ["/swift-sdk/Sources/MCP/Base/Transports/HTTPClientTransport.swift", "import Foundation\nimport Logging\n\n#if !os(Linux)\n import EventSource\n#endif\n\n#if canImport(FoundationNetworking)\n import FoundationNetworking\n#endif\n\n/// An implementation of the MCP Streamable HTTP transport protocol for clients.\n///\n/// This transport implements the [Streamable HTTP transport](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http)\n/// specification from the Model Context Protocol.\n///\n/// It supports:\n/// - Sending JSON-RPC messages via HTTP POST requests\n/// - Receiving responses via both direct JSON responses and SSE streams\n/// - Session management using the `Mcp-Session-Id` header\n/// - Automatic reconnection for dropped SSE streams\n/// - Platform-specific optimizations for different operating systems\n///\n/// The transport supports two modes:\n/// - Regular HTTP (`streaming=false`): Simple request/response pattern\n/// - Streaming HTTP with SSE (`streaming=true`): Enables server-to-client push messages\n///\n/// - Important: Server-Sent Events (SSE) functionality is not supported on Linux platforms.\n///\n/// ## Example Usage\n///\n/// ```swift\n/// import MCP\n///\n/// // Create a streaming HTTP transport\n/// let transport = HTTPClientTransport(\n/// endpoint: URL(string: \"http://localhost:8080\")!,\n/// )\n///\n/// // Initialize the client with streaming transport\n/// let client = Client(name: \"MyApp\", version: \"1.0.0\")\n/// try await client.connect(transport: transport)\n///\n/// // The transport will automatically handle SSE events\n/// // and deliver them through the client's notification handlers\n/// ```\npublic actor HTTPClientTransport: Transport {\n /// The server endpoint URL to connect to\n public let endpoint: URL\n private let session: URLSession\n\n /// The session ID assigned by the server, used for maintaining state across requests\n public private(set) var sessionID: String?\n private let streaming: Bool\n private var streamingTask: Task?\n\n /// Logger instance for transport-related events\n public nonisolated let logger: Logger\n\n /// Maximum time to wait for a session ID before proceeding with SSE connection\n public let sseInitializationTimeout: TimeInterval\n\n private var isConnected = false\n private let messageStream: AsyncThrowingStream\n private let messageContinuation: AsyncThrowingStream.Continuation\n\n private var initialSessionIDSignalTask: Task?\n private var initialSessionIDContinuation: CheckedContinuation?\n\n /// Creates a new HTTP transport client with the specified endpoint\n ///\n /// - Parameters:\n /// - endpoint: The server URL to connect to\n /// - configuration: URLSession configuration to use for HTTP requests\n /// - streaming: Whether to enable SSE streaming mode (default: true)\n /// - sseInitializationTimeout: Maximum time to wait for session ID before proceeding with SSE (default: 10 seconds)\n /// - logger: Optional logger instance for transport events\n public init(\n endpoint: URL,\n configuration: URLSessionConfiguration = .default,\n streaming: Bool = true,\n sseInitializationTimeout: TimeInterval = 10,\n logger: Logger? = nil\n ) {\n self.init(\n endpoint: endpoint,\n session: URLSession(configuration: configuration),\n streaming: streaming,\n sseInitializationTimeout: sseInitializationTimeout,\n logger: logger\n )\n }\n\n internal init(\n endpoint: URL,\n session: URLSession,\n streaming: Bool = false,\n sseInitializationTimeout: TimeInterval = 10,\n logger: Logger? = nil\n ) {\n self.endpoint = endpoint\n self.session = session\n self.streaming = streaming\n self.sseInitializationTimeout = sseInitializationTimeout\n\n // Create message stream\n var continuation: AsyncThrowingStream.Continuation!\n self.messageStream = AsyncThrowingStream { continuation = $0 }\n self.messageContinuation = continuation\n\n self.logger =\n logger\n ?? Logger(\n label: \"mcp.transport.http.client\",\n factory: { _ in SwiftLogNoOpLogHandler() }\n )\n }\n\n // Setup the initial session ID signal\n private func setupInitialSessionIDSignal() {\n self.initialSessionIDSignalTask = Task {\n await withCheckedContinuation { continuation in\n self.initialSessionIDContinuation = continuation\n // This task will suspend here until continuation.resume() is called\n }\n }\n }\n\n // Trigger the initial session ID signal when a session ID is established\n private func triggerInitialSessionIDSignal() {\n if let continuation = self.initialSessionIDContinuation {\n continuation.resume()\n self.initialSessionIDContinuation = nil // Consume the continuation\n logger.trace(\"Initial session ID signal triggered for SSE task.\")\n }\n }\n\n /// Establishes connection with the transport\n ///\n /// This prepares the transport for communication and sets up SSE streaming\n /// if streaming mode is enabled. The actual HTTP connection happens with the\n /// first message sent.\n public func connect() async throws {\n guard !isConnected else { return }\n isConnected = true\n\n // Setup initial session ID signal\n setupInitialSessionIDSignal()\n\n if streaming {\n // Start listening to server events\n streamingTask = Task { await startListeningForServerEvents() }\n }\n\n logger.info(\"HTTP transport connected\")\n }\n\n /// Disconnects from the transport\n ///\n /// This terminates any active connections, cancels the streaming task,\n /// and releases any resources being used by the transport.\n public func disconnect() async {\n guard isConnected else { return }\n isConnected = false\n\n // Cancel streaming task if active\n streamingTask?.cancel()\n streamingTask = nil\n\n // Cancel any in-progress requests\n session.invalidateAndCancel()\n\n // Clean up message stream\n messageContinuation.finish()\n\n // Cancel the initial session ID signal task if active\n initialSessionIDSignalTask?.cancel()\n initialSessionIDSignalTask = nil\n // Resume the continuation if it's still pending to avoid leaks\n initialSessionIDContinuation?.resume()\n initialSessionIDContinuation = nil\n\n logger.info(\"HTTP clienttransport disconnected\")\n }\n\n /// Sends data through an HTTP POST request\n ///\n /// This sends a JSON-RPC message to the server via HTTP POST and processes\n /// the response according to the MCP Streamable HTTP specification. It handles:\n ///\n /// - Adding appropriate Accept headers for both JSON and SSE\n /// - Including the session ID in requests if one has been established\n /// - Processing different response types (JSON vs SSE)\n /// - Handling HTTP error codes according to the specification\n ///\n /// - Parameter data: The JSON-RPC message to send\n /// - Throws: MCPError for transport failures or server errors\n public func send(_ data: Data) async throws {\n guard isConnected else {\n throw MCPError.internalError(\"Transport not connected\")\n }\n\n var request = URLRequest(url: endpoint)\n request.httpMethod = \"POST\"\n request.addValue(\"application/json, text/event-stream\", forHTTPHeaderField: \"Accept\")\n request.addValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\n request.httpBody = data\n\n // Add session ID if available\n if let sessionID = sessionID {\n request.addValue(sessionID, forHTTPHeaderField: \"Mcp-Session-Id\")\n }\n\n #if os(Linux)\n // Linux implementation using data(for:) instead of bytes(for:)\n let (responseData, response) = try await session.data(for: request)\n try await processResponse(response: response, data: responseData)\n #else\n // macOS and other platforms with bytes(for:) support\n let (responseStream, response) = try await session.bytes(for: request)\n try await processResponse(response: response, stream: responseStream)\n #endif\n }\n\n #if os(Linux)\n // Process response with data payload (Linux)\n private func processResponse(response: URLResponse, data: Data) async throws {\n guard let httpResponse = response as? HTTPURLResponse else {\n throw MCPError.internalError(\"Invalid HTTP response\")\n }\n\n // Process the response based on content type and status code\n let contentType = httpResponse.value(forHTTPHeaderField: \"Content-Type\") ?? \"\"\n\n // Extract session ID if present\n if let newSessionID = httpResponse.value(forHTTPHeaderField: \"Mcp-Session-Id\") {\n let wasSessionIDNil = (self.sessionID == nil)\n self.sessionID = newSessionID\n if wasSessionIDNil {\n // Trigger signal on first session ID\n triggerInitialSessionIDSignal()\n }\n logger.debug(\"Session ID received\", metadata: [\"sessionID\": \"\\(newSessionID)\"])\n }\n\n try processHTTPResponse(httpResponse, contentType: contentType)\n guard case 200..<300 = httpResponse.statusCode else { return }\n\n // For JSON responses, yield the data\n if contentType.contains(\"text/event-stream\") {\n logger.warning(\"SSE responses aren't fully supported on Linux\")\n messageContinuation.yield(data)\n } else if contentType.contains(\"application/json\") {\n logger.trace(\"Received JSON response\", metadata: [\"size\": \"\\(data.count)\"])\n messageContinuation.yield(data)\n } else {\n logger.warning(\"Unexpected content type: \\(contentType)\")\n }\n }\n #else\n // Process response with byte stream (macOS, iOS, etc.)\n private func processResponse(response: URLResponse, stream: URLSession.AsyncBytes)\n async throws\n {\n guard let httpResponse = response as? HTTPURLResponse else {\n throw MCPError.internalError(\"Invalid HTTP response\")\n }\n\n // Process the response based on content type and status code\n let contentType = httpResponse.value(forHTTPHeaderField: \"Content-Type\") ?? \"\"\n\n // Extract session ID if present\n if let newSessionID = httpResponse.value(forHTTPHeaderField: \"Mcp-Session-Id\") {\n let wasSessionIDNil = (self.sessionID == nil)\n self.sessionID = newSessionID\n if wasSessionIDNil {\n // Trigger signal on first session ID\n triggerInitialSessionIDSignal()\n }\n logger.debug(\"Session ID received\", metadata: [\"sessionID\": \"\\(newSessionID)\"])\n }\n\n try processHTTPResponse(httpResponse, contentType: contentType)\n guard case 200..<300 = httpResponse.statusCode else { return }\n\n if contentType.contains(\"text/event-stream\") {\n // For SSE, processing happens via the stream\n logger.trace(\"Received SSE response, processing in streaming task\")\n try await self.processSSE(stream)\n } else if contentType.contains(\"application/json\") {\n // For JSON responses, collect and deliver the data\n var buffer = Data()\n for try await byte in stream {\n buffer.append(byte)\n }\n logger.trace(\"Received JSON response\", metadata: [\"size\": \"\\(buffer.count)\"])\n messageContinuation.yield(buffer)\n } else {\n logger.warning(\"Unexpected content type: \\(contentType)\")\n }\n }\n #endif\n\n // Common HTTP response handling for all platforms\n private func processHTTPResponse(_ response: HTTPURLResponse, contentType: String) throws {\n // Handle status codes according to HTTP semantics\n switch response.statusCode {\n case 200..<300:\n // Success range - these are handled by the platform-specific code\n return\n\n case 400:\n throw MCPError.internalError(\"Bad request\")\n\n case 401:\n throw MCPError.internalError(\"Authentication required\")\n\n case 403:\n throw MCPError.internalError(\"Access forbidden\")\n\n case 404:\n // If we get a 404 with a session ID, it means our session is invalid\n if sessionID != nil {\n logger.warning(\"Session has expired\")\n sessionID = nil\n throw MCPError.internalError(\"Session expired\")\n }\n throw MCPError.internalError(\"Endpoint not found\")\n\n case 405:\n // If we get a 405, it means the server does not support the requested method\n // If streaming was requested, we should cancel the streaming task\n if streaming {\n self.streamingTask?.cancel()\n throw MCPError.internalError(\"Server does not support streaming\")\n }\n throw MCPError.internalError(\"Method not allowed\")\n\n case 408:\n throw MCPError.internalError(\"Request timeout\")\n\n case 429:\n throw MCPError.internalError(\"Too many requests\")\n\n case 500..<600:\n // Server error range\n throw MCPError.internalError(\"Server error: \\(response.statusCode)\")\n\n default:\n throw MCPError.internalError(\n \"Unexpected HTTP response: \\(response.statusCode) (\\(contentType))\")\n }\n }\n\n /// Receives data in an async sequence\n ///\n /// This returns an AsyncThrowingStream that emits Data objects representing\n /// each JSON-RPC message received from the server. This includes:\n ///\n /// - Direct responses to client requests\n /// - Server-initiated messages delivered via SSE streams\n ///\n /// - Returns: An AsyncThrowingStream of Data objects\n public func receive() -> AsyncThrowingStream {\n return messageStream\n }\n\n // MARK: - SSE\n\n /// Starts listening for server events using SSE\n ///\n /// This establishes a long-lived HTTP connection using Server-Sent Events (SSE)\n /// to enable server-to-client push messaging. It handles:\n ///\n /// - Waiting for session ID if needed\n /// - Opening the SSE connection\n /// - Automatic reconnection on connection drops\n /// - Processing received events\n private func startListeningForServerEvents() async {\n #if os(Linux)\n // SSE is not fully supported on Linux\n if streaming {\n logger.warning(\n \"SSE streaming was requested but is not fully supported on Linux. SSE connection will not be attempted.\"\n )\n }\n #else\n // This is the original code for platforms that support SSE\n guard isConnected else { return }\n\n // Wait for the initial session ID signal, but only if sessionID isn't already set\n if self.sessionID == nil, let signalTask = self.initialSessionIDSignalTask {\n logger.trace(\"SSE streaming task waiting for initial sessionID signal...\")\n\n // Race the signalTask against a timeout\n let timeoutTask = Task {\n try? await Task.sleep(for: .seconds(self.sseInitializationTimeout))\n return false\n }\n\n let signalCompletionTask = Task {\n await signalTask.value\n return true // Indicates signal received\n }\n\n // Use TaskGroup to race the two tasks\n var signalReceived = false\n do {\n signalReceived = try await withThrowingTaskGroup(of: Bool.self) { group in\n group.addTask {\n await signalCompletionTask.value\n }\n group.addTask {\n await timeoutTask.value\n }\n\n // Take the first result and cancel the other task\n if let firstResult = try await group.next() {\n group.cancelAll()\n return firstResult\n }\n return false\n }\n } catch {\n logger.error(\"Error while waiting for session ID signal: \\(error)\")\n }\n\n // Clean up tasks\n timeoutTask.cancel()\n\n if signalReceived {\n logger.trace(\"SSE streaming task proceeding after initial sessionID signal.\")\n } else {\n logger.warning(\n \"Timeout waiting for initial sessionID signal. SSE stream will proceed (sessionID might be nil).\"\n )\n }\n } else if self.sessionID != nil {\n logger.trace(\n \"Initial sessionID already available. Proceeding with SSE streaming task immediately.\"\n )\n } else {\n logger.info(\n \"Proceeding with SSE connection attempt; sessionID is nil. This might be expected for stateless servers or if initialize hasn't provided one yet.\"\n )\n }\n\n // Retry loop for connection drops\n while isConnected && !Task.isCancelled {\n do {\n try await connectToEventStream()\n } catch {\n if !Task.isCancelled {\n logger.error(\"SSE connection error: \\(error)\")\n // Wait before retrying\n try? await Task.sleep(for: .seconds(1))\n }\n }\n }\n #endif\n }\n\n #if !os(Linux)\n /// Establishes an SSE connection to the server\n ///\n /// This initiates a GET request to the server endpoint with appropriate\n /// headers to establish an SSE stream according to the MCP specification.\n ///\n /// - Throws: MCPError for connection failures or server errors\n private func connectToEventStream() async throws {\n guard isConnected else { return }\n\n var request = URLRequest(url: endpoint)\n request.httpMethod = \"GET\"\n request.addValue(\"text/event-stream\", forHTTPHeaderField: \"Accept\")\n request.addValue(\"no-cache\", forHTTPHeaderField: \"Cache-Control\")\n\n // Add session ID if available\n if let sessionID = sessionID {\n request.addValue(sessionID, forHTTPHeaderField: \"Mcp-Session-Id\")\n }\n\n logger.debug(\"Starting SSE connection\")\n\n // Create URLSession task for SSE\n let (stream, response) = try await session.bytes(for: request)\n\n guard let httpResponse = response as? HTTPURLResponse else {\n throw MCPError.internalError(\"Invalid HTTP response\")\n }\n\n // Check response status\n guard httpResponse.statusCode == 200 else {\n // If the server returns 405 Method Not Allowed,\n // it indicates that the server doesn't support SSE streaming.\n // We should cancel the task instead of retrying the connection.\n if httpResponse.statusCode == 405 {\n self.streamingTask?.cancel()\n }\n throw MCPError.internalError(\"HTTP error: \\(httpResponse.statusCode)\")\n }\n\n // Extract session ID if present\n if let newSessionID = httpResponse.value(forHTTPHeaderField: \"Mcp-Session-Id\") {\n let wasSessionIDNil = (self.sessionID == nil)\n self.sessionID = newSessionID\n if wasSessionIDNil {\n // Trigger signal on first session ID, though this is unlikely to happen here\n // as GET usually follows a POST that would have already set the session ID\n triggerInitialSessionIDSignal()\n }\n logger.debug(\"Session ID received\", metadata: [\"sessionID\": \"\\(newSessionID)\"])\n }\n\n try await self.processSSE(stream)\n }\n\n /// Processes an SSE byte stream, extracting events and delivering them\n ///\n /// - Parameter stream: The URLSession.AsyncBytes stream to process\n /// - Throws: Error for stream processing failures\n private func processSSE(_ stream: URLSession.AsyncBytes) async throws {\n do {\n for try await event in stream.events {\n // Check if task has been cancelled\n if Task.isCancelled { break }\n\n logger.trace(\n \"SSE event received\",\n metadata: [\n \"type\": \"\\(event.event ?? \"message\")\",\n \"id\": \"\\(event.id ?? \"none\")\",\n ]\n )\n\n // Convert the event data to Data and yield it to the message stream\n if !event.data.isEmpty, let data = event.data.data(using: .utf8) {\n messageContinuation.yield(data)\n }\n }\n } catch {\n logger.error(\"Error processing SSE events: \\(error)\")\n throw error\n }\n }\n #endif\n}\n"], ["/swift-sdk/Sources/MCP/Client/Client.swift", "import Logging\n\nimport struct Foundation.Data\nimport struct Foundation.Date\nimport class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\n/// Model Context Protocol client\npublic actor Client {\n /// The client configuration\n public struct Configuration: Hashable, Codable, Sendable {\n /// The default configuration.\n public static let `default` = Configuration(strict: false)\n\n /// The strict configuration.\n public static let strict = Configuration(strict: true)\n\n /// When strict mode is enabled, the client:\n /// - Requires server capabilities to be initialized before making requests\n /// - Rejects all requests that require capabilities before initialization\n ///\n /// While the MCP specification requires servers to respond to initialize requests\n /// with their capabilities, some implementations may not follow this.\n /// Disabling strict mode allows the client to be more lenient with non-compliant\n /// servers, though this may lead to undefined behavior.\n public var strict: Bool\n\n public init(strict: Bool = false) {\n self.strict = strict\n }\n }\n\n /// Implementation information\n public struct Info: Hashable, Codable, Sendable {\n /// The client name\n public var name: String\n /// The client version\n public var version: String\n\n public init(name: String, version: String) {\n self.name = name\n self.version = version\n }\n }\n\n /// The client capabilities\n public struct Capabilities: Hashable, Codable, Sendable {\n /// The roots capabilities\n public struct Roots: Hashable, Codable, Sendable {\n /// Whether the list of roots has changed\n public var listChanged: Bool?\n\n public init(listChanged: Bool? = nil) {\n self.listChanged = listChanged\n }\n }\n\n /// The sampling capabilities\n public struct Sampling: Hashable, Codable, Sendable {\n public init() {}\n }\n\n /// Whether the client supports sampling\n public var sampling: Sampling?\n /// Experimental features supported by the client\n public var experimental: [String: String]?\n /// Whether the client supports roots\n public var roots: Capabilities.Roots?\n\n public init(\n sampling: Sampling? = nil,\n experimental: [String: String]? = nil,\n roots: Capabilities.Roots? = nil\n ) {\n self.sampling = sampling\n self.experimental = experimental\n self.roots = roots\n }\n }\n\n /// The connection to the server\n private var connection: (any Transport)?\n /// The logger for the client\n private var logger: Logger? {\n get async {\n await connection?.logger\n }\n }\n\n /// The client information\n private let clientInfo: Client.Info\n /// The client name\n public nonisolated var name: String { clientInfo.name }\n /// The client version\n public nonisolated var version: String { clientInfo.version }\n\n /// The client capabilities\n public var capabilities: Client.Capabilities\n /// The client configuration\n public var configuration: Configuration\n\n /// The server capabilities\n private var serverCapabilities: Server.Capabilities?\n /// The server version\n private var serverVersion: String?\n /// The server instructions\n private var instructions: String?\n\n /// A dictionary of type-erased notification handlers, keyed by method name\n private var notificationHandlers: [String: [NotificationHandlerBox]] = [:]\n /// The task for the message handling loop\n private var task: Task?\n\n /// An error indicating a type mismatch when decoding a pending request\n private struct TypeMismatchError: Swift.Error {}\n\n /// A pending request with a continuation for the result\n private struct PendingRequest {\n let continuation: CheckedContinuation\n }\n\n /// A type-erased pending request\n private struct AnyPendingRequest {\n private let _resume: (Result) -> Void\n\n init(_ request: PendingRequest) {\n _resume = { result in\n switch result {\n case .success(let value):\n if let typedValue = value as? T {\n request.continuation.resume(returning: typedValue)\n } else if let value = value as? Value,\n let data = try? JSONEncoder().encode(value),\n let decoded = try? JSONDecoder().decode(T.self, from: data)\n {\n request.continuation.resume(returning: decoded)\n } else {\n request.continuation.resume(throwing: TypeMismatchError())\n }\n case .failure(let error):\n request.continuation.resume(throwing: error)\n }\n }\n }\n func resume(returning value: Any) {\n _resume(.success(value))\n }\n\n func resume(throwing error: Swift.Error) {\n _resume(.failure(error))\n }\n }\n\n /// A dictionary of type-erased pending requests, keyed by request ID\n private var pendingRequests: [ID: AnyPendingRequest] = [:]\n // Add reusable JSON encoder/decoder\n private let encoder = JSONEncoder()\n private let decoder = JSONDecoder()\n\n public init(\n name: String,\n version: String,\n configuration: Configuration = .default\n ) {\n self.clientInfo = Client.Info(name: name, version: version)\n self.capabilities = Capabilities()\n self.configuration = configuration\n }\n\n /// Connect to the server using the given transport\n @discardableResult\n public func connect(transport: any Transport) async throws -> Initialize.Result {\n self.connection = transport\n try await self.connection?.connect()\n\n await logger?.info(\n \"Client connected\", metadata: [\"name\": \"\\(name)\", \"version\": \"\\(version)\"])\n\n // Start message handling loop\n task = Task {\n guard let connection = self.connection else { return }\n repeat {\n // Check for cancellation before starting the iteration\n if Task.isCancelled { break }\n\n do {\n let stream = await connection.receive()\n for try await data in stream {\n if Task.isCancelled { break } // Check inside loop too\n\n // Attempt to decode data\n // Try decoding as a batch response first\n if let batchResponse = try? decoder.decode([AnyResponse].self, from: data) {\n await handleBatchResponse(batchResponse)\n } else if let response = try? decoder.decode(AnyResponse.self, from: data) {\n await handleResponse(response)\n } else if let message = try? decoder.decode(AnyMessage.self, from: data) {\n await handleMessage(message)\n } else {\n var metadata: Logger.Metadata = [:]\n if let string = String(data: data, encoding: .utf8) {\n metadata[\"message\"] = .string(string)\n }\n await logger?.warning(\n \"Unexpected message received by client (not single/batch response or notification)\",\n metadata: metadata\n )\n }\n }\n } catch let error where MCPError.isResourceTemporarilyUnavailable(error) {\n try? await Task.sleep(for: .milliseconds(10))\n continue\n } catch {\n await logger?.error(\n \"Error in message handling loop\", metadata: [\"error\": \"\\(error)\"])\n break\n }\n } while true\n await self.logger?.info(\"Client message handling loop task is terminating.\")\n }\n\n // Automatically initialize after connecting\n return try await _initialize()\n }\n\n /// Disconnect the client and cancel all pending requests\n public func disconnect() async {\n await logger?.info(\"Initiating client disconnect...\")\n\n // Part 1: Inside actor - Grab state and clear internal references\n let taskToCancel = self.task\n let connectionToDisconnect = self.connection\n let pendingRequestsToCancel = self.pendingRequests\n\n self.task = nil\n self.connection = nil\n self.pendingRequests = [:] // Use empty dictionary literal\n\n // Part 2: Outside actor - Resume continuations, disconnect transport, await task\n\n // Resume continuations first\n for (_, request) in pendingRequestsToCancel {\n request.resume(throwing: MCPError.internalError(\"Client disconnected\"))\n }\n await logger?.info(\"Pending requests cancelled.\")\n\n // Cancel the task\n taskToCancel?.cancel()\n await logger?.info(\"Message loop task cancellation requested.\")\n\n // Disconnect the transport *before* awaiting the task\n // This should ensure the transport stream is finished, unblocking the loop.\n if let conn = connectionToDisconnect {\n await conn.disconnect()\n await logger?.info(\"Transport disconnected.\")\n } else {\n await logger?.info(\"No active transport connection to disconnect.\")\n }\n\n // Await the task completion *after* transport disconnect\n _ = await taskToCancel?.value\n await logger?.info(\"Client message loop task finished.\")\n\n await logger?.info(\"Client disconnect complete.\")\n }\n\n // MARK: - Registration\n\n /// Register a handler for a notification\n @discardableResult\n public func onNotification(\n _ type: N.Type,\n handler: @escaping @Sendable (Message) async throws -> Void\n ) async -> Self {\n let handlers = notificationHandlers[N.name, default: []]\n notificationHandlers[N.name] = handlers + [TypedNotificationHandler(handler)]\n return self\n }\n\n /// Send a notification to the server\n public func notify(_ notification: Message) async throws {\n guard let connection = connection else {\n throw MCPError.internalError(\"Client connection not initialized\")\n }\n\n let notificationData = try encoder.encode(notification)\n try await connection.send(notificationData)\n }\n\n // MARK: - Requests\n\n /// Send a request and receive its response\n public func send(_ request: Request) async throws -> M.Result {\n guard let connection = connection else {\n throw MCPError.internalError(\"Client connection not initialized\")\n }\n\n let requestData = try encoder.encode(request)\n\n // Store the pending request first\n return try await withCheckedThrowingContinuation { continuation in\n Task {\n // Add the pending request before attempting to send\n self.addPendingRequest(\n id: request.id,\n continuation: continuation,\n type: M.Result.self\n )\n\n // Send the request data\n do {\n // Use the existing connection send\n try await connection.send(requestData)\n } catch {\n // If send fails, try to remove the pending request.\n // Resume with the send error only if we successfully removed the request,\n // indicating the response handler hasn't processed it yet.\n if self.removePendingRequest(id: request.id) != nil {\n continuation.resume(throwing: error)\n }\n // Otherwise, the request was already removed by the response handler\n // or by disconnect, so the continuation was already resumed.\n // Do nothing here.\n }\n }\n }\n }\n\n private func addPendingRequest(\n id: ID,\n continuation: CheckedContinuation,\n type: T.Type // Keep type for AnyPendingRequest internal logic\n ) {\n pendingRequests[id] = AnyPendingRequest(PendingRequest(continuation: continuation))\n }\n\n private func removePendingRequest(id: ID) -> AnyPendingRequest? {\n return pendingRequests.removeValue(forKey: id)\n }\n\n // MARK: - Batching\n\n /// A batch of requests.\n ///\n /// Objects of this type are passed as an argument to the closure\n /// of the ``Client/withBatch(_:)`` method.\n public actor Batch {\n unowned let client: Client\n var requests: [AnyRequest] = []\n\n init(client: Client) {\n self.client = client\n }\n\n /// Adds a request to the batch and prepares its expected response task.\n /// The actual sending happens when the `withBatch` scope completes.\n /// - Returns: A `Task` that will eventually produce the result or throw an error.\n public func addRequest(_ request: Request) async throws -> Task<\n M.Result, Swift.Error\n > {\n requests.append(try AnyRequest(request))\n\n // Return a Task that registers the pending request and awaits its result.\n // The continuation is resumed when the response arrives.\n return Task {\n try await withCheckedThrowingContinuation { continuation in\n // We are already inside a Task, but need another Task\n // to bridge to the client actor's context.\n Task {\n await client.addPendingRequest(\n id: request.id,\n continuation: continuation,\n type: M.Result.self\n )\n }\n }\n }\n }\n }\n\n /// Executes multiple requests in a single batch.\n ///\n /// This method allows you to group multiple MCP requests together,\n /// which are then sent to the server as a single JSON array.\n /// The server processes these requests and sends back a corresponding\n /// JSON array of responses.\n ///\n /// Within the `body` closure, use the provided `Batch` actor to add\n /// requests using `batch.addRequest(_:)`. Each call to `addRequest`\n /// returns a `Task` handle representing the asynchronous operation\n /// for that specific request's result.\n ///\n /// It's recommended to collect these `Task` handles into an array\n /// within the `body` closure`. After the `withBatch` method returns\n /// (meaning the batch request has been sent), you can then process\n /// the results by awaiting each `Task` in the collected array.\n ///\n /// Example 1: Batching multiple tool calls and collecting typed tasks:\n /// ```swift\n /// // Array to hold the task handles for each tool call\n /// var toolTasks: [Task] = []\n /// try await client.withBatch { batch in\n /// for i in 0..<10 {\n /// toolTasks.append(\n /// try await batch.addRequest(\n /// CallTool.request(.init(name: \"square\", arguments: [\"n\": i]))\n /// )\n /// )\n /// }\n /// }\n ///\n /// // Process results after the batch is sent\n /// print(\"Processing \\(toolTasks.count) tool results...\")\n /// for (index, task) in toolTasks.enumerated() {\n /// do {\n /// let result = try await task.value\n /// print(\"\\(index): \\(result.content)\")\n /// } catch {\n /// print(\"\\(index) failed: \\(error)\")\n /// }\n /// }\n /// ```\n ///\n /// Example 2: Batching different request types and awaiting individual tasks:\n /// ```swift\n /// // Declare optional task variables beforehand\n /// var pingTask: Task?\n /// var promptTask: Task?\n ///\n /// try await client.withBatch { batch in\n /// // Assign the tasks within the batch closure\n /// pingTask = try await batch.addRequest(Ping.request())\n /// promptTask = try await batch.addRequest(GetPrompt.request(.init(name: \"greeting\")))\n /// }\n ///\n /// // Await the results after the batch is sent\n /// do {\n /// if let pingTask = pingTask {\n /// try await pingTask.value // Await ping result (throws if ping failed)\n /// print(\"Ping successful\")\n /// }\n /// if let promptTask = promptTask {\n /// let promptResult = try await promptTask.value // Await prompt result\n /// print(\"Prompt description: \\(promptResult.description ?? \"None\")\")\n /// }\n /// } catch {\n /// print(\"Error processing batch results: \\(error)\")\n /// }\n /// ```\n ///\n /// - Parameter body: An asynchronous closure that takes a `Batch` object as input.\n /// Use this object to add requests to the batch.\n /// - Throws: `MCPError.internalError` if the client is not connected.\n /// Can also rethrow errors from the `body` closure or from sending the batch request.\n public func withBatch(body: @escaping (Batch) async throws -> Void) async throws {\n guard let connection = connection else {\n throw MCPError.internalError(\"Client connection not initialized\")\n }\n\n // Create Batch actor, passing self (Client)\n let batch = Batch(client: self)\n\n // Populate the batch actor by calling the user's closure.\n try await body(batch)\n\n // Get the collected requests from the batch actor\n let requests = await batch.requests\n\n // Check if there are any requests to send\n guard !requests.isEmpty else {\n await logger?.info(\"Batch requested but no requests were added.\")\n return // Nothing to send\n }\n\n await logger?.debug(\n \"Sending batch request\", metadata: [\"count\": \"\\(requests.count)\"])\n\n // Encode the array of AnyMethod requests into a single JSON payload\n let data = try encoder.encode(requests)\n try await connection.send(data)\n\n // Responses will be handled asynchronously by the message loop and handleBatchResponse/handleResponse.\n }\n\n // MARK: - Lifecycle\n\n /// Initialize the connection with the server.\n ///\n /// - Important: This method is deprecated. Initialization now happens automatically\n /// when calling `connect(transport:)`. You should use that method instead.\n ///\n /// - Returns: The server's initialization response containing capabilities and server info\n @available(\n *, deprecated,\n message:\n \"Initialization now happens automatically during connect. Use connect(transport:) instead.\"\n )\n public func initialize() async throws -> Initialize.Result {\n return try await _initialize()\n }\n\n /// Internal initialization implementation\n private func _initialize() async throws -> Initialize.Result {\n let request = Initialize.request(\n .init(\n protocolVersion: Version.latest,\n capabilities: capabilities,\n clientInfo: clientInfo\n ))\n\n let result = try await send(request)\n\n self.serverCapabilities = result.capabilities\n self.serverVersion = result.protocolVersion\n self.instructions = result.instructions\n\n try await notify(InitializedNotification.message())\n\n return result\n }\n\n public func ping() async throws {\n let request = Ping.request()\n _ = try await send(request)\n }\n\n // MARK: - Prompts\n\n public func getPrompt(name: String, arguments: [String: Value]? = nil) async throws\n -> (description: String?, messages: [Prompt.Message])\n {\n try validateServerCapability(\\.prompts, \"Prompts\")\n let request = GetPrompt.request(.init(name: name, arguments: arguments))\n let result = try await send(request)\n return (description: result.description, messages: result.messages)\n }\n\n public func listPrompts(cursor: String? = nil) async throws\n -> (prompts: [Prompt], nextCursor: String?)\n {\n try validateServerCapability(\\.prompts, \"Prompts\")\n let request: Request\n if let cursor = cursor {\n request = ListPrompts.request(.init(cursor: cursor))\n } else {\n request = ListPrompts.request(.init())\n }\n let result = try await send(request)\n return (prompts: result.prompts, nextCursor: result.nextCursor)\n }\n\n // MARK: - Resources\n\n public func readResource(uri: String) async throws -> [Resource.Content] {\n try validateServerCapability(\\.resources, \"Resources\")\n let request = ReadResource.request(.init(uri: uri))\n let result = try await send(request)\n return result.contents\n }\n\n public func listResources(cursor: String? = nil) async throws -> (\n resources: [Resource], nextCursor: String?\n ) {\n try validateServerCapability(\\.resources, \"Resources\")\n let request: Request\n if let cursor = cursor {\n request = ListResources.request(.init(cursor: cursor))\n } else {\n request = ListResources.request(.init())\n }\n let result = try await send(request)\n return (resources: result.resources, nextCursor: result.nextCursor)\n }\n\n public func subscribeToResource(uri: String) async throws {\n try validateServerCapability(\\.resources?.subscribe, \"Resource subscription\")\n let request = ResourceSubscribe.request(.init(uri: uri))\n _ = try await send(request)\n }\n\n public func listResourceTemplates(cursor: String? = nil) async throws -> (\n templates: [Resource.Template], nextCursor: String?\n ) {\n try validateServerCapability(\\.resources, \"Resources\")\n let request: Request\n if let cursor = cursor {\n request = ListResourceTemplates.request(.init(cursor: cursor))\n } else {\n request = ListResourceTemplates.request(.init())\n }\n let result = try await send(request)\n return (templates: result.templates, nextCursor: result.nextCursor)\n }\n\n // MARK: - Tools\n\n public func listTools(cursor: String? = nil) async throws -> (\n tools: [Tool], nextCursor: String?\n ) {\n try validateServerCapability(\\.tools, \"Tools\")\n let request: Request\n if let cursor = cursor {\n request = ListTools.request(.init(cursor: cursor))\n } else {\n request = ListTools.request(.init())\n }\n let result = try await send(request)\n return (tools: result.tools, nextCursor: result.nextCursor)\n }\n\n public func callTool(name: String, arguments: [String: Value]? = nil) async throws -> (\n content: [Tool.Content], isError: Bool?\n ) {\n try validateServerCapability(\\.tools, \"Tools\")\n let request = CallTool.request(.init(name: name, arguments: arguments))\n let result = try await send(request)\n return (content: result.content, isError: result.isError)\n }\n\n // MARK: - Sampling\n\n /// Register a handler for sampling requests from servers\n ///\n /// Sampling allows servers to request LLM completions through the client,\n /// enabling sophisticated agentic behaviors while maintaining human-in-the-loop control.\n ///\n /// The sampling flow follows these steps:\n /// 1. Server sends a `sampling/createMessage` request to the client\n /// 2. Client reviews the request and can modify it (via this handler)\n /// 3. Client samples from an LLM (via this handler)\n /// 4. Client reviews the completion (via this handler)\n /// 5. Client returns the result to the server\n ///\n /// - Parameter handler: A closure that processes sampling requests and returns completions\n /// - Returns: Self for method chaining\n /// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/sampling#how-sampling-works\n @discardableResult\n public func withSamplingHandler(\n _ handler: @escaping @Sendable (CreateSamplingMessage.Parameters) async throws ->\n CreateSamplingMessage.Result\n ) -> Self {\n // Note: This would require extending the client architecture to handle incoming requests from servers.\n // The current MCP Swift SDK architecture assumes clients only send requests to servers,\n // but sampling requires bidirectional communication where servers can send requests to clients.\n //\n // A full implementation would need:\n // 1. Request handlers in the client (similar to how servers handle requests)\n // 2. Bidirectional transport support\n // 3. Request/response correlation for server-to-client requests\n //\n // For now, this serves as the correct API design for when bidirectional support is added.\n\n // This would register the handler similar to how servers register method handlers:\n // methodHandlers[CreateSamplingMessage.name] = TypedRequestHandler(handler)\n\n return self\n }\n\n // MARK: -\n\n private func handleResponse(_ response: Response) async {\n await logger?.trace(\n \"Processing response\",\n metadata: [\"id\": \"\\(response.id)\"])\n\n // Attempt to remove the pending request using the response ID.\n // Resume with the response only if it hadn't yet been removed.\n if let removedRequest = self.removePendingRequest(id: response.id) {\n // If we successfully removed it, resume its continuation.\n switch response.result {\n case .success(let value):\n removedRequest.resume(returning: value)\n case .failure(let error):\n removedRequest.resume(throwing: error)\n }\n } else {\n // Request was already removed (e.g., by send error handler or disconnect).\n // Log this, but it's not an error in race condition scenarios.\n await logger?.warning(\n \"Attempted to handle response for already removed request\",\n metadata: [\"id\": \"\\(response.id)\"]\n )\n }\n }\n\n private func handleMessage(_ message: Message) async {\n await logger?.trace(\n \"Processing notification\",\n metadata: [\"method\": \"\\(message.method)\"])\n\n // Find notification handlers for this method\n guard let handlers = notificationHandlers[message.method] else { return }\n\n // Convert notification parameters to concrete type and call handlers\n for handler in handlers {\n do {\n try await handler(message)\n } catch {\n await logger?.error(\n \"Error handling notification\",\n metadata: [\n \"method\": \"\\(message.method)\",\n \"error\": \"\\(error)\",\n ])\n }\n }\n }\n\n // MARK: -\n\n /// Validate the server capabilities.\n /// Throws an error if the client is configured to be strict and the capability is not supported.\n private func validateServerCapability(\n _ keyPath: KeyPath,\n _ name: String\n )\n throws\n {\n if configuration.strict {\n guard let capabilities = serverCapabilities else {\n throw MCPError.methodNotFound(\"Server capabilities not initialized\")\n }\n guard capabilities[keyPath: keyPath] != nil else {\n throw MCPError.methodNotFound(\"\\(name) is not supported by the server\")\n }\n }\n }\n\n // Add handler for batch responses\n private func handleBatchResponse(_ responses: [AnyResponse]) async {\n await logger?.trace(\"Processing batch response\", metadata: [\"count\": \"\\(responses.count)\"])\n for response in responses {\n // Attempt to remove the pending request.\n // If successful, pendingRequest contains the request.\n if let pendingRequest = self.removePendingRequest(id: response.id) {\n // If we successfully removed it, handle the response using the pending request.\n switch response.result {\n case .success(let value):\n pendingRequest.resume(returning: value)\n case .failure(let error):\n pendingRequest.resume(throwing: error)\n }\n } else {\n // If removal failed, it means the request ID was not found (or already handled).\n // Log a warning.\n await logger?.warning(\n \"Received response in batch for unknown or already handled request ID\",\n metadata: [\"id\": \"\\(response.id)\"]\n )\n }\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Server/Server.swift", "import Logging\n\nimport struct Foundation.Data\nimport struct Foundation.Date\nimport class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\n/// Model Context Protocol server\npublic actor Server {\n /// The server configuration\n public struct Configuration: Hashable, Codable, Sendable {\n /// The default configuration.\n public static let `default` = Configuration(strict: false)\n\n /// The strict configuration.\n public static let strict = Configuration(strict: true)\n\n /// When strict mode is enabled, the server:\n /// - Requires clients to send an initialize request before any other requests\n /// - Rejects all requests from uninitialized clients with a protocol error\n ///\n /// While the MCP specification requires clients to initialize the connection\n /// before sending other requests, some implementations may not follow this.\n /// Disabling strict mode allows the server to be more lenient with non-compliant\n /// clients, though this may lead to undefined behavior.\n public var strict: Bool\n }\n\n /// Implementation information\n public struct Info: Hashable, Codable, Sendable {\n /// The server name\n public let name: String\n /// The server version\n public let version: String\n\n public init(name: String, version: String) {\n self.name = name\n self.version = version\n }\n }\n\n /// Server capabilities\n public struct Capabilities: Hashable, Codable, Sendable {\n /// Resources capabilities\n public struct Resources: Hashable, Codable, Sendable {\n /// Whether the resource can be subscribed to\n public var subscribe: Bool?\n /// Whether the list of resources has changed\n public var listChanged: Bool?\n\n public init(\n subscribe: Bool? = nil,\n listChanged: Bool? = nil\n ) {\n self.subscribe = subscribe\n self.listChanged = listChanged\n }\n }\n\n /// Tools capabilities\n public struct Tools: Hashable, Codable, Sendable {\n /// Whether the server notifies clients when tools change\n public var listChanged: Bool?\n\n public init(listChanged: Bool? = nil) {\n self.listChanged = listChanged\n }\n }\n\n /// Prompts capabilities\n public struct Prompts: Hashable, Codable, Sendable {\n /// Whether the server notifies clients when prompts change\n public var listChanged: Bool?\n\n public init(listChanged: Bool? = nil) {\n self.listChanged = listChanged\n }\n }\n\n /// Logging capabilities\n public struct Logging: Hashable, Codable, Sendable {\n public init() {}\n }\n\n /// Sampling capabilities\n public struct Sampling: Hashable, Codable, Sendable {\n public init() {}\n }\n\n /// Logging capabilities\n public var logging: Logging?\n /// Prompts capabilities\n public var prompts: Prompts?\n /// Resources capabilities\n public var resources: Resources?\n /// Sampling capabilities\n public var sampling: Sampling?\n /// Tools capabilities\n public var tools: Tools?\n\n public init(\n logging: Logging? = nil,\n prompts: Prompts? = nil,\n resources: Resources? = nil,\n sampling: Sampling? = nil,\n tools: Tools? = nil\n ) {\n self.logging = logging\n self.prompts = prompts\n self.resources = resources\n self.sampling = sampling\n self.tools = tools\n }\n }\n\n /// Server information\n private let serverInfo: Server.Info\n /// The server connection\n private var connection: (any Transport)?\n /// The server logger\n private var logger: Logger? {\n get async {\n await connection?.logger\n }\n }\n\n /// The server name\n public nonisolated var name: String { serverInfo.name }\n /// The server version\n public nonisolated var version: String { serverInfo.version }\n /// The server capabilities\n public var capabilities: Capabilities\n /// The server configuration\n public var configuration: Configuration\n\n /// Request handlers\n private var methodHandlers: [String: RequestHandlerBox] = [:]\n /// Notification handlers\n private var notificationHandlers: [String: [NotificationHandlerBox]] = [:]\n\n /// Whether the server is initialized\n private var isInitialized = false\n /// The client information\n private var clientInfo: Client.Info?\n /// The client capabilities\n private var clientCapabilities: Client.Capabilities?\n /// The protocol version\n private var protocolVersion: String?\n /// The list of subscriptions\n private var subscriptions: [String: Set] = [:]\n /// The task for the message handling loop\n private var task: Task?\n\n public init(\n name: String,\n version: String,\n capabilities: Server.Capabilities = .init(),\n configuration: Configuration = .default\n ) {\n self.serverInfo = Server.Info(name: name, version: version)\n self.capabilities = capabilities\n self.configuration = configuration\n }\n\n /// Start the server\n /// - Parameters:\n /// - transport: The transport to use for the server\n /// - initializeHook: An optional hook that runs when the client sends an initialize request\n public func start(\n transport: any Transport,\n initializeHook: (@Sendable (Client.Info, Client.Capabilities) async throws -> Void)? = nil\n ) async throws {\n self.connection = transport\n registerDefaultHandlers(initializeHook: initializeHook)\n try await transport.connect()\n\n await logger?.info(\n \"Server started\", metadata: [\"name\": \"\\(name)\", \"version\": \"\\(version)\"])\n\n // Start message handling loop\n task = Task {\n do {\n let stream = await transport.receive()\n for try await data in stream {\n if Task.isCancelled { break } // Check cancellation inside loop\n\n var requestID: ID?\n do {\n // Attempt to decode as batch first, then as individual request or notification\n let decoder = JSONDecoder()\n if let batch = try? decoder.decode(Server.Batch.self, from: data) {\n try await handleBatch(batch)\n } else if let request = try? decoder.decode(AnyRequest.self, from: data) {\n _ = try await handleRequest(request, sendResponse: true)\n } else if let message = try? decoder.decode(AnyMessage.self, from: data) {\n try await handleMessage(message)\n } else {\n // Try to extract request ID from raw JSON if possible\n if let json = try? JSONDecoder().decode(\n [String: Value].self, from: data),\n let idValue = json[\"id\"]\n {\n if let strValue = idValue.stringValue {\n requestID = .string(strValue)\n } else if let intValue = idValue.intValue {\n requestID = .number(intValue)\n }\n }\n throw MCPError.parseError(\"Invalid message format\")\n }\n } catch let error where MCPError.isResourceTemporarilyUnavailable(error) {\n // Resource temporarily unavailable, retry after a short delay\n try? await Task.sleep(for: .milliseconds(10))\n continue\n } catch {\n await logger?.error(\n \"Error processing message\", metadata: [\"error\": \"\\(error)\"])\n let response = AnyMethod.response(\n id: requestID ?? .random,\n error: error as? MCPError\n ?? MCPError.internalError(error.localizedDescription)\n )\n try? await send(response)\n }\n }\n } catch {\n await logger?.error(\n \"Fatal error in message handling loop\", metadata: [\"error\": \"\\(error)\"])\n }\n await logger?.info(\"Server finished\", metadata: [:])\n }\n }\n\n /// Stop the server\n public func stop() async {\n task?.cancel()\n task = nil\n if let connection = connection {\n await connection.disconnect()\n }\n connection = nil\n }\n\n public func waitUntilCompleted() async {\n await task?.value\n }\n\n // MARK: - Registration\n\n /// Register a method handler\n @discardableResult\n public func withMethodHandler(\n _ type: M.Type,\n handler: @escaping @Sendable (M.Parameters) async throws -> M.Result\n ) -> Self {\n methodHandlers[M.name] = TypedRequestHandler { (request: Request) -> Response in\n let result = try await handler(request.params)\n return Response(id: request.id, result: result)\n }\n return self\n }\n\n /// Register a notification handler\n @discardableResult\n public func onNotification(\n _ type: N.Type,\n handler: @escaping @Sendable (Message) async throws -> Void\n ) -> Self {\n let handlers = notificationHandlers[N.name, default: []]\n notificationHandlers[N.name] = handlers + [TypedNotificationHandler(handler)]\n return self\n }\n\n // MARK: - Sending\n\n /// Send a response to a request\n public func send(_ response: Response) async throws {\n guard let connection = connection else {\n throw MCPError.internalError(\"Server connection not initialized\")\n }\n\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]\n\n let responseData = try encoder.encode(response)\n try await connection.send(responseData)\n }\n\n /// Send a notification to connected clients\n public func notify(_ notification: Message) async throws {\n guard let connection = connection else {\n throw MCPError.internalError(\"Server connection not initialized\")\n }\n\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]\n\n let notificationData = try encoder.encode(notification)\n try await connection.send(notificationData)\n }\n\n // MARK: - Sampling\n\n /// Request sampling from the connected client\n ///\n /// Sampling allows servers to request LLM completions through the client,\n /// enabling sophisticated agentic behaviors while maintaining human-in-the-loop control.\n ///\n /// The sampling flow follows these steps:\n /// 1. Server sends a `sampling/createMessage` request to the client\n /// 2. Client reviews the request and can modify it\n /// 3. Client samples from an LLM\n /// 4. Client reviews the completion\n /// 5. Client returns the result to the server\n ///\n /// - Parameters:\n /// - messages: The conversation history to send to the LLM\n /// - modelPreferences: Model selection preferences\n /// - systemPrompt: Optional system prompt\n /// - includeContext: What MCP context to include\n /// - temperature: Controls randomness (0.0 to 1.0)\n /// - maxTokens: Maximum tokens to generate\n /// - stopSequences: Array of sequences that stop generation\n /// - metadata: Additional provider-specific parameters\n /// - Returns: The sampling result containing the model used, stop reason, role, and content\n /// - Throws: MCPError if the request fails\n /// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/sampling#how-sampling-works\n public func requestSampling(\n messages: [Sampling.Message],\n modelPreferences: Sampling.ModelPreferences? = nil,\n systemPrompt: String? = nil,\n includeContext: Sampling.ContextInclusion? = nil,\n temperature: Double? = nil,\n maxTokens: Int,\n stopSequences: [String]? = nil,\n metadata: [String: Value]? = nil\n ) async throws -> CreateSamplingMessage.Result {\n guard connection != nil else {\n throw MCPError.internalError(\"Server connection not initialized\")\n }\n\n // Note: This is a conceptual implementation. The actual implementation would require\n // bidirectional communication support in the transport layer, allowing servers to\n // send requests to clients and receive responses.\n\n _ = CreateSamplingMessage.request(\n .init(\n messages: messages,\n modelPreferences: modelPreferences,\n systemPrompt: systemPrompt,\n includeContext: includeContext,\n temperature: temperature,\n maxTokens: maxTokens,\n stopSequences: stopSequences,\n metadata: metadata\n )\n )\n\n // This would need to be implemented with proper request/response handling\n // similar to how the client sends requests to servers\n throw MCPError.internalError(\n \"Bidirectional sampling requests not yet implemented in transport layer\")\n }\n\n /// A JSON-RPC batch containing multiple requests and/or notifications\n struct Batch: Sendable {\n /// An item in a JSON-RPC batch\n enum Item: Sendable {\n case request(Request)\n case notification(Message)\n\n }\n\n var items: [Item]\n\n init(items: [Item]) {\n self.items = items\n }\n }\n\n /// Process a batch of requests and/or notifications\n private func handleBatch(_ batch: Batch) async throws {\n await logger?.trace(\"Processing batch request\", metadata: [\"size\": \"\\(batch.items.count)\"])\n\n if batch.items.isEmpty {\n // Empty batch is invalid according to JSON-RPC spec\n let error = MCPError.invalidRequest(\"Batch array must not be empty\")\n let response = AnyMethod.response(id: .random, error: error)\n try await send(response)\n return\n }\n\n // Process each item in the batch and collect responses\n var responses: [Response] = []\n\n for item in batch.items {\n do {\n switch item {\n case .request(let request):\n // For batched requests, collect responses instead of sending immediately\n if let response = try await handleRequest(request, sendResponse: false) {\n responses.append(response)\n }\n\n case .notification(let notification):\n // Handle notification (no response needed)\n try await handleMessage(notification)\n }\n } catch {\n // Only add errors to response for requests (notifications don't have responses)\n if case .request(let request) = item {\n let mcpError =\n error as? MCPError ?? MCPError.internalError(error.localizedDescription)\n responses.append(AnyMethod.response(id: request.id, error: mcpError))\n }\n }\n }\n\n // Send collected responses if any\n if !responses.isEmpty {\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]\n let responseData = try encoder.encode(responses)\n\n guard let connection = connection else {\n throw MCPError.internalError(\"Server connection not initialized\")\n }\n\n try await connection.send(responseData)\n }\n }\n\n // MARK: - Request and Message Handling\n\n /// Handle a request and either send the response immediately or return it\n ///\n /// - Parameters:\n /// - request: The request to handle\n /// - sendResponse: Whether to send the response immediately (true) or return it (false)\n /// - Returns: The response when sendResponse is false\n private func handleRequest(_ request: Request, sendResponse: Bool = true)\n async throws -> Response?\n {\n // Check if this is a pre-processed error request (empty method)\n if request.method.isEmpty && !sendResponse {\n // This is a placeholder for an invalid request that couldn't be parsed in batch mode\n return AnyMethod.response(\n id: request.id,\n error: MCPError.invalidRequest(\"Invalid batch item format\")\n )\n }\n\n await logger?.trace(\n \"Processing request\",\n metadata: [\n \"method\": \"\\(request.method)\",\n \"id\": \"\\(request.id)\",\n ])\n\n if configuration.strict {\n // The client SHOULD NOT send requests other than pings\n // before the server has responded to the initialize request.\n switch request.method {\n case Initialize.name, Ping.name:\n break\n default:\n try checkInitialized()\n }\n }\n\n // Find handler for method name\n guard let handler = methodHandlers[request.method] else {\n let error = MCPError.methodNotFound(\"Unknown method: \\(request.method)\")\n let response = AnyMethod.response(id: request.id, error: error)\n\n if sendResponse {\n try await send(response)\n return nil\n }\n\n return response\n }\n\n do {\n // Handle request and get response\n let response = try await handler(request)\n\n if sendResponse {\n try await send(response)\n return nil\n }\n\n return response\n } catch {\n let mcpError = error as? MCPError ?? MCPError.internalError(error.localizedDescription)\n let response = AnyMethod.response(id: request.id, error: mcpError)\n\n if sendResponse {\n try await send(response)\n return nil\n }\n\n return response\n }\n }\n\n private func handleMessage(_ message: Message) async throws {\n await logger?.trace(\n \"Processing notification\",\n metadata: [\"method\": \"\\(message.method)\"])\n\n if configuration.strict {\n // Check initialization state unless this is an initialized notification\n if message.method != InitializedNotification.name {\n try checkInitialized()\n }\n }\n\n // Find notification handlers for this method\n guard let handlers = notificationHandlers[message.method] else { return }\n\n // Convert notification parameters to concrete type and call handlers\n for handler in handlers {\n do {\n try await handler(message)\n } catch {\n await logger?.error(\n \"Error handling notification\",\n metadata: [\n \"method\": \"\\(message.method)\",\n \"error\": \"\\(error)\",\n ])\n }\n }\n }\n\n private func checkInitialized() throws {\n guard isInitialized else {\n throw MCPError.invalidRequest(\"Server is not initialized\")\n }\n }\n\n private func registerDefaultHandlers(\n initializeHook: (@Sendable (Client.Info, Client.Capabilities) async throws -> Void)?\n ) {\n // Initialize\n withMethodHandler(Initialize.self) { [weak self] params in\n guard let self = self else {\n throw MCPError.internalError(\"Server was deallocated\")\n }\n\n guard await !self.isInitialized else {\n throw MCPError.invalidRequest(\"Server is already initialized\")\n }\n\n // Call initialization hook if registered\n if let hook = initializeHook {\n try await hook(params.clientInfo, params.capabilities)\n }\n\n // Perform version negotiation\n let clientRequestedVersion = params.protocolVersion\n let negotiatedProtocolVersion = Version.negotiate(\n clientRequestedVersion: clientRequestedVersion)\n\n // Set initial state with the negotiated protocol version\n await self.setInitialState(\n clientInfo: params.clientInfo,\n clientCapabilities: params.capabilities,\n protocolVersion: negotiatedProtocolVersion\n )\n\n return Initialize.Result(\n protocolVersion: negotiatedProtocolVersion,\n capabilities: await self.capabilities,\n serverInfo: self.serverInfo,\n instructions: nil\n )\n }\n\n // Ping\n withMethodHandler(Ping.self) { _ in return Empty() }\n }\n\n private func setInitialState(\n clientInfo: Client.Info,\n clientCapabilities: Client.Capabilities,\n protocolVersion: String\n ) async {\n self.clientInfo = clientInfo\n self.clientCapabilities = clientCapabilities\n self.protocolVersion = protocolVersion\n self.isInitialized = true\n }\n}\n\nextension Server.Batch: Codable {\n init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n\n let encoder = JSONEncoder()\n let decoder = JSONDecoder()\n\n var items: [Item] = []\n for item in try container.decode([Value].self) {\n let data = try encoder.encode(item)\n try items.append(decoder.decode(Item.self, from: data))\n }\n\n self.items = items\n }\n\n func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n try container.encode(items)\n }\n}\n\nextension Server.Batch.Item: Codable {\n private enum CodingKeys: String, CodingKey {\n case id\n }\n\n init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n // Check if it's a request (has id) or notification (no id)\n if container.contains(.id) {\n self = .request(try Request(from: decoder))\n } else {\n self = .notification(try Message(from: decoder))\n }\n }\n\n func encode(to encoder: Encoder) throws {\n switch self {\n case .request(let request):\n try request.encode(to: encoder)\n case .notification(let notification):\n try notification.encode(to: encoder)\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Error.swift", "import Foundation\n\n#if canImport(System)\n import System\n#else\n @preconcurrency import SystemPackage\n#endif\n\n/// A model context protocol error.\npublic enum MCPError: Swift.Error, Sendable {\n // Standard JSON-RPC 2.0 errors (-32700 to -32603)\n case parseError(String?) // -32700\n case invalidRequest(String?) // -32600\n case methodNotFound(String?) // -32601\n case invalidParams(String?) // -32602\n case internalError(String?) // -32603\n\n // Server errors (-32000 to -32099)\n case serverError(code: Int, message: String)\n\n // Transport specific errors\n case connectionClosed\n case transportError(Swift.Error)\n\n /// The JSON-RPC 2.0 error code\n public var code: Int {\n switch self {\n case .parseError: return -32700\n case .invalidRequest: return -32600\n case .methodNotFound: return -32601\n case .invalidParams: return -32602\n case .internalError: return -32603\n case .serverError(let code, _): return code\n case .connectionClosed: return -32000\n case .transportError: return -32001\n }\n }\n\n /// Check if an error represents a \"resource temporarily unavailable\" condition\n public static func isResourceTemporarilyUnavailable(_ error: Swift.Error) -> Bool {\n #if canImport(System)\n if let errno = error as? System.Errno, errno == .resourceTemporarilyUnavailable {\n return true\n }\n #else\n if let errno = error as? SystemPackage.Errno, errno == .resourceTemporarilyUnavailable {\n return true\n }\n #endif\n return false\n }\n}\n\n// MARK: LocalizedError\n\nextension MCPError: LocalizedError {\n public var errorDescription: String? {\n switch self {\n case .parseError(let detail):\n return \"Parse error: Invalid JSON\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .invalidRequest(let detail):\n return \"Invalid Request\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .methodNotFound(let detail):\n return \"Method not found\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .invalidParams(let detail):\n return \"Invalid params\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .internalError(let detail):\n return \"Internal error\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .serverError(_, let message):\n return \"Server error: \\(message)\"\n case .connectionClosed:\n return \"Connection closed\"\n case .transportError(let error):\n return \"Transport error: \\(error.localizedDescription)\"\n }\n }\n\n public var failureReason: String? {\n switch self {\n case .parseError:\n return \"The server received invalid JSON that could not be parsed\"\n case .invalidRequest:\n return \"The JSON sent is not a valid Request object\"\n case .methodNotFound:\n return \"The method does not exist or is not available\"\n case .invalidParams:\n return \"Invalid method parameter(s)\"\n case .internalError:\n return \"Internal JSON-RPC error\"\n case .serverError:\n return \"Server-defined error occurred\"\n case .connectionClosed:\n return \"The connection to the server was closed\"\n case .transportError(let error):\n return (error as? LocalizedError)?.failureReason ?? error.localizedDescription\n }\n }\n\n public var recoverySuggestion: String? {\n switch self {\n case .parseError:\n return \"Verify that the JSON being sent is valid and well-formed\"\n case .invalidRequest:\n return \"Ensure the request follows the JSON-RPC 2.0 specification format\"\n case .methodNotFound:\n return \"Check the method name and ensure it is supported by the server\"\n case .invalidParams:\n return \"Verify the parameters match the method's expected parameters\"\n case .connectionClosed:\n return \"Try reconnecting to the server\"\n default:\n return nil\n }\n }\n}\n\n// MARK: CustomDebugStringConvertible\n\nextension MCPError: CustomDebugStringConvertible {\n public var debugDescription: String {\n switch self {\n case .transportError(let error):\n return\n \"[\\(code)] \\(errorDescription ?? \"\") (Underlying error: \\(String(reflecting: error)))\"\n default:\n return \"[\\(code)] \\(errorDescription ?? \"\")\"\n }\n }\n\n}\n\n// MARK: Codable\n\nextension MCPError: Codable {\n private enum CodingKeys: String, CodingKey {\n case code, message, data\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(code, forKey: .code)\n try container.encode(errorDescription ?? \"Unknown error\", forKey: .message)\n\n // Encode additional data if available\n switch self {\n case .parseError(let detail),\n .invalidRequest(let detail),\n .methodNotFound(let detail),\n .invalidParams(let detail),\n .internalError(let detail):\n if let detail = detail {\n try container.encode([\"detail\": detail], forKey: .data)\n }\n case .serverError(_, _):\n // No additional data for server errors\n break\n case .connectionClosed:\n break\n case .transportError(let error):\n try container.encode(\n [\"error\": error.localizedDescription],\n forKey: .data\n )\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let code = try container.decode(Int.self, forKey: .code)\n let message = try container.decode(String.self, forKey: .message)\n let data = try container.decodeIfPresent([String: Value].self, forKey: .data)\n\n // Helper to extract detail from data, falling back to message if needed\n let unwrapDetail: (String?) -> String? = { fallback in\n guard let detailValue = data?[\"detail\"] else { return fallback }\n if case .string(let str) = detailValue { return str }\n return fallback\n }\n\n switch code {\n case -32700:\n self = .parseError(unwrapDetail(message))\n case -32600:\n self = .invalidRequest(unwrapDetail(message))\n case -32601:\n self = .methodNotFound(unwrapDetail(message))\n case -32602:\n self = .invalidParams(unwrapDetail(message))\n case -32603:\n self = .internalError(unwrapDetail(nil))\n case -32000:\n self = .connectionClosed\n case -32001:\n // Extract underlying error string if present\n let underlyingErrorString =\n data?[\"error\"].flatMap { val -> String? in\n if case .string(let str) = val { return str }\n return nil\n } ?? message\n self = .transportError(\n NSError(\n domain: \"org.jsonrpc.error\",\n code: code,\n userInfo: [NSLocalizedDescriptionKey: underlyingErrorString]\n )\n )\n default:\n self = .serverError(code: code, message: message)\n }\n }\n}\n\n// MARK: Equatable\n\nextension MCPError: Equatable {\n public static func == (lhs: MCPError, rhs: MCPError) -> Bool {\n lhs.code == rhs.code\n }\n}\n\n// MARK: Hashable\n\nextension MCPError: Hashable {\n public func hash(into hasher: inout Hasher) {\n hasher.combine(code)\n switch self {\n case .parseError(let detail):\n hasher.combine(detail)\n case .invalidRequest(let detail):\n hasher.combine(detail)\n case .methodNotFound(let detail):\n hasher.combine(detail)\n case .invalidParams(let detail):\n hasher.combine(detail)\n case .internalError(let detail):\n hasher.combine(detail)\n case .serverError(_, let message):\n hasher.combine(message)\n case .connectionClosed:\n break\n case .transportError(let error):\n hasher.combine(error.localizedDescription)\n }\n }\n}\n\n// MARK: -\n\n/// This is provided to allow existing code that uses `MCP.Error` to continue\n/// to work without modification.\n///\n/// The MCPError type is now the recommended way to handle errors in MCP.\n@available(*, deprecated, renamed: \"MCPError\", message: \"Use MCPError instead of MCP.Error\")\npublic typealias Error = MCPError\n"], ["/swift-sdk/Sources/MCP/Base/Messages.swift", "import class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\nprivate let jsonrpc = \"2.0\"\n\npublic protocol NotRequired {\n init()\n}\n\npublic struct Empty: NotRequired, Hashable, Codable, Sendable {\n public init() {}\n}\n\nextension Value: NotRequired {\n public init() {\n self = .null\n }\n}\n\n// MARK: -\n\n/// A method that can be used to send requests and receive responses.\npublic protocol Method {\n /// The parameters of the method.\n associatedtype Parameters: Codable, Hashable, Sendable = Empty\n /// The result of the method.\n associatedtype Result: Codable, Hashable, Sendable = Empty\n /// The name of the method.\n static var name: String { get }\n}\n\n/// Type-erased method for request/response handling\nstruct AnyMethod: Method, Sendable {\n static var name: String { \"\" }\n typealias Parameters = Value\n typealias Result = Value\n}\n\nextension Method where Parameters == Empty {\n public static func request(id: ID = .random) -> Request {\n Request(id: id, method: name, params: Empty())\n }\n}\n\nextension Method where Result == Empty {\n public static func response(id: ID) -> Response {\n Response(id: id, result: Empty())\n }\n}\n\nextension Method {\n /// Create a request with the given parameters.\n public static func request(id: ID = .random, _ parameters: Self.Parameters) -> Request {\n Request(id: id, method: name, params: parameters)\n }\n\n /// Create a response with the given result.\n public static func response(id: ID, result: Self.Result) -> Response {\n Response(id: id, result: result)\n }\n\n /// Create a response with the given error.\n public static func response(id: ID, error: MCPError) -> Response {\n Response(id: id, error: error)\n }\n}\n\n// MARK: -\n\n/// A request message.\npublic struct Request: Hashable, Identifiable, Codable, Sendable {\n /// The request ID.\n public let id: ID\n /// The method name.\n public let method: String\n /// The request parameters.\n public let params: M.Parameters\n\n init(id: ID = .random, method: String, params: M.Parameters) {\n self.id = id\n self.method = method\n self.params = params\n }\n\n private enum CodingKeys: String, CodingKey {\n case jsonrpc, id, method, params\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(jsonrpc, forKey: .jsonrpc)\n try container.encode(id, forKey: .id)\n try container.encode(method, forKey: .method)\n try container.encode(params, forKey: .params)\n }\n}\n\nextension Request {\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let version = try container.decode(String.self, forKey: .jsonrpc)\n guard version == jsonrpc else {\n throw DecodingError.dataCorruptedError(\n forKey: .jsonrpc, in: container, debugDescription: \"Invalid JSON-RPC version\")\n }\n id = try container.decode(ID.self, forKey: .id)\n method = try container.decode(String.self, forKey: .method)\n\n if M.Parameters.self is NotRequired.Type {\n // For NotRequired parameters, use decodeIfPresent or init()\n params =\n (try container.decodeIfPresent(M.Parameters.self, forKey: .params)\n ?? (M.Parameters.self as! NotRequired.Type).init() as! M.Parameters)\n } else if let value = try? container.decode(M.Parameters.self, forKey: .params) {\n // If params exists and can be decoded, use it\n params = value\n } else if !container.contains(.params)\n || (try? container.decodeNil(forKey: .params)) == true\n {\n // If params is missing or explicitly null, use Empty for Empty parameters\n // or throw for non-Empty parameters\n if M.Parameters.self == Empty.self {\n params = Empty() as! M.Parameters\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Missing required params field\"))\n }\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Invalid params field\"))\n }\n }\n}\n\n/// A type-erased request for request/response handling\ntypealias AnyRequest = Request\n\nextension AnyRequest {\n init(_ request: Request) throws {\n let encoder = JSONEncoder()\n let decoder = JSONDecoder()\n\n let data = try encoder.encode(request)\n self = try decoder.decode(AnyRequest.self, from: data)\n }\n}\n\n/// A box for request handlers that can be type-erased\nclass RequestHandlerBox: @unchecked Sendable {\n func callAsFunction(_ request: AnyRequest) async throws -> AnyResponse {\n fatalError(\"Must override\")\n }\n}\n\n/// A typed request handler that can be used to handle requests of a specific type\nfinal class TypedRequestHandler: RequestHandlerBox, @unchecked Sendable {\n private let _handle: @Sendable (Request) async throws -> Response\n\n init(_ handler: @escaping @Sendable (Request) async throws -> Response) {\n self._handle = handler\n super.init()\n }\n\n override func callAsFunction(_ request: AnyRequest) async throws -> AnyResponse {\n let encoder = JSONEncoder()\n let decoder = JSONDecoder()\n\n // Create a concrete request from the type-erased one\n let data = try encoder.encode(request)\n let request = try decoder.decode(Request.self, from: data)\n\n // Handle with concrete type\n let response = try await _handle(request)\n\n // Convert result to AnyMethod response\n switch response.result {\n case .success(let result):\n let resultData = try encoder.encode(result)\n let resultValue = try decoder.decode(Value.self, from: resultData)\n return Response(id: response.id, result: resultValue)\n case .failure(let error):\n return Response(id: response.id, error: error)\n }\n }\n}\n\n// MARK: -\n\n/// A response message.\npublic struct Response: Hashable, Identifiable, Codable, Sendable {\n /// The response ID.\n public let id: ID\n /// The response result.\n public let result: Swift.Result\n\n public init(id: ID, result: M.Result) {\n self.id = id\n self.result = .success(result)\n }\n\n public init(id: ID, error: MCPError) {\n self.id = id\n self.result = .failure(error)\n }\n\n private enum CodingKeys: String, CodingKey {\n case jsonrpc, id, result, error\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(jsonrpc, forKey: .jsonrpc)\n try container.encode(id, forKey: .id)\n switch result {\n case .success(let result):\n try container.encode(result, forKey: .result)\n case .failure(let error):\n try container.encode(error, forKey: .error)\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let version = try container.decode(String.self, forKey: .jsonrpc)\n guard version == jsonrpc else {\n throw DecodingError.dataCorruptedError(\n forKey: .jsonrpc, in: container, debugDescription: \"Invalid JSON-RPC version\")\n }\n id = try container.decode(ID.self, forKey: .id)\n if let result = try? container.decode(M.Result.self, forKey: .result) {\n self.result = .success(result)\n } else if let error = try? container.decode(MCPError.self, forKey: .error) {\n self.result = .failure(error)\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Invalid response\"))\n }\n }\n}\n\n/// A type-erased response for request/response handling\ntypealias AnyResponse = Response\n\nextension AnyResponse {\n init(_ response: Response) throws {\n // Instead of re-encoding/decoding which might double-wrap the error,\n // directly transfer the properties\n self.id = response.id\n switch response.result {\n case .success(let result):\n // For success, we still need to convert the result to a Value\n let data = try JSONEncoder().encode(result)\n let resultValue = try JSONDecoder().decode(Value.self, from: data)\n self.result = .success(resultValue)\n case .failure(let error):\n // Keep the original error without re-encoding/decoding\n self.result = .failure(error)\n }\n }\n}\n\n// MARK: -\n\n/// A notification message.\npublic protocol Notification: Hashable, Codable, Sendable {\n /// The parameters of the notification.\n associatedtype Parameters: Hashable, Codable, Sendable = Empty\n /// The name of the notification.\n static var name: String { get }\n}\n\n/// A type-erased notification for message handling\nstruct AnyNotification: Notification, Sendable {\n static var name: String { \"\" }\n typealias Parameters = Value\n}\n\nextension AnyNotification {\n init(_ notification: some Notification) throws {\n let encoder = JSONEncoder()\n let decoder = JSONDecoder()\n\n let data = try encoder.encode(notification)\n self = try decoder.decode(AnyNotification.self, from: data)\n }\n}\n\n/// A message that can be used to send notifications.\npublic struct Message: Hashable, Codable, Sendable {\n /// The method name.\n public let method: String\n /// The notification parameters.\n public let params: N.Parameters\n\n public init(method: String, params: N.Parameters) {\n self.method = method\n self.params = params\n }\n\n private enum CodingKeys: String, CodingKey {\n case jsonrpc, method, params\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(jsonrpc, forKey: .jsonrpc)\n try container.encode(method, forKey: .method)\n if N.Parameters.self != Empty.self {\n try container.encode(params, forKey: .params)\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let version = try container.decode(String.self, forKey: .jsonrpc)\n guard version == jsonrpc else {\n throw DecodingError.dataCorruptedError(\n forKey: .jsonrpc, in: container, debugDescription: \"Invalid JSON-RPC version\")\n }\n method = try container.decode(String.self, forKey: .method)\n\n if N.Parameters.self is NotRequired.Type {\n // For NotRequired parameters, use decodeIfPresent or init()\n params =\n (try container.decodeIfPresent(N.Parameters.self, forKey: .params)\n ?? (N.Parameters.self as! NotRequired.Type).init() as! N.Parameters)\n } else if let value = try? container.decode(N.Parameters.self, forKey: .params) {\n // If params exists and can be decoded, use it\n params = value\n } else if !container.contains(.params)\n || (try? container.decodeNil(forKey: .params)) == true\n {\n // If params is missing or explicitly null, use Empty for Empty parameters\n // or throw for non-Empty parameters\n if N.Parameters.self == Empty.self {\n params = Empty() as! N.Parameters\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Missing required params field\"))\n }\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Invalid params field\"))\n }\n }\n}\n\n/// A type-erased message for message handling\ntypealias AnyMessage = Message\n\nextension Notification where Parameters == Empty {\n /// Create a message with empty parameters.\n public static func message() -> Message {\n Message(method: name, params: Empty())\n }\n}\n\nextension Notification {\n /// Create a message with the given parameters.\n public static func message(_ parameters: Parameters) -> Message {\n Message(method: name, params: parameters)\n }\n}\n\n/// A box for notification handlers that can be type-erased\nclass NotificationHandlerBox: @unchecked Sendable {\n func callAsFunction(_ notification: Message) async throws {}\n}\n\n/// A typed notification handler that can be used to handle notifications of a specific type\nfinal class TypedNotificationHandler: NotificationHandlerBox,\n @unchecked Sendable\n{\n private let _handle: @Sendable (Message) async throws -> Void\n\n init(_ handler: @escaping @Sendable (Message) async throws -> Void) {\n self._handle = handler\n super.init()\n }\n\n override func callAsFunction(_ notification: Message) async throws {\n // Create a concrete notification from the type-erased one\n let data = try JSONEncoder().encode(notification)\n let typedNotification = try JSONDecoder().decode(Message.self, from: data)\n\n try await _handle(typedNotification)\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Value.swift", "import struct Foundation.Data\nimport class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\n/// A codable value.\npublic enum Value: Hashable, Sendable {\n case null\n case bool(Bool)\n case int(Int)\n case double(Double)\n case string(String)\n case data(mimeType: String? = nil, Data)\n case array([Value])\n case object([String: Value])\n\n /// Create a `Value` from a `Codable` value.\n /// - Parameter value: The codable value\n /// - Returns: A value\n public init(_ value: T) throws {\n if let valueAsValue = value as? Value {\n self = valueAsValue\n } else {\n let data = try JSONEncoder().encode(value)\n self = try JSONDecoder().decode(Value.self, from: data)\n }\n }\n\n /// Returns whether the value is `null`.\n public var isNull: Bool {\n return self == .null\n }\n\n /// Returns the `Bool` value if the value is a `bool`,\n /// otherwise returns `nil`.\n public var boolValue: Bool? {\n guard case let .bool(value) = self else { return nil }\n return value\n }\n\n /// Returns the `Int` value if the value is an `integer`,\n /// otherwise returns `nil`.\n public var intValue: Int? {\n guard case let .int(value) = self else { return nil }\n return value\n }\n\n /// Returns the `Double` value if the value is a `double`,\n /// otherwise returns `nil`.\n public var doubleValue: Double? {\n guard case let .double(value) = self else { return nil }\n return value\n }\n\n /// Returns the `String` value if the value is a `string`,\n /// otherwise returns `nil`.\n public var stringValue: String? {\n guard case let .string(value) = self else { return nil }\n return value\n }\n\n /// Returns the data value and optional MIME type if the value is `data`,\n /// otherwise returns `nil`.\n public var dataValue: (mimeType: String?, Data)? {\n guard case let .data(mimeType: mimeType, data) = self else { return nil }\n return (mimeType: mimeType, data)\n }\n\n /// Returns the `[Value]` value if the value is an `array`,\n /// otherwise returns `nil`.\n public var arrayValue: [Value]? {\n guard case let .array(value) = self else { return nil }\n return value\n }\n\n /// Returns the `[String: Value]` value if the value is an `object`,\n /// otherwise returns `nil`.\n public var objectValue: [String: Value]? {\n guard case let .object(value) = self else { return nil }\n return value\n }\n}\n\n// MARK: - Codable\n\nextension Value: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n\n if container.decodeNil() {\n self = .null\n } else if let value = try? container.decode(Bool.self) {\n self = .bool(value)\n } else if let value = try? container.decode(Int.self) {\n self = .int(value)\n } else if let value = try? container.decode(Double.self) {\n self = .double(value)\n } else if let value = try? container.decode(String.self) {\n if Data.isDataURL(string: value),\n case let (mimeType, data)? = Data.parseDataURL(value)\n {\n self = .data(mimeType: mimeType, data)\n } else {\n self = .string(value)\n }\n } else if let value = try? container.decode([Value].self) {\n self = .array(value)\n } else if let value = try? container.decode([String: Value].self) {\n self = .object(value)\n } else {\n throw DecodingError.dataCorruptedError(\n in: container, debugDescription: \"Value type not found\")\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n\n switch self {\n case .null:\n try container.encodeNil()\n case .bool(let value):\n try container.encode(value)\n case .int(let value):\n try container.encode(value)\n case .double(let value):\n try container.encode(value)\n case .string(let value):\n try container.encode(value)\n case let .data(mimeType, value):\n try container.encode(value.dataURLEncoded(mimeType: mimeType))\n case .array(let value):\n try container.encode(value)\n case .object(let value):\n try container.encode(value)\n }\n }\n}\n\nextension Value: CustomStringConvertible {\n public var description: String {\n switch self {\n case .null:\n return \"\"\n case .bool(let value):\n return value.description\n case .int(let value):\n return value.description\n case .double(let value):\n return value.description\n case .string(let value):\n return value.description\n case let .data(mimeType, value):\n return value.dataURLEncoded(mimeType: mimeType)\n case .array(let value):\n return value.description\n case .object(let value):\n return value.description\n }\n }\n}\n\n// MARK: - ExpressibleByNilLiteral\n\nextension Value: ExpressibleByNilLiteral {\n public init(nilLiteral: ()) {\n self = .null\n }\n}\n\n// MARK: - ExpressibleByBooleanLiteral\n\nextension Value: ExpressibleByBooleanLiteral {\n public init(booleanLiteral value: Bool) {\n self = .bool(value)\n }\n}\n\n// MARK: - ExpressibleByIntegerLiteral\n\nextension Value: ExpressibleByIntegerLiteral {\n public init(integerLiteral value: Int) {\n self = .int(value)\n }\n}\n\n// MARK: - ExpressibleByFloatLiteral\n\nextension Value: ExpressibleByFloatLiteral {\n public init(floatLiteral value: Double) {\n self = .double(value)\n }\n}\n\n// MARK: - ExpressibleByStringLiteral\n\nextension Value: ExpressibleByStringLiteral {\n public init(stringLiteral value: String) {\n self = .string(value)\n }\n}\n\n// MARK: - ExpressibleByArrayLiteral\n\nextension Value: ExpressibleByArrayLiteral {\n public init(arrayLiteral elements: Value...) {\n self = .array(elements)\n }\n}\n\n// MARK: - ExpressibleByDictionaryLiteral\n\nextension Value: ExpressibleByDictionaryLiteral {\n public init(dictionaryLiteral elements: (String, Value)...) {\n var dictionary: [String: Value] = [:]\n for (key, value) in elements {\n dictionary[key] = value\n }\n self = .object(dictionary)\n }\n}\n\n// MARK: - ExpressibleByStringInterpolation\n\nextension Value: ExpressibleByStringInterpolation {\n public struct StringInterpolation: StringInterpolationProtocol {\n var stringValue: String\n\n public init(literalCapacity: Int, interpolationCount: Int) {\n self.stringValue = \"\"\n self.stringValue.reserveCapacity(literalCapacity + interpolationCount)\n }\n\n public mutating func appendLiteral(_ literal: String) {\n self.stringValue.append(literal)\n }\n\n public mutating func appendInterpolation(_ value: T) {\n self.stringValue.append(value.description)\n }\n }\n\n public init(stringInterpolation: StringInterpolation) {\n self = .string(stringInterpolation.stringValue)\n }\n}\n\n// MARK: - Standard Library Type Extensions\n\nextension Bool {\n /// Creates a boolean value from a `Value` instance.\n ///\n /// In strict mode, only `.bool` values are converted. In non-strict mode, the following conversions are supported:\n /// - Integers: `1` is `true`, `0` is `false`\n /// - Doubles: `1.0` is `true`, `0.0` is `false`\n /// - Strings (lowercase only):\n /// - `true`: \"true\", \"t\", \"yes\", \"y\", \"on\", \"1\"\n /// - `false`: \"false\", \"f\", \"no\", \"n\", \"off\", \"0\"\n ///\n /// - Parameters:\n /// - value: The `Value` to convert\n /// - strict: When `true`, only converts from `.bool` values. Defaults to `true`\n /// - Returns: A boolean value if conversion is possible, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// Bool(Value.bool(true)) // Returns true\n /// Bool(Value.int(1), strict: false) // Returns true\n /// Bool(Value.string(\"yes\"), strict: false) // Returns true\n /// ```\n public init?(_ value: Value, strict: Bool = true) {\n switch value {\n case .bool(let b):\n self = b\n case .int(let i) where !strict:\n switch i {\n case 0: self = false\n case 1: self = true\n default: return nil\n }\n case .double(let d) where !strict:\n switch d {\n case 0.0: self = false\n case 1.0: self = true\n default: return nil\n }\n case .string(let s) where !strict:\n switch s {\n case \"true\", \"t\", \"yes\", \"y\", \"on\", \"1\":\n self = true\n case \"false\", \"f\", \"no\", \"n\", \"off\", \"0\":\n self = false\n default:\n return nil\n }\n default:\n return nil\n }\n }\n}\n\nextension Int {\n /// Creates an integer value from a `Value` instance.\n ///\n /// In strict mode, only `.int` values are converted. In non-strict mode, the following conversions are supported:\n /// - Doubles: Converted if they can be represented exactly as integers\n /// - Strings: Parsed if they contain a valid integer representation\n ///\n /// - Parameters:\n /// - value: The `Value` to convert\n /// - strict: When `true`, only converts from `.int` values. Defaults to `true`\n /// - Returns: An integer value if conversion is possible, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// Int(Value.int(42)) // Returns 42\n /// Int(Value.double(42.0), strict: false) // Returns 42\n /// Int(Value.string(\"42\"), strict: false) // Returns 42\n /// Int(Value.double(42.5), strict: false) // Returns nil\n /// ```\n public init?(_ value: Value, strict: Bool = true) {\n switch value {\n case .int(let i):\n self = i\n case .double(let d) where !strict:\n guard let intValue = Int(exactly: d) else { return nil }\n self = intValue\n case .string(let s) where !strict:\n guard let intValue = Int(s) else { return nil }\n self = intValue\n default:\n return nil\n }\n }\n}\n\nextension Double {\n /// Creates a double value from a `Value` instance.\n ///\n /// In strict mode, converts from `.double` and `.int` values. In non-strict mode, the following conversions are supported:\n /// - Integers: Converted to their double representation\n /// - Strings: Parsed if they contain a valid floating-point representation\n ///\n /// - Parameters:\n /// - value: The `Value` to convert\n /// - strict: When `true`, only converts from `.double` and `.int` values. Defaults to `true`\n /// - Returns: A double value if conversion is possible, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// Double(Value.double(42.5)) // Returns 42.5\n /// Double(Value.int(42)) // Returns 42.0\n /// Double(Value.string(\"42.5\"), strict: false) // Returns 42.5\n /// ```\n public init?(_ value: Value, strict: Bool = true) {\n switch value {\n case .double(let d):\n self = d\n case .int(let i):\n self = Double(i)\n case .string(let s) where !strict:\n guard let doubleValue = Double(s) else { return nil }\n self = doubleValue\n default:\n return nil\n }\n }\n}\n\nextension String {\n /// Creates a string value from a `Value` instance.\n ///\n /// In strict mode, only `.string` values are converted. In non-strict mode, the following conversions are supported:\n /// - Integers: Converted to their string representation\n /// - Doubles: Converted to their string representation\n /// - Booleans: Converted to \"true\" or \"false\"\n ///\n /// - Parameters:\n /// - value: The `Value` to convert\n /// - strict: When `true`, only converts from `.string` values. Defaults to `true`\n /// - Returns: A string value if conversion is possible, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// String(Value.string(\"hello\")) // Returns \"hello\"\n /// String(Value.int(42), strict: false) // Returns \"42\"\n /// String(Value.bool(true), strict: false) // Returns \"true\"\n /// ```\n public init?(_ value: Value, strict: Bool = true) {\n switch value {\n case .string(let s):\n self = s\n case .int(let i) where !strict:\n self = String(i)\n case .double(let d) where !strict:\n self = String(d)\n case .bool(let b) where !strict:\n self = String(b)\n default:\n return nil\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Extensions/Data+Extensions.swift", "import Foundation\nimport RegexBuilder\n\nextension Data {\n /// Regex pattern for data URLs\n @inline(__always) private static var dataURLRegex:\n Regex<(Substring, Substring, Substring?, Substring)>\n {\n Regex {\n \"data:\"\n Capture {\n ZeroOrMore(.reluctant) {\n CharacterClass.anyOf(\",;\").inverted\n }\n }\n Optionally {\n \";charset=\"\n Capture {\n OneOrMore(.reluctant) {\n CharacterClass.anyOf(\",;\").inverted\n }\n }\n }\n Optionally { \";base64\" }\n \",\"\n Capture {\n ZeroOrMore { .any }\n }\n }\n }\n\n /// Checks if a given string is a valid data URL.\n ///\n /// - Parameter string: The string to check.\n /// - Returns: `true` if the string is a valid data URL, otherwise `false`.\n /// - SeeAlso: [RFC 2397](https://www.rfc-editor.org/rfc/rfc2397.html)\n public static func isDataURL(string: String) -> Bool {\n return string.wholeMatch(of: dataURLRegex) != nil\n }\n\n /// Parses a data URL string into its MIME type and data components.\n ///\n /// - Parameter string: The data URL string to parse.\n /// - Returns: A tuple containing the MIME type and decoded data, or `nil` if parsing fails.\n /// - SeeAlso: [RFC 2397](https://www.rfc-editor.org/rfc/rfc2397.html)\n public static func parseDataURL(_ string: String) -> (mimeType: String, data: Data)? {\n guard let match = string.wholeMatch(of: dataURLRegex) else {\n return nil\n }\n\n // Extract components using strongly typed captures\n let (_, mediatype, charset, encodedData) = match.output\n\n let isBase64 = string.contains(\";base64,\")\n\n // Process MIME type\n var mimeType = mediatype.isEmpty ? \"text/plain\" : String(mediatype)\n if let charset = charset, !charset.isEmpty, mimeType.starts(with: \"text/\") {\n mimeType += \";charset=\\(charset)\"\n }\n\n // Decode data\n let decodedData: Data\n if isBase64 {\n guard let base64Data = Data(base64Encoded: String(encodedData)) else { return nil }\n decodedData = base64Data\n } else {\n guard\n let percentDecodedData = String(encodedData).removingPercentEncoding?.data(\n using: .utf8)\n else { return nil }\n decodedData = percentDecodedData\n }\n\n return (mimeType: mimeType, data: decodedData)\n }\n\n /// Encodes the data as a data URL string with an optional MIME type.\n ///\n /// - Parameter mimeType: The MIME type of the data. If `nil`, \"text/plain\" will be used.\n /// - Returns: A data URL string representation of the data.\n /// - SeeAlso: [RFC 2397](https://www.rfc-editor.org/rfc/rfc2397.html)\n public func dataURLEncoded(mimeType: String? = nil) -> String {\n let base64Data = self.base64EncodedString()\n return \"data:\\(mimeType ?? \"text/plain\");base64,\\(base64Data)\"\n }\n}\n"], ["/swift-sdk/Sources/MCP/Server/Tools.swift", "import Foundation\n\n/// The Model Context Protocol (MCP) allows servers to expose tools\n/// that can be invoked by language models.\n/// Tools enable models to interact with external systems, such as\n/// querying databases, calling APIs, or performing computations.\n/// Each tool is uniquely identified by a name and includes metadata\n/// describing its schema.\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/\npublic struct Tool: Hashable, Codable, Sendable {\n /// The tool name\n public let name: String\n /// The tool description\n public let description: String\n /// The tool input schema\n public let inputSchema: Value?\n\n /// Annotations that provide display-facing and operational information for a Tool.\n ///\n /// - Note: All properties in `ToolAnnotations` are **hints**.\n /// They are not guaranteed to provide a faithful description of\n /// tool behavior (including descriptive properties like `title`).\n ///\n /// Clients should never make tool use decisions based on `ToolAnnotations`\n /// received from untrusted servers.\n public struct Annotations: Hashable, Codable, Sendable, ExpressibleByNilLiteral {\n /// A human-readable title for the tool\n public var title: String?\n\n /// If true, the tool may perform destructive updates to its environment.\n /// If false, the tool performs only additive updates.\n /// (This property is meaningful only when `readOnlyHint == false`)\n ///\n /// When unspecified, the implicit default is `true`.\n public var destructiveHint: Bool?\n\n /// If true, calling the tool repeatedly with the same arguments\n /// will have no additional effect on its environment.\n /// (This property is meaningful only when `readOnlyHint == false`)\n ///\n /// When unspecified, the implicit default is `false`.\n public var idempotentHint: Bool?\n\n /// If true, this tool may interact with an \"open world\" of external\n /// entities. If false, the tool's domain of interaction is closed.\n /// For example, the world of a web search tool is open, whereas that\n /// of a memory tool is not.\n ///\n /// When unspecified, the implicit default is `true`.\n public var openWorldHint: Bool?\n\n /// If true, the tool does not modify its environment.\n ///\n /// When unspecified, the implicit default is `false`.\n public var readOnlyHint: Bool?\n\n /// Returns true if all properties are nil\n public var isEmpty: Bool {\n title == nil && readOnlyHint == nil && destructiveHint == nil && idempotentHint == nil\n && openWorldHint == nil\n }\n\n public init(\n title: String? = nil,\n readOnlyHint: Bool? = nil,\n destructiveHint: Bool? = nil,\n idempotentHint: Bool? = nil,\n openWorldHint: Bool? = nil\n ) {\n self.title = title\n self.readOnlyHint = readOnlyHint\n self.destructiveHint = destructiveHint\n self.idempotentHint = idempotentHint\n self.openWorldHint = openWorldHint\n }\n\n /// Initialize an empty annotations object\n public init(nilLiteral: ()) {}\n }\n\n /// Annotations that provide display-facing and operational information\n public var annotations: Annotations\n\n /// Initialize a tool with a name, description, input schema, and annotations\n public init(\n name: String,\n description: String,\n inputSchema: Value? = nil,\n annotations: Annotations = nil\n ) {\n self.name = name\n self.description = description\n self.inputSchema = inputSchema\n self.annotations = annotations\n }\n\n /// Content types that can be returned by a tool\n public enum Content: Hashable, Codable, Sendable {\n /// Text content\n case text(String)\n /// Image content\n case image(data: String, mimeType: String, metadata: [String: String]?)\n /// Audio content\n case audio(data: String, mimeType: String)\n /// Embedded resource content\n case resource(uri: String, mimeType: String, text: String?)\n\n private enum CodingKeys: String, CodingKey {\n case type\n case text\n case image\n case resource\n case audio\n case uri\n case mimeType\n case data\n case metadata\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let type = try container.decode(String.self, forKey: .type)\n\n switch type {\n case \"text\":\n let text = try container.decode(String.self, forKey: .text)\n self = .text(text)\n case \"image\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n let metadata = try container.decodeIfPresent(\n [String: String].self, forKey: .metadata)\n self = .image(data: data, mimeType: mimeType, metadata: metadata)\n case \"audio\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n self = .audio(data: data, mimeType: mimeType)\n case \"resource\":\n let uri = try container.decode(String.self, forKey: .uri)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n let text = try container.decodeIfPresent(String.self, forKey: .text)\n self = .resource(uri: uri, mimeType: mimeType, text: text)\n default:\n throw DecodingError.dataCorruptedError(\n forKey: .type, in: container, debugDescription: \"Unknown tool content type\")\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n\n switch self {\n case .text(let text):\n try container.encode(\"text\", forKey: .type)\n try container.encode(text, forKey: .text)\n case .image(let data, let mimeType, let metadata):\n try container.encode(\"image\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n try container.encodeIfPresent(metadata, forKey: .metadata)\n case .audio(let data, let mimeType):\n try container.encode(\"audio\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n case .resource(let uri, let mimeType, let text):\n try container.encode(\"resource\", forKey: .type)\n try container.encode(uri, forKey: .uri)\n try container.encode(mimeType, forKey: .mimeType)\n try container.encodeIfPresent(text, forKey: .text)\n }\n }\n }\n\n private enum CodingKeys: String, CodingKey {\n case name\n case description\n case inputSchema\n case annotations\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n name = try container.decode(String.self, forKey: .name)\n description = try container.decode(String.self, forKey: .description)\n inputSchema = try container.decodeIfPresent(Value.self, forKey: .inputSchema)\n annotations =\n try container.decodeIfPresent(Tool.Annotations.self, forKey: .annotations) ?? .init()\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(name, forKey: .name)\n try container.encode(description, forKey: .description)\n if let schema = inputSchema {\n try container.encode(schema, forKey: .inputSchema)\n }\n if !annotations.isEmpty {\n try container.encode(annotations, forKey: .annotations)\n }\n }\n}\n\n// MARK: -\n\n/// To discover available tools, clients send a `tools/list` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/#listing-tools\npublic enum ListTools: Method {\n public static let name = \"tools/list\"\n\n public struct Parameters: NotRequired, Hashable, Codable, Sendable {\n public let cursor: String?\n\n public init() {\n self.cursor = nil\n }\n\n public init(cursor: String) {\n self.cursor = cursor\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let tools: [Tool]\n public let nextCursor: String?\n\n public init(tools: [Tool], nextCursor: String? = nil) {\n self.tools = tools\n self.nextCursor = nextCursor\n }\n }\n}\n\n/// To call a tool, clients send a `tools/call` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/#calling-tools\npublic enum CallTool: Method {\n public static let name = \"tools/call\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let name: String\n public let arguments: [String: Value]?\n\n public init(name: String, arguments: [String: Value]? = nil) {\n self.name = name\n self.arguments = arguments\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let content: [Tool.Content]\n public let isError: Bool?\n\n public init(content: [Tool.Content], isError: Bool? = nil) {\n self.content = content\n self.isError = isError\n }\n }\n}\n\n/// When the list of available tools changes, servers that declared the listChanged capability SHOULD send a notification:\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/#list-changed-notification\npublic struct ToolListChangedNotification: Notification {\n public static let name: String = \"notifications/tools/list_changed\"\n}\n"], ["/swift-sdk/Sources/MCP/Base/UnitInterval.swift", "/// A value constrained to the range 0.0 to 1.0, inclusive.\n///\n/// `UnitInterval` represents a normalized value that is guaranteed to be within\n/// the unit interval [0, 1]. This type is commonly used for representing\n/// priorities in sampling request model preferences.\n///\n/// The type provides safe initialization that returns `nil` for values outside\n/// the valid range, ensuring that all instances contain valid unit interval values.\n///\n/// - Example:\n/// ```swift\n/// let zero: UnitInterval = 0 // 0.0\n/// let half = UnitInterval(0.5)! // 0.5\n/// let one: UnitInterval = 1.0 // 1.0\n/// let invalid = UnitInterval(1.5) // nil\n/// ```\npublic struct UnitInterval: Hashable, Sendable {\n private let value: Double\n\n /// Creates a unit interval value from a `Double`.\n ///\n /// - Parameter value: A double value that must be in the range 0.0...1.0\n /// - Returns: A `UnitInterval` instance if the value is valid, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// let valid = UnitInterval(0.75) // Optional(0.75)\n /// let invalid = UnitInterval(-0.1) // nil\n /// let boundary = UnitInterval(1.0) // Optional(1.0)\n /// ```\n public init?(_ value: Double) {\n guard (0...1).contains(value) else { return nil }\n self.value = value\n }\n\n /// The underlying double value.\n ///\n /// This property provides access to the raw double value that is guaranteed\n /// to be within the range [0, 1].\n ///\n /// - Returns: The double value between 0.0 and 1.0, inclusive\n public var doubleValue: Double { value }\n}\n\n// MARK: - Comparable\n\nextension UnitInterval: Comparable {\n public static func < (lhs: UnitInterval, rhs: UnitInterval) -> Bool {\n lhs.value < rhs.value\n }\n}\n\n// MARK: - CustomStringConvertible\n\nextension UnitInterval: CustomStringConvertible {\n public var description: String { \"\\(value)\" }\n}\n\n// MARK: - Codable\n\nextension UnitInterval: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let doubleValue = try container.decode(Double.self)\n guard let interval = UnitInterval(doubleValue) else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: decoder.codingPath,\n debugDescription: \"Value \\(doubleValue) is not in range 0...1\")\n )\n }\n self = interval\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n try container.encode(value)\n }\n}\n\n// MARK: - ExpressibleByFloatLiteral\n\nextension UnitInterval: ExpressibleByFloatLiteral {\n /// Creates a unit interval from a floating-point literal.\n ///\n /// This initializer allows you to create `UnitInterval` instances using\n /// floating-point literals. The literal value must be in the range [0, 1]\n /// or a runtime error will occur.\n ///\n /// - Parameter value: A floating-point literal between 0.0 and 1.0\n ///\n /// - Warning: This initializer will crash if the literal is outside the valid range.\n /// Use the failable initializer `init(_:)` for runtime validation.\n ///\n /// - Example:\n /// ```swift\n /// let quarter: UnitInterval = 0.25\n /// let half: UnitInterval = 0.5\n /// ```\n public init(floatLiteral value: Double) {\n self.init(value)!\n }\n}\n\n// MARK: - ExpressibleByIntegerLiteral\n\nextension UnitInterval: ExpressibleByIntegerLiteral {\n /// Creates a unit interval from an integer literal.\n ///\n /// This initializer allows you to create `UnitInterval` instances using\n /// integer literals. Only the values 0 and 1 are valid.\n ///\n /// - Parameter value: An integer literal, either 0 or 1\n ///\n /// - Warning: This initializer will crash if the literal is outside the valid range.\n /// Use the failable initializer `init(_:)` for runtime validation.\n ///\n /// - Example:\n /// ```swift\n /// let zero: UnitInterval = 0\n /// let one: UnitInterval = 1\n /// ```\n public init(integerLiteral value: Int) {\n self.init(Double(value))!\n }\n}\n"], ["/swift-sdk/Sources/MCP/Client/Sampling.swift", "import Foundation\n\n/// The Model Context Protocol (MCP) allows servers to request LLM completions\n/// through the client, enabling sophisticated agentic behaviors while maintaining\n/// security and privacy.\n///\n/// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/sampling#how-sampling-works\npublic enum Sampling {\n /// A message in the conversation history.\n public struct Message: Hashable, Codable, Sendable {\n /// The message role\n public enum Role: String, Hashable, Codable, Sendable {\n /// A user message\n case user\n /// An assistant message\n case assistant\n }\n\n /// The message role\n public let role: Role\n /// The message content\n public let content: Content\n\n /// Creates a message with the specified role and content\n @available(\n *, deprecated, message: \"Use static factory methods .user(_:) or .assistant(_:) instead\"\n )\n public init(role: Role, content: Content) {\n self.role = role\n self.content = content\n }\n\n /// Private initializer for convenience methods to avoid deprecation warnings\n private init(_role role: Role, _content content: Content) {\n self.role = role\n self.content = content\n }\n\n /// Creates a user message with the specified content\n public static func user(_ content: Content) -> Message {\n return Message(_role: .user, _content: content)\n }\n\n /// Creates an assistant message with the specified content\n public static func assistant(_ content: Content) -> Message {\n return Message(_role: .assistant, _content: content)\n }\n\n /// Content types for sampling messages\n public enum Content: Hashable, Sendable {\n /// Text content\n case text(String)\n /// Image content\n case image(data: String, mimeType: String)\n }\n }\n\n /// Model preferences for sampling requests\n public struct ModelPreferences: Hashable, Codable, Sendable {\n /// Model hints for selection\n public struct Hint: Hashable, Codable, Sendable {\n /// Suggested model name/family\n public let name: String?\n\n public init(name: String? = nil) {\n self.name = name\n }\n }\n\n /// Array of model name suggestions that clients can use to select an appropriate model\n public let hints: [Hint]?\n /// Importance of minimizing costs (0-1 normalized)\n public let costPriority: UnitInterval?\n /// Importance of low latency response (0-1 normalized)\n public let speedPriority: UnitInterval?\n /// Importance of advanced model capabilities (0-1 normalized)\n public let intelligencePriority: UnitInterval?\n\n public init(\n hints: [Hint]? = nil,\n costPriority: UnitInterval? = nil,\n speedPriority: UnitInterval? = nil,\n intelligencePriority: UnitInterval? = nil\n ) {\n self.hints = hints\n self.costPriority = costPriority\n self.speedPriority = speedPriority\n self.intelligencePriority = intelligencePriority\n }\n }\n\n /// Context inclusion options for sampling requests\n public enum ContextInclusion: String, Hashable, Codable, Sendable {\n /// No additional context\n case none\n /// Include context from the requesting server\n case thisServer\n /// Include context from all connected MCP servers\n case allServers\n }\n\n /// Stop reason for sampling completion\n public enum StopReason: String, Hashable, Codable, Sendable {\n /// Natural end of turn\n case endTurn\n /// Hit a stop sequence\n case stopSequence\n /// Reached maximum tokens\n case maxTokens\n }\n}\n\n// MARK: - Codable\n\nextension Sampling.Message.Content: Codable {\n private enum CodingKeys: String, CodingKey {\n case type, text, data, mimeType\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let type = try container.decode(String.self, forKey: .type)\n\n switch type {\n case \"text\":\n let text = try container.decode(String.self, forKey: .text)\n self = .text(text)\n case \"image\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n self = .image(data: data, mimeType: mimeType)\n default:\n throw DecodingError.dataCorruptedError(\n forKey: .type, in: container,\n debugDescription: \"Unknown sampling message content type\")\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n\n switch self {\n case .text(let text):\n try container.encode(\"text\", forKey: .type)\n try container.encode(text, forKey: .text)\n case .image(let data, let mimeType):\n try container.encode(\"image\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n }\n }\n}\n\n// MARK: - ExpressibleByStringLiteral\n\nextension Sampling.Message.Content: ExpressibleByStringLiteral {\n public init(stringLiteral value: String) {\n self = .text(value)\n }\n}\n\n// MARK: - ExpressibleByStringInterpolation\n\nextension Sampling.Message.Content: ExpressibleByStringInterpolation {\n public init(stringInterpolation: DefaultStringInterpolation) {\n self = .text(String(stringInterpolation: stringInterpolation))\n }\n}\n\n// MARK: -\n\n/// To request sampling from a client, servers send a `sampling/createMessage` request.\n/// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/sampling#how-sampling-works\npublic enum CreateSamplingMessage: Method {\n public static let name = \"sampling/createMessage\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n /// The conversation history to send to the LLM\n public let messages: [Sampling.Message]\n /// Model selection preferences\n public let modelPreferences: Sampling.ModelPreferences?\n /// Optional system prompt\n public let systemPrompt: String?\n /// What MCP context to include\n public let includeContext: Sampling.ContextInclusion?\n /// Controls randomness (0.0 to 1.0)\n public let temperature: Double?\n /// Maximum tokens to generate\n public let maxTokens: Int\n /// Array of sequences that stop generation\n public let stopSequences: [String]?\n /// Additional provider-specific parameters\n public let metadata: [String: Value]?\n\n public init(\n messages: [Sampling.Message],\n modelPreferences: Sampling.ModelPreferences? = nil,\n systemPrompt: String? = nil,\n includeContext: Sampling.ContextInclusion? = nil,\n temperature: Double? = nil,\n maxTokens: Int,\n stopSequences: [String]? = nil,\n metadata: [String: Value]? = nil\n ) {\n self.messages = messages\n self.modelPreferences = modelPreferences\n self.systemPrompt = systemPrompt\n self.includeContext = includeContext\n self.temperature = temperature\n self.maxTokens = maxTokens\n self.stopSequences = stopSequences\n self.metadata = metadata\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n /// Name of the model used\n public let model: String\n /// Why sampling stopped\n public let stopReason: Sampling.StopReason?\n /// The role of the completion\n public let role: Sampling.Message.Role\n /// The completion content\n public let content: Sampling.Message.Content\n\n public init(\n model: String,\n stopReason: Sampling.StopReason? = nil,\n role: Sampling.Message.Role,\n content: Sampling.Message.Content\n ) {\n self.model = model\n self.stopReason = stopReason\n self.role = role\n self.content = content\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Server/Prompts.swift", "import Foundation\n\n/// The Model Context Protocol (MCP) provides a standardized way\n/// for servers to expose prompt templates to clients.\n/// Prompts allow servers to provide structured messages and instructions\n/// for interacting with language models.\n/// Clients can discover available prompts, retrieve their contents,\n/// and provide arguments to customize them.\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/\npublic struct Prompt: Hashable, Codable, Sendable {\n /// The prompt name\n public let name: String\n /// The prompt description\n public let description: String?\n /// The prompt arguments\n public let arguments: [Argument]?\n\n public init(name: String, description: String? = nil, arguments: [Argument]? = nil) {\n self.name = name\n self.description = description\n self.arguments = arguments\n }\n\n /// An argument for a prompt\n public struct Argument: Hashable, Codable, Sendable {\n /// The argument name\n public let name: String\n /// The argument description\n public let description: String?\n /// Whether the argument is required\n public let required: Bool?\n\n public init(name: String, description: String? = nil, required: Bool? = nil) {\n self.name = name\n self.description = description\n self.required = required\n }\n }\n\n /// A message in a prompt\n public struct Message: Hashable, Codable, Sendable {\n /// The message role\n public enum Role: String, Hashable, Codable, Sendable {\n /// A user message\n case user\n /// An assistant message\n case assistant\n }\n\n /// The message role\n public let role: Role\n /// The message content\n public let content: Content\n\n /// Creates a message with the specified role and content\n @available(\n *, deprecated, message: \"Use static factory methods .user(_:) or .assistant(_:) instead\"\n )\n public init(role: Role, content: Content) {\n self.role = role\n self.content = content\n }\n\n /// Private initializer for convenience methods to avoid deprecation warnings\n private init(_role role: Role, _content content: Content) {\n self.role = role\n self.content = content\n }\n\n /// Creates a user message with the specified content\n public static func user(_ content: Content) -> Message {\n return Message(_role: .user, _content: content)\n }\n\n /// Creates an assistant message with the specified content\n public static func assistant(_ content: Content) -> Message {\n return Message(_role: .assistant, _content: content)\n }\n\n /// Content types for messages\n public enum Content: Hashable, Sendable {\n /// Text content\n case text(text: String)\n /// Image content\n case image(data: String, mimeType: String)\n /// Audio content\n case audio(data: String, mimeType: String)\n /// Embedded resource content\n case resource(uri: String, mimeType: String, text: String?, blob: String?)\n }\n }\n\n /// Reference type for prompts\n public struct Reference: Hashable, Codable, Sendable {\n /// The prompt reference name\n public let name: String\n\n public init(name: String) {\n self.name = name\n }\n\n private enum CodingKeys: String, CodingKey {\n case type, name\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(\"ref/prompt\", forKey: .type)\n try container.encode(name, forKey: .name)\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n _ = try container.decode(String.self, forKey: .type)\n name = try container.decode(String.self, forKey: .name)\n }\n }\n}\n\n// MARK: - Codable\n\nextension Prompt.Message.Content: Codable {\n private enum CodingKeys: String, CodingKey {\n case type, text, data, mimeType, uri, blob\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n\n switch self {\n case .text(let text):\n try container.encode(\"text\", forKey: .type)\n try container.encode(text, forKey: .text)\n case .image(let data, let mimeType):\n try container.encode(\"image\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n case .audio(let data, let mimeType):\n try container.encode(\"audio\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n case .resource(let uri, let mimeType, let text, let blob):\n try container.encode(\"resource\", forKey: .type)\n try container.encode(uri, forKey: .uri)\n try container.encode(mimeType, forKey: .mimeType)\n try container.encodeIfPresent(text, forKey: .text)\n try container.encodeIfPresent(blob, forKey: .blob)\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let type = try container.decode(String.self, forKey: .type)\n\n switch type {\n case \"text\":\n let text = try container.decode(String.self, forKey: .text)\n self = .text(text: text)\n case \"image\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n self = .image(data: data, mimeType: mimeType)\n case \"audio\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n self = .audio(data: data, mimeType: mimeType)\n case \"resource\":\n let uri = try container.decode(String.self, forKey: .uri)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n let text = try container.decodeIfPresent(String.self, forKey: .text)\n let blob = try container.decodeIfPresent(String.self, forKey: .blob)\n self = .resource(uri: uri, mimeType: mimeType, text: text, blob: blob)\n default:\n throw DecodingError.dataCorruptedError(\n forKey: .type,\n in: container,\n debugDescription: \"Unknown content type\")\n }\n }\n}\n\n// MARK: - ExpressibleByStringLiteral\n\nextension Prompt.Message.Content: ExpressibleByStringLiteral {\n public init(stringLiteral value: String) {\n self = .text(text: value)\n }\n}\n\n// MARK: - ExpressibleByStringInterpolation\n\nextension Prompt.Message.Content: ExpressibleByStringInterpolation {\n public init(stringInterpolation: DefaultStringInterpolation) {\n self = .text(text: String(stringInterpolation: stringInterpolation))\n }\n}\n\n// MARK: -\n\n/// To retrieve available prompts, clients send a `prompts/list` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/#listing-prompts\npublic enum ListPrompts: Method {\n public static let name: String = \"prompts/list\"\n\n public struct Parameters: NotRequired, Hashable, Codable, Sendable {\n public let cursor: String?\n\n public init() {\n self.cursor = nil\n }\n\n public init(cursor: String) {\n self.cursor = cursor\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let prompts: [Prompt]\n public let nextCursor: String?\n\n public init(prompts: [Prompt], nextCursor: String? = nil) {\n self.prompts = prompts\n self.nextCursor = nextCursor\n }\n }\n}\n\n/// To retrieve a specific prompt, clients send a `prompts/get` request.\n/// Arguments may be auto-completed through the completion API.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/#getting-a-prompt\npublic enum GetPrompt: Method {\n public static let name: String = \"prompts/get\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let name: String\n public let arguments: [String: Value]?\n\n public init(name: String, arguments: [String: Value]? = nil) {\n self.name = name\n self.arguments = arguments\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let description: String?\n public let messages: [Prompt.Message]\n\n public init(description: String?, messages: [Prompt.Message]) {\n self.description = description\n self.messages = messages\n }\n }\n}\n\n/// When the list of available prompts changes, servers that declared the listChanged capability SHOULD send a notification.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/#list-changed-notification\npublic struct PromptListChangedNotification: Notification {\n public static let name: String = \"notifications/prompts/list_changed\"\n}\n"], ["/swift-sdk/Sources/MCP/Base/Transport.swift", "import Logging\n\nimport struct Foundation.Data\n\n/// Protocol defining the transport layer for MCP communication\npublic protocol Transport: Actor {\n var logger: Logger { get }\n\n /// Establishes connection with the transport\n func connect() async throws\n\n /// Disconnects from the transport\n func disconnect() async\n\n /// Sends data\n func send(_ data: Data) async throws\n\n /// Receives data in an async sequence\n func receive() -> AsyncThrowingStream\n}\n"], ["/swift-sdk/Sources/MCP/Server/Resources.swift", "import Foundation\n\n/// The Model Context Protocol (MCP) provides a standardized way\n/// for servers to expose resources to clients.\n/// Resources allow servers to share data that provides context to language models,\n/// such as files, database schemas, or application-specific information.\n/// Each resource is uniquely identified by a URI.\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/\npublic struct Resource: Hashable, Codable, Sendable {\n /// The resource name\n public var name: String\n /// The resource URI\n public var uri: String\n /// The resource description\n public var description: String?\n /// The resource MIME type\n public var mimeType: String?\n /// The resource metadata\n public var metadata: [String: String]?\n\n public init(\n name: String,\n uri: String,\n description: String? = nil,\n mimeType: String? = nil,\n metadata: [String: String]? = nil\n ) {\n self.name = name\n self.uri = uri\n self.description = description\n self.mimeType = mimeType\n self.metadata = metadata\n }\n\n /// Content of a resource.\n public struct Content: Hashable, Codable, Sendable {\n /// The resource URI\n public let uri: String\n /// The resource MIME type\n public let mimeType: String?\n /// The resource text content\n public let text: String?\n /// The resource binary content\n public let blob: String?\n\n public static func text(_ content: String, uri: String, mimeType: String? = nil) -> Self {\n .init(uri: uri, mimeType: mimeType, text: content)\n }\n\n public static func binary(_ data: Data, uri: String, mimeType: String? = nil) -> Self {\n .init(uri: uri, mimeType: mimeType, blob: data.base64EncodedString())\n }\n\n private init(uri: String, mimeType: String? = nil, text: String? = nil) {\n self.uri = uri\n self.mimeType = mimeType\n self.text = text\n self.blob = nil\n }\n\n private init(uri: String, mimeType: String? = nil, blob: String) {\n self.uri = uri\n self.mimeType = mimeType\n self.text = nil\n self.blob = blob\n }\n }\n\n /// A resource template.\n public struct Template: Hashable, Codable, Sendable {\n /// The URI template pattern\n public var uriTemplate: String\n /// The template name\n public var name: String\n /// The template description\n public var description: String?\n /// The resource MIME type\n public var mimeType: String?\n\n public init(\n uriTemplate: String,\n name: String,\n description: String? = nil,\n mimeType: String? = nil\n ) {\n self.uriTemplate = uriTemplate\n self.name = name\n self.description = description\n self.mimeType = mimeType\n }\n }\n}\n\n// MARK: -\n\n/// To discover available resources, clients send a `resources/list` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#listing-resources\npublic enum ListResources: Method {\n public static let name: String = \"resources/list\"\n\n public struct Parameters: NotRequired, Hashable, Codable, Sendable {\n public let cursor: String?\n\n public init() {\n self.cursor = nil\n }\n \n public init(cursor: String) {\n self.cursor = cursor\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let resources: [Resource]\n public let nextCursor: String?\n\n public init(resources: [Resource], nextCursor: String? = nil) {\n self.resources = resources\n self.nextCursor = nextCursor\n }\n }\n}\n\n/// To retrieve resource contents, clients send a `resources/read` request:\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#reading-resources\npublic enum ReadResource: Method {\n public static let name: String = \"resources/read\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let uri: String\n\n public init(uri: String) {\n self.uri = uri\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let contents: [Resource.Content]\n\n public init(contents: [Resource.Content]) {\n self.contents = contents\n }\n }\n}\n\n/// To discover available resource templates, clients send a `resources/templates/list` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#resource-templates\npublic enum ListResourceTemplates: Method {\n public static let name: String = \"resources/templates/list\"\n\n public struct Parameters: NotRequired, Hashable, Codable, Sendable {\n public let cursor: String?\n\n public init() {\n self.cursor = nil\n }\n \n public init(cursor: String) {\n self.cursor = cursor\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let templates: [Resource.Template]\n public let nextCursor: String?\n\n public init(templates: [Resource.Template], nextCursor: String? = nil) {\n self.templates = templates\n self.nextCursor = nextCursor\n }\n\n private enum CodingKeys: String, CodingKey {\n case templates = \"resourceTemplates\"\n case nextCursor\n }\n }\n}\n\n/// When the list of available resources changes, servers that declared the listChanged capability SHOULD send a notification.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#list-changed-notification\npublic struct ResourceListChangedNotification: Notification {\n public static let name: String = \"notifications/resources/list_changed\"\n\n public typealias Parameters = Empty\n}\n\n/// Clients can subscribe to specific resources and receive notifications when they change.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#subscriptions\npublic enum ResourceSubscribe: Method {\n public static let name: String = \"resources/subscribe\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let uri: String\n }\n\n public typealias Result = Empty\n}\n\n/// When a resource changes, servers that declared the updated capability SHOULD send a notification to subscribed clients.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#subscriptions\npublic struct ResourceUpdatedNotification: Notification {\n public static let name: String = \"notifications/resources/updated\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let uri: String\n\n public init(uri: String) {\n self.uri = uri\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Lifecycle.swift", "/// The initialization phase MUST be the first interaction between client and server.\n/// During this phase, the client and server:\n/// - Establish protocol version compatibility\n/// - Exchange and negotiate capabilities\n/// - Share implementation details\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle/#initialization\npublic enum Initialize: Method {\n public static let name: String = \"initialize\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let protocolVersion: String\n public let capabilities: Client.Capabilities\n public let clientInfo: Client.Info\n\n public init(\n protocolVersion: String = Version.latest,\n capabilities: Client.Capabilities,\n clientInfo: Client.Info\n ) {\n self.protocolVersion = protocolVersion\n self.capabilities = capabilities\n self.clientInfo = clientInfo\n }\n\n private enum CodingKeys: String, CodingKey {\n case protocolVersion, capabilities, clientInfo\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n protocolVersion =\n try container.decodeIfPresent(String.self, forKey: .protocolVersion)\n ?? Version.latest\n capabilities =\n try container.decodeIfPresent(Client.Capabilities.self, forKey: .capabilities)\n ?? .init()\n clientInfo =\n try container.decodeIfPresent(Client.Info.self, forKey: .clientInfo)\n ?? .init(name: \"unknown\", version: \"0.0.0\")\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let protocolVersion: String\n public let capabilities: Server.Capabilities\n public let serverInfo: Server.Info\n public let instructions: String?\n }\n}\n\n/// After successful initialization, the client MUST send an initialized notification to indicate it is ready to begin normal operations.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle/#initialization\npublic struct InitializedNotification: Notification {\n public static let name: String = \"notifications/initialized\"\n}\n"], ["/swift-sdk/Sources/MCP/Base/ID.swift", "import struct Foundation.UUID\n\n/// A unique identifier for a request.\npublic enum ID: Hashable, Sendable {\n /// A string ID.\n case string(String)\n\n /// A number ID.\n case number(Int)\n\n /// Generates a random string ID.\n public static var random: ID {\n return .string(UUID().uuidString)\n }\n}\n\n// MARK: - ExpressibleByStringLiteral\n\nextension ID: ExpressibleByStringLiteral {\n public init(stringLiteral value: String) {\n self = .string(value)\n }\n}\n\n// MARK: - ExpressibleByIntegerLiteral\n\nextension ID: ExpressibleByIntegerLiteral {\n public init(integerLiteral value: Int) {\n self = .number(value)\n }\n}\n\n// MARK: - CustomStringConvertible\n\nextension ID: CustomStringConvertible {\n public var description: String {\n switch self {\n case .string(let str): return str\n case .number(let num): return String(num)\n }\n }\n}\n\n// MARK: - Codable\n\nextension ID: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n if let string = try? container.decode(String.self) {\n self = .string(string)\n } else if let number = try? container.decode(Int.self) {\n self = .number(number)\n } else if container.decodeNil() {\n // Handle unspecified/null IDs as empty string\n self = .string(\"\")\n } else {\n throw DecodingError.dataCorruptedError(\n in: container, debugDescription: \"ID must be string or number\")\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n switch self {\n case .string(let str): try container.encode(str)\n case .number(let num): try container.encode(num)\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Versioning.swift", "import Foundation\n\n/// The Model Context Protocol uses string-based version identifiers\n/// following the format YYYY-MM-DD, to indicate\n/// the last date backwards incompatible changes were made.\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2025-03-26/\npublic enum Version {\n /// All protocol versions supported by this implementation, ordered from newest to oldest.\n static let supported: Set = [\n \"2025-03-26\",\n \"2024-11-05\",\n ]\n\n /// The latest protocol version supported by this implementation.\n public static let latest = supported.max()!\n\n /// Negotiates the protocol version based on the client's request and server's capabilities.\n /// - Parameter clientRequestedVersion: The protocol version requested by the client.\n /// - Returns: The negotiated protocol version. If the client's requested version is supported,\n /// that version is returned. Otherwise, the server's latest supported version is returned.\n static func negotiate(clientRequestedVersion: String) -> String {\n if supported.contains(clientRequestedVersion) {\n return clientRequestedVersion\n }\n return latest\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Utilities/Ping.swift", "/// The Model Context Protocol includes an optional ping mechanism that allows either party to verify that their counterpart is still responsive and the connection is alive.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/utilities/ping\npublic enum Ping: Method {\n public static let name: String = \"ping\"\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 03:25:14", "created_task_model": "DeepSeek-R1", "function_skeleton": "private func readLoop ( ) async { }", "code_description": "This code segment functions to: Continuously read and buffer input data streams while detecting message boundaries using newline characters, then extract complete messages and propagate them through an asynchronous data pipeline while handling partial reads and temporary resource constraints."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```swift\n[TASK_BEGIN]\n private func readLoop() async {\n var buffer = Data()\n let chunkSize = 4096\n \n while isConnected {\n do {\n var chunk = Data(count: chunkSize)\n let bytesRead = try chunk.withUnsafeMutableBytes { ptr in\n try input.read(into: UnsafeMutableRawBufferPointer(ptr))\n }\n \n guard bytesRead > 0 else {\n // EOF reached, disconnect gracefully\n await disconnect()\n return\n }\n \n buffer.append(chunk.prefix(bytesRead))\n \n // Process complete messages\n while let newlineIndex = buffer.firstIndex(of: UInt8(ascii: \"\\n\")) {\n let message = buffer.prefix(upTo: newlineIndex)\n buffer.removeSubrange(...newlineIndex)\n messageContinuation.yield(message)\n }\n } catch let error as Errno where error == .resourceTemporarilyUnavailable {\n // Wait before retrying non-blocking read\n try? await Task.sleep(for: .milliseconds(10))\n continue\n } catch {\n messageContinuation.finish(throwing: error)\n return\n }\n }\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 03-26-11"}, "editdistance_info": {"edit_distance": 44.1281, "calculate_time": "2025-08-21 03:26:11", "true_code_clean": "private func readLoop() async {\n let bufferSize = 4096\n var buffer = [UInt8](repeating: 0, count: bufferSize)\n var pendingData = Data()\n while isConnected && !Task.isCancelled {\n do {\n let bytesRead = try buffer.withUnsafeMutableBufferPointer { pointer in\n try input.read(into: UnsafeMutableRawBufferPointer(pointer))\n }\n if bytesRead == 0 {\n logger.notice(\"EOF received\")\n break\n }\n pendingData.append(Data(buffer[.. 0 else {\n await disconnect()\n return\n }\n buffer.append(chunk.prefix(bytesRead))\n while let newlineIndex = buffer.firstIndex(of: UInt8(ascii: \"\\n\")) {\n let message = buffer.prefix(upTo: newlineIndex)\n buffer.removeSubrange(...newlineIndex)\n messageContinuation.yield(message)\n }\n } catch let error as Errno where error == .resourceTemporarilyUnavailable {\n try? await Task.sleep(for: .milliseconds(10))\n continue\n } catch {\n messageContinuation.finish(throwing: error)\n return\n }\n }\n }"}} +{"repo_name": "swift-sdk", "file_name": "/swift-sdk/Sources/MCP/Base/Transports/NetworkTransport.swift", "inference_info": {"prefix_code": "import Foundation\nimport Logging\n\n#if canImport(Network)\n import Network\n\n /// Protocol that abstracts the Network.NWConnection functionality needed for NetworkTransport\n @preconcurrency protocol NetworkConnectionProtocol {\n var state: NWConnection.State { get }\n var stateUpdateHandler: ((@Sendable (NWConnection.State) -> Void))? { get set }\n\n func start(queue: DispatchQueue)\n func cancel()\n func send(\n content: Data?, contentContext: NWConnection.ContentContext, isComplete: Bool,\n completion: NWConnection.SendCompletion)\n func receive(\n minimumIncompleteLength: Int, maximumLength: Int,\n completion: @escaping @Sendable (\n Data?, NWConnection.ContentContext?, Bool, NWError?\n ) -> Void)\n }\n\n /// Extension to conform NWConnection to internal NetworkConnectionProtocol\n extension NWConnection: NetworkConnectionProtocol {}\n\n /// An implementation of a custom MCP transport using Apple's Network framework.\n ///\n /// This transport allows MCP clients and servers to communicate over TCP/UDP connections\n /// using Apple's Network framework.\n ///\n /// - Important: This transport is available exclusively on Apple platforms\n /// (macOS, iOS, watchOS, tvOS, visionOS) as it depends on the Network framework.\n ///\n /// ## Example Usage\n ///\n /// ```swift\n /// import MCP\n /// import Network\n ///\n /// // Create a TCP connection to a server\n /// let connection = NWConnection(\n /// host: NWEndpoint.Host(\"localhost\"),\n /// port: NWEndpoint.Port(8080)!,\n /// using: .tcp\n /// )\n ///\n /// // Initialize the transport with the connection\n /// let transport = NetworkTransport(connection: connection)\n ///\n /// // For large messages (e.g., images), configure unlimited buffer size\n /// let largeBufferTransport = NetworkTransport(\n /// connection: connection,\n /// bufferConfig: .unlimited\n /// )\n ///\n /// // Use the transport with an MCP client\n /// let client = Client(name: \"MyApp\", version: \"1.0.0\")\n /// try await client.connect(transport: transport)\n /// ```\n public actor NetworkTransport: Transport {\n /// Represents a heartbeat message for connection health monitoring.\n public struct Heartbeat: RawRepresentable, Hashable, Sendable {\n /// Magic bytes used to identify a heartbeat message.\n private static let magicBytes: [UInt8] = [0xF0, 0x9F, 0x92, 0x93]\n\n /// The timestamp of when the heartbeat was created.\n public let timestamp: Date\n\n /// Creates a new heartbeat with the current timestamp.\n public init() {\n self.timestamp = Date()\n }\n\n /// Creates a heartbeat with a specific timestamp.\n ///\n /// - Parameter timestamp: The timestamp for the heartbeat.\n public init(timestamp: Date) {\n self.timestamp = timestamp\n }\n\n // MARK: - RawRepresentable\n\n public typealias RawValue = [UInt8]\n\n /// Creates a heartbeat from its raw representation.\n ///\n /// - Parameter rawValue: The raw bytes of the heartbeat message.\n /// - Returns: A heartbeat if the raw value is valid, nil otherwise.\n public init?(rawValue: [UInt8]) {\n // Check if the data has the correct format (magic bytes + timestamp)\n guard rawValue.count >= 12,\n rawValue.prefix(4).elementsEqual(Self.magicBytes)\n else {\n return nil\n }\n\n // Extract the timestamp\n let timestampData = Data(rawValue[4..<12])\n let timestamp = timestampData.withUnsafeBytes {\n $0.load(as: UInt64.self)\n }\n\n self.timestamp = Date(\n timeIntervalSinceReferenceDate: TimeInterval(timestamp) / 1000.0)\n }\n\n /// Converts the heartbeat to its raw representation.\n public var rawValue: [UInt8] {\n var result = Data(Self.magicBytes)\n\n // Add timestamp (milliseconds since reference date)\n let timestamp = UInt64(self.timestamp.timeIntervalSinceReferenceDate * 1000)\n withUnsafeBytes(of: timestamp) { buffer in\n result.append(contentsOf: buffer)\n }\n\n return Array(result)\n }\n\n /// Converts the heartbeat to Data.\n public var data: Data {\n return Data(self.rawValue)\n }\n\n /// Checks if the given data represents a heartbeat message.\n ///\n /// - Parameter data: The data to check.\n /// - Returns: true if the data is a heartbeat message, false otherwise.\n public static func isHeartbeat(_ data: Data) -> Bool {\n guard data.count >= 4 else {\n return false\n }\n\n return data.prefix(4).elementsEqual(Self.magicBytes)\n }\n\n /// Attempts to parse a heartbeat from the given data.\n ///\n /// - Parameter data: The data to parse.\n /// - Returns: A heartbeat if the data is valid, nil otherwise.\n public static func from(data: Data) -> Heartbeat? {\n guard data.count >= 12 else {\n return nil\n }\n\n return Heartbeat(rawValue: Array(data))\n }\n }\n\n /// Configuration for heartbeat behavior.\n public struct HeartbeatConfiguration: Hashable, Sendable {\n /// Whether heartbeats are enabled.\n public let enabled: Bool\n /// Interval between heartbeats in seconds.\n public let interval: TimeInterval\n\n /// Creates a new heartbeat configuration.\n ///\n /// - Parameters:\n /// - enabled: Whether heartbeats are enabled (default: true)\n /// - interval: Interval in seconds between heartbeats (default: 15.0)\n public init(enabled: Bool = true, interval: TimeInterval = 15.0) {\n self.enabled = enabled\n self.interval = interval\n }\n\n /// Default heartbeat configuration.\n public static let `default` = HeartbeatConfiguration()\n\n /// Configuration with heartbeats disabled.\n public static let disabled = HeartbeatConfiguration(enabled: false)\n }\n\n /// Configuration for connection retry behavior.\n public struct ReconnectionConfiguration: Hashable, Sendable {\n /// Whether the transport should attempt to reconnect on failure.\n public let enabled: Bool\n /// Maximum number of reconnection attempts.\n public let maxAttempts: Int\n /// Multiplier for exponential backoff on reconnect.\n public let backoffMultiplier: Double\n\n /// Creates a new reconnection configuration.\n ///\n /// - Parameters:\n /// - enabled: Whether reconnection should be attempted on failure (default: true)\n /// - maxAttempts: Maximum number of reconnection attempts (default: 5)\n /// - backoffMultiplier: Multiplier for exponential backoff on reconnect (default: 1.5)\n public init(\n enabled: Bool = true,\n maxAttempts: Int = 5,\n backoffMultiplier: Double = 1.5\n ) {\n self.enabled = enabled\n self.maxAttempts = maxAttempts\n self.backoffMultiplier = backoffMultiplier\n }\n\n /// Default reconnection configuration.\n public static let `default` = ReconnectionConfiguration()\n\n /// Configuration with reconnection disabled.\n public static let disabled = ReconnectionConfiguration(enabled: false)\n\n /// Calculates the backoff delay for a given attempt number.\n ///\n /// - Parameter attempt: The current attempt number (1-based)\n /// - Returns: The delay in seconds before the next attempt\n public func backoffDelay(for attempt: Int) -> TimeInterval {\n let baseDelay = 0.5 // 500ms\n return baseDelay * pow(backoffMultiplier, Double(attempt - 1))\n }\n }\n\n /// Configuration for buffer behavior.\n public struct BufferConfiguration: Hashable, Sendable {\n /// Maximum buffer size for receiving data chunks.\n /// Set to nil for unlimited (uses system default).\n public let maxReceiveBufferSize: Int?\n\n /// Creates a new buffer configuration.\n ///\n /// - Parameter maxReceiveBufferSize: Maximum buffer size in bytes (default: 10MB, nil for unlimited)\n public init(maxReceiveBufferSize: Int? = 10 * 1024 * 1024) {\n self.maxReceiveBufferSize = maxReceiveBufferSize\n }\n\n /// Default buffer configuration with 10MB limit.\n public static let `default` = BufferConfiguration()\n\n /// Configuration with no buffer size limit.\n public static let unlimited = BufferConfiguration(maxReceiveBufferSize: nil)\n }\n\n // State tracking\n private var isConnected = false\n private var isStopping = false\n private var reconnectAttempt = 0\n private var heartbeatTask: Task?\n private var lastHeartbeatTime: Date?\n private let messageStream: AsyncThrowingStream\n private let messageContinuation: AsyncThrowingStream.Continuation\n\n // Track connection state for continuations\n private var connectionContinuationResumed = false\n\n // Connection is marked nonisolated(unsafe) to allow access from closures\n private nonisolated(unsafe) var connection: NetworkConnectionProtocol\n\n /// Logger instance for transport-related events\n public nonisolated let logger: Logger\n\n // Configuration\n private let heartbeatConfig: HeartbeatConfiguration\n private let reconnectionConfig: ReconnectionConfiguration\n private let bufferConfig: BufferConfiguration\n\n /// Creates a new NetworkTransport with the specified NWConnection\n ///\n /// - Parameters:\n /// - connection: The NWConnection to use for communication\n /// - logger: Optional logger instance for transport events\n /// - reconnectionConfig: Configuration for reconnection behavior (default: .default)\n /// - heartbeatConfig: Configuration for heartbeat behavior (default: .default)\n /// - bufferConfig: Configuration for buffer behavior (default: .default)\n public init(\n connection: NWConnection,\n logger: Logger? = nil,\n heartbeatConfig: HeartbeatConfiguration = .default,\n reconnectionConfig: ReconnectionConfiguration = .default,\n bufferConfig: BufferConfiguration = .default\n ) {\n self.init(\n connection,\n logger: logger,\n heartbeatConfig: heartbeatConfig,\n reconnectionConfig: reconnectionConfig,\n bufferConfig: bufferConfig\n )\n }\n\n init(\n _ connection: NetworkConnectionProtocol,\n logger: Logger? = nil,\n heartbeatConfig: HeartbeatConfiguration = .default,\n reconnectionConfig: ReconnectionConfiguration = .default,\n bufferConfig: BufferConfiguration = .default\n ) {\n self.connection = connection\n self.logger =\n logger\n ?? Logger(\n label: \"mcp.transport.network\",\n factory: { _ in SwiftLogNoOpLogHandler() }\n )\n self.reconnectionConfig = reconnectionConfig\n self.heartbeatConfig = heartbeatConfig\n self.bufferConfig = bufferConfig\n\n // Create message stream\n var continuation: AsyncThrowingStream.Continuation!\n self.messageStream = AsyncThrowingStream { continuation = $0 }\n self.messageContinuation = continuation\n }\n\n /// Establishes connection with the transport\n ///\n /// This initiates the NWConnection and waits for it to become ready.\n /// Once the connection is established, it starts the message receiving loop.\n ///\n /// - Throws: Error if the connection fails to establish\n public func connect() async throws {\n guard !isConnected else { return }\n\n // Reset state for fresh connection\n isStopping = false\n reconnectAttempt = 0\n\n // Reset continuation state\n connectionContinuationResumed = false\n\n // Wait for connection to be ready\n try await withCheckedThrowingContinuation {\n [weak self] (continuation: CheckedContinuation) in\n guard let self = self else {\n continuation.resume(throwing: MCPError.internalError(\"Transport deallocated\"))\n return\n }\n\n connection.stateUpdateHandler = { [weak self] state in\n guard let self = self else { return }\n\n Task { @MainActor in\n switch state {\n case .ready:\n await self.handleConnectionReady(continuation: continuation)\n case .failed(let error):\n await self.handleConnectionFailed(\n error: error, continuation: continuation)\n case .cancelled:\n await self.handleConnectionCancelled(continuation: continuation)\n case .waiting(let error):\n self.logger.debug(\"Connection waiting: \\(error)\")\n case .preparing:\n self.logger.debug(\"Connection preparing...\")\n case .setup:\n self.logger.debug(\"Connection setup...\")\n @unknown default:\n self.logger.warning(\"Unknown connection state\")\n }\n }\n }\n\n connection.start(queue: .main)\n }\n }\n\n /// Handles when the connection reaches the ready state\n ///\n /// - Parameter continuation: The continuation to resume when connection is ready\n private func handleConnectionReady(continuation: CheckedContinuation)\n async\n {\n if !connectionContinuationResumed {\n connectionContinuationResumed = true\n isConnected = true\n\n // Reset reconnect attempt counter on successful connection\n reconnectAttempt = 0\n logger.info(\"Network transport connected successfully\")\n continuation.resume()\n\n // Start the receive loop after connection is established\n Task { await self.receiveLoop() }\n\n // Start heartbeat task if enabled\n if heartbeatConfig.enabled {\n startHeartbeat()\n }\n }\n }\n\n /// Starts a task to periodically send heartbeats to check connection health\n private func startHeartbeat() {\n // Cancel any existing heartbeat task\n heartbeatTask?.cancel()\n\n // Start a new heartbeat task\n heartbeatTask = Task { [weak self] in\n guard let self = self else { return }\n\n // Initial delay before starting heartbeats\n try? await Task.sleep(for: .seconds(1))\n\n while !Task.isCancelled {\n do {\n // Check actor-isolated properties first\n let isStopping = await self.isStopping\n let isConnected = await self.isConnected\n\n guard !isStopping && isConnected else { break }\n\n try await self.sendHeartbeat()\n try await Task.sleep(for: .seconds(self.heartbeatConfig.interval))\n } catch {\n // If heartbeat fails, log and retry after a shorter interval\n self.logger.warning(\"Heartbeat failed: \\(error)\")\n try? await Task.sleep(for: .seconds(2))\n }\n }\n }\n }\n\n /// Sends a heartbeat message to verify connection health\n private func sendHeartbeat() async throws {\n guard isConnected && !isStopping else { return }\n\n // Try to send the heartbeat (without the newline delimiter used for normal messages)\n try await withCheckedThrowingContinuation {\n [weak self] (continuation: CheckedContinuation) in\n guard let self = self else {\n continuation.resume(throwing: MCPError.internalError(\"Transport deallocated\"))\n return\n }\n\n connection.send(\n content: Heartbeat().data,\n contentContext: .defaultMessage,\n isComplete: true,\n completion: .contentProcessed { [weak self] error in\n if let error = error {\n continuation.resume(throwing: error)\n } else {\n Task { [weak self] in\n await self?.setLastHeartbeatTime(Date())\n }\n continuation.resume()\n }\n })\n }\n\n logger.trace(\"Heartbeat sent\")\n }\n\n /// Handles connection failure\n ///\n /// - Parameters:\n /// - error: The error that caused the connection to fail\n /// - continuation: The continuation to resume with the error\n private func handleConnectionFailed(\n error: Swift.Error, continuation: CheckedContinuation\n ) async {\n if !connectionContinuationResumed {\n connectionContinuationResumed = true\n logger.error(\"Connection failed: \\(error)\")\n\n await handleReconnection(\n error: error,\n continuation: continuation,\n context: \"failure\"\n )\n }\n }\n\n /// Handles connection cancellation\n ///\n /// - Parameter continuation: The continuation to resume with cancellation error\n private func handleConnectionCancelled(continuation: CheckedContinuation)\n async\n {\n if !connectionContinuationResumed {\n connectionContinuationResumed = true\n logger.warning(\"Connection cancelled\")\n\n await handleReconnection(\n error: MCPError.internalError(\"Connection cancelled\"),\n continuation: continuation,\n context: \"cancellation\"\n )\n }\n }\n\n /// Common reconnection handling logic\n ///\n /// - Parameters:\n /// - error: The error that triggered the reconnection\n /// - continuation: The continuation to resume with the error\n /// - context: The context of the reconnection (for logging)\n private func handleReconnection(\n error: Swift.Error,\n continuation: CheckedContinuation,\n context: String\n ) async {\n if !isStopping,\n reconnectionConfig.enabled,\n reconnectAttempt < reconnectionConfig.maxAttempts\n {\n // Try to reconnect with exponential backoff\n reconnectAttempt += 1\n logger.info(\n \"Attempting reconnection after \\(context) (\\(reconnectAttempt)/\\(reconnectionConfig.maxAttempts))...\"\n )\n\n // Calculate backoff delay\n let delay = reconnectionConfig.backoffDelay(for: reconnectAttempt)\n\n // Schedule reconnection attempt after delay\n Task {\n try? await Task.sleep(for: .seconds(delay))\n if !isStopping {\n // Cancel the current connection before attempting to reconnect.\n self.connection.cancel()\n // Resume original continuation with error; outer logic or a new call to connect() will handle retry.\n continuation.resume(throwing: error)\n } else {\n continuation.resume(throwing: error) // Stopping, so fail.\n }\n }\n } else {\n // Not configured to reconnect, exceeded max attempts, or stopping\n self.connection.cancel() // Ensure connection is cancelled\n continuation.resume(throwing: error)\n }\n }\n\n /// Disconnects from the transport\n ///\n /// This cancels the NWConnection, finalizes the message stream,\n /// and releases associated resources.\n public func disconnect() async {\n guard isConnected else { return }\n\n // Mark as stopping to prevent reconnection attempts during disconnect\n isStopping = true\n isConnected = false\n\n // Cancel heartbeat task if it exists\n heartbeatTask?.cancel()\n heartbeatTask = nil\n\n connection.cancel()\n messageContinuation.finish()\n logger.info(\"Network transport disconnected\")\n }\n\n /// Sends data through the network connection\n ///\n /// This sends a JSON-RPC message through the NWConnection, adding a newline\n /// delimiter to mark the end of the message.\n ///\n /// - Parameter message: The JSON-RPC message to send\n /// - Throws: MCPError for transport failures or connection issues\n public func send(_ message: Data) async throws {\n guard isConnected else {\n throw MCPError.internalError(\"Transport not connected\")\n }\n\n // Add newline as delimiter\n var messageWithNewline = message\n messageWithNewline.append(UInt8(ascii: \"\\n\"))\n\n // Use a local actor-isolated variable to track continuation state\n var sendContinuationResumed = false\n\n try await withCheckedThrowingContinuation {\n [weak self] (continuation: CheckedContinuation) in\n guard let self = self else {\n continuation.resume(throwing: MCPError.internalError(\"Transport deallocated\"))\n return\n }\n\n connection.send(\n content: messageWithNewline,\n contentContext: .defaultMessage,\n isComplete: true,\n completion: .contentProcessed { [weak self] error in\n guard let self = self else { return }\n\n Task { @MainActor in\n if !sendContinuationResumed {\n sendContinuationResumed = true\n if let error = error {\n self.logger.error(\"Send error: \\(error)\")\n\n // Check if we should attempt to reconnect on send failure\n let isStopping = await self.isStopping // Await actor-isolated property\n if !isStopping && self.reconnectionConfig.enabled {\n let isConnected = await self.isConnected\n if isConnected {\n if error.isConnectionLost {\n self.logger.warning(\n \"Connection appears broken, will attempt to reconnect...\"\n )\n\n // Schedule connection restart\n Task { [weak self] in // Operate on self's executor\n guard let self = self else { return }\n\n await self.setIsConnected(false)\n\n try? await Task.sleep(for: .milliseconds(500))\n\n let currentIsStopping = await self.isStopping\n if !currentIsStopping {\n // Cancel the connection, then attempt to reconnect fully.\n self.connection.cancel()\n try? await self.connect()\n }\n }\n }\n }\n }\n\n continuation.resume(\n throwing: MCPError.internalError(\"Send error: \\(error)\"))\n } else {\n continuation.resume()\n }\n }\n }\n })\n }\n }\n\n /// Receives data in an async sequence\n ///\n /// This returns an AsyncThrowingStream that emits Data objects representing\n /// each JSON-RPC message received from the network connection.\n ///\n /// - Returns: An AsyncThrowingStream of Data objects\n public func receive() -> AsyncThrowingStream {\n return messageStream\n }\n\n /// Continuous loop to receive and process incoming messages\n ///\n /// This method runs continuously while the connection is active,\n /// receiving data and yielding complete messages to the message stream.\n /// Messages are delimited by newline characters.\n ", "suffix_code": "\n\n /// Receives a chunk of data from the network connection\n ///\n /// - Returns: The received data chunk\n /// - Throws: Network errors or transport failures\n private func receiveData() async throws -> Data {\n var receiveContinuationResumed = false\n\n return try await withCheckedThrowingContinuation {\n [weak self] (continuation: CheckedContinuation) in\n guard let self = self else {\n continuation.resume(throwing: MCPError.internalError(\"Transport deallocated\"))\n return\n }\n\n let maxLength = bufferConfig.maxReceiveBufferSize ?? Int.max\n connection.receive(minimumIncompleteLength: 1, maximumLength: maxLength) {\n content, _, isComplete, error in\n Task { @MainActor in\n if !receiveContinuationResumed {\n receiveContinuationResumed = true\n if let error = error {\n continuation.resume(throwing: MCPError.transportError(error))\n } else if let content = content {\n continuation.resume(returning: content)\n } else if isComplete {\n self.logger.trace(\"Connection completed by peer\")\n continuation.resume(throwing: MCPError.connectionClosed)\n } else {\n // EOF: Resume with empty data instead of throwing an error\n continuation.resume(returning: Data())\n }\n }\n }\n }\n }\n }\n\n private func setLastHeartbeatTime(_ time: Date) {\n self.lastHeartbeatTime = time\n }\n\n private func setIsConnected(_ connected: Bool) {\n self.isConnected = connected\n }\n }\n\n extension NWError {\n /// Whether this error indicates a connection has been lost or reset.\n fileprivate var isConnectionLost: Bool {\n let nsError = self as NSError\n return nsError.code == 57 // Socket is not connected (EHOSTUNREACH or ENOTCONN)\n || nsError.code == 54 // Connection reset by peer (ECONNRESET)\n }\n }\n#endif\n", "middle_code": "private func receiveLoop() async {\n var buffer = Data()\n var consecutiveEmptyReads = 0\n let maxConsecutiveEmptyReads = 5\n while isConnected && !Task.isCancelled && !isStopping {\n do {\n let newData = try await receiveData()\n if newData.isEmpty {\n consecutiveEmptyReads += 1\n if consecutiveEmptyReads >= maxConsecutiveEmptyReads {\n logger.warning(\n \"Multiple consecutive empty reads (\\(consecutiveEmptyReads)), possible connection issue\"\n )\n if connection.state != .ready {\n logger.info(\"Connection no longer ready, exiting receive loop\")\n break\n }\n }\n try await Task.sleep(for: .milliseconds(100))\n continue\n }\n if Heartbeat.isHeartbeat(newData) {\n logger.trace(\"Received heartbeat from peer\")\n if let heartbeat = Heartbeat.from(data: newData) {\n logger.trace(\"Heartbeat timestamp: \\(heartbeat.timestamp)\")\n }\n consecutiveEmptyReads = 0\n continue \n }\n consecutiveEmptyReads = 0\n buffer.append(newData)\n while let newlineIndex = buffer.firstIndex(of: UInt8(ascii: \"\\n\")) {\n let messageData = buffer[..?\n\n /// Logger instance for transport-related events\n public nonisolated let logger: Logger\n\n /// Maximum time to wait for a session ID before proceeding with SSE connection\n public let sseInitializationTimeout: TimeInterval\n\n private var isConnected = false\n private let messageStream: AsyncThrowingStream\n private let messageContinuation: AsyncThrowingStream.Continuation\n\n private var initialSessionIDSignalTask: Task?\n private var initialSessionIDContinuation: CheckedContinuation?\n\n /// Creates a new HTTP transport client with the specified endpoint\n ///\n /// - Parameters:\n /// - endpoint: The server URL to connect to\n /// - configuration: URLSession configuration to use for HTTP requests\n /// - streaming: Whether to enable SSE streaming mode (default: true)\n /// - sseInitializationTimeout: Maximum time to wait for session ID before proceeding with SSE (default: 10 seconds)\n /// - logger: Optional logger instance for transport events\n public init(\n endpoint: URL,\n configuration: URLSessionConfiguration = .default,\n streaming: Bool = true,\n sseInitializationTimeout: TimeInterval = 10,\n logger: Logger? = nil\n ) {\n self.init(\n endpoint: endpoint,\n session: URLSession(configuration: configuration),\n streaming: streaming,\n sseInitializationTimeout: sseInitializationTimeout,\n logger: logger\n )\n }\n\n internal init(\n endpoint: URL,\n session: URLSession,\n streaming: Bool = false,\n sseInitializationTimeout: TimeInterval = 10,\n logger: Logger? = nil\n ) {\n self.endpoint = endpoint\n self.session = session\n self.streaming = streaming\n self.sseInitializationTimeout = sseInitializationTimeout\n\n // Create message stream\n var continuation: AsyncThrowingStream.Continuation!\n self.messageStream = AsyncThrowingStream { continuation = $0 }\n self.messageContinuation = continuation\n\n self.logger =\n logger\n ?? Logger(\n label: \"mcp.transport.http.client\",\n factory: { _ in SwiftLogNoOpLogHandler() }\n )\n }\n\n // Setup the initial session ID signal\n private func setupInitialSessionIDSignal() {\n self.initialSessionIDSignalTask = Task {\n await withCheckedContinuation { continuation in\n self.initialSessionIDContinuation = continuation\n // This task will suspend here until continuation.resume() is called\n }\n }\n }\n\n // Trigger the initial session ID signal when a session ID is established\n private func triggerInitialSessionIDSignal() {\n if let continuation = self.initialSessionIDContinuation {\n continuation.resume()\n self.initialSessionIDContinuation = nil // Consume the continuation\n logger.trace(\"Initial session ID signal triggered for SSE task.\")\n }\n }\n\n /// Establishes connection with the transport\n ///\n /// This prepares the transport for communication and sets up SSE streaming\n /// if streaming mode is enabled. The actual HTTP connection happens with the\n /// first message sent.\n public func connect() async throws {\n guard !isConnected else { return }\n isConnected = true\n\n // Setup initial session ID signal\n setupInitialSessionIDSignal()\n\n if streaming {\n // Start listening to server events\n streamingTask = Task { await startListeningForServerEvents() }\n }\n\n logger.info(\"HTTP transport connected\")\n }\n\n /// Disconnects from the transport\n ///\n /// This terminates any active connections, cancels the streaming task,\n /// and releases any resources being used by the transport.\n public func disconnect() async {\n guard isConnected else { return }\n isConnected = false\n\n // Cancel streaming task if active\n streamingTask?.cancel()\n streamingTask = nil\n\n // Cancel any in-progress requests\n session.invalidateAndCancel()\n\n // Clean up message stream\n messageContinuation.finish()\n\n // Cancel the initial session ID signal task if active\n initialSessionIDSignalTask?.cancel()\n initialSessionIDSignalTask = nil\n // Resume the continuation if it's still pending to avoid leaks\n initialSessionIDContinuation?.resume()\n initialSessionIDContinuation = nil\n\n logger.info(\"HTTP clienttransport disconnected\")\n }\n\n /// Sends data through an HTTP POST request\n ///\n /// This sends a JSON-RPC message to the server via HTTP POST and processes\n /// the response according to the MCP Streamable HTTP specification. It handles:\n ///\n /// - Adding appropriate Accept headers for both JSON and SSE\n /// - Including the session ID in requests if one has been established\n /// - Processing different response types (JSON vs SSE)\n /// - Handling HTTP error codes according to the specification\n ///\n /// - Parameter data: The JSON-RPC message to send\n /// - Throws: MCPError for transport failures or server errors\n public func send(_ data: Data) async throws {\n guard isConnected else {\n throw MCPError.internalError(\"Transport not connected\")\n }\n\n var request = URLRequest(url: endpoint)\n request.httpMethod = \"POST\"\n request.addValue(\"application/json, text/event-stream\", forHTTPHeaderField: \"Accept\")\n request.addValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\n request.httpBody = data\n\n // Add session ID if available\n if let sessionID = sessionID {\n request.addValue(sessionID, forHTTPHeaderField: \"Mcp-Session-Id\")\n }\n\n #if os(Linux)\n // Linux implementation using data(for:) instead of bytes(for:)\n let (responseData, response) = try await session.data(for: request)\n try await processResponse(response: response, data: responseData)\n #else\n // macOS and other platforms with bytes(for:) support\n let (responseStream, response) = try await session.bytes(for: request)\n try await processResponse(response: response, stream: responseStream)\n #endif\n }\n\n #if os(Linux)\n // Process response with data payload (Linux)\n private func processResponse(response: URLResponse, data: Data) async throws {\n guard let httpResponse = response as? HTTPURLResponse else {\n throw MCPError.internalError(\"Invalid HTTP response\")\n }\n\n // Process the response based on content type and status code\n let contentType = httpResponse.value(forHTTPHeaderField: \"Content-Type\") ?? \"\"\n\n // Extract session ID if present\n if let newSessionID = httpResponse.value(forHTTPHeaderField: \"Mcp-Session-Id\") {\n let wasSessionIDNil = (self.sessionID == nil)\n self.sessionID = newSessionID\n if wasSessionIDNil {\n // Trigger signal on first session ID\n triggerInitialSessionIDSignal()\n }\n logger.debug(\"Session ID received\", metadata: [\"sessionID\": \"\\(newSessionID)\"])\n }\n\n try processHTTPResponse(httpResponse, contentType: contentType)\n guard case 200..<300 = httpResponse.statusCode else { return }\n\n // For JSON responses, yield the data\n if contentType.contains(\"text/event-stream\") {\n logger.warning(\"SSE responses aren't fully supported on Linux\")\n messageContinuation.yield(data)\n } else if contentType.contains(\"application/json\") {\n logger.trace(\"Received JSON response\", metadata: [\"size\": \"\\(data.count)\"])\n messageContinuation.yield(data)\n } else {\n logger.warning(\"Unexpected content type: \\(contentType)\")\n }\n }\n #else\n // Process response with byte stream (macOS, iOS, etc.)\n private func processResponse(response: URLResponse, stream: URLSession.AsyncBytes)\n async throws\n {\n guard let httpResponse = response as? HTTPURLResponse else {\n throw MCPError.internalError(\"Invalid HTTP response\")\n }\n\n // Process the response based on content type and status code\n let contentType = httpResponse.value(forHTTPHeaderField: \"Content-Type\") ?? \"\"\n\n // Extract session ID if present\n if let newSessionID = httpResponse.value(forHTTPHeaderField: \"Mcp-Session-Id\") {\n let wasSessionIDNil = (self.sessionID == nil)\n self.sessionID = newSessionID\n if wasSessionIDNil {\n // Trigger signal on first session ID\n triggerInitialSessionIDSignal()\n }\n logger.debug(\"Session ID received\", metadata: [\"sessionID\": \"\\(newSessionID)\"])\n }\n\n try processHTTPResponse(httpResponse, contentType: contentType)\n guard case 200..<300 = httpResponse.statusCode else { return }\n\n if contentType.contains(\"text/event-stream\") {\n // For SSE, processing happens via the stream\n logger.trace(\"Received SSE response, processing in streaming task\")\n try await self.processSSE(stream)\n } else if contentType.contains(\"application/json\") {\n // For JSON responses, collect and deliver the data\n var buffer = Data()\n for try await byte in stream {\n buffer.append(byte)\n }\n logger.trace(\"Received JSON response\", metadata: [\"size\": \"\\(buffer.count)\"])\n messageContinuation.yield(buffer)\n } else {\n logger.warning(\"Unexpected content type: \\(contentType)\")\n }\n }\n #endif\n\n // Common HTTP response handling for all platforms\n private func processHTTPResponse(_ response: HTTPURLResponse, contentType: String) throws {\n // Handle status codes according to HTTP semantics\n switch response.statusCode {\n case 200..<300:\n // Success range - these are handled by the platform-specific code\n return\n\n case 400:\n throw MCPError.internalError(\"Bad request\")\n\n case 401:\n throw MCPError.internalError(\"Authentication required\")\n\n case 403:\n throw MCPError.internalError(\"Access forbidden\")\n\n case 404:\n // If we get a 404 with a session ID, it means our session is invalid\n if sessionID != nil {\n logger.warning(\"Session has expired\")\n sessionID = nil\n throw MCPError.internalError(\"Session expired\")\n }\n throw MCPError.internalError(\"Endpoint not found\")\n\n case 405:\n // If we get a 405, it means the server does not support the requested method\n // If streaming was requested, we should cancel the streaming task\n if streaming {\n self.streamingTask?.cancel()\n throw MCPError.internalError(\"Server does not support streaming\")\n }\n throw MCPError.internalError(\"Method not allowed\")\n\n case 408:\n throw MCPError.internalError(\"Request timeout\")\n\n case 429:\n throw MCPError.internalError(\"Too many requests\")\n\n case 500..<600:\n // Server error range\n throw MCPError.internalError(\"Server error: \\(response.statusCode)\")\n\n default:\n throw MCPError.internalError(\n \"Unexpected HTTP response: \\(response.statusCode) (\\(contentType))\")\n }\n }\n\n /// Receives data in an async sequence\n ///\n /// This returns an AsyncThrowingStream that emits Data objects representing\n /// each JSON-RPC message received from the server. This includes:\n ///\n /// - Direct responses to client requests\n /// - Server-initiated messages delivered via SSE streams\n ///\n /// - Returns: An AsyncThrowingStream of Data objects\n public func receive() -> AsyncThrowingStream {\n return messageStream\n }\n\n // MARK: - SSE\n\n /// Starts listening for server events using SSE\n ///\n /// This establishes a long-lived HTTP connection using Server-Sent Events (SSE)\n /// to enable server-to-client push messaging. It handles:\n ///\n /// - Waiting for session ID if needed\n /// - Opening the SSE connection\n /// - Automatic reconnection on connection drops\n /// - Processing received events\n private func startListeningForServerEvents() async {\n #if os(Linux)\n // SSE is not fully supported on Linux\n if streaming {\n logger.warning(\n \"SSE streaming was requested but is not fully supported on Linux. SSE connection will not be attempted.\"\n )\n }\n #else\n // This is the original code for platforms that support SSE\n guard isConnected else { return }\n\n // Wait for the initial session ID signal, but only if sessionID isn't already set\n if self.sessionID == nil, let signalTask = self.initialSessionIDSignalTask {\n logger.trace(\"SSE streaming task waiting for initial sessionID signal...\")\n\n // Race the signalTask against a timeout\n let timeoutTask = Task {\n try? await Task.sleep(for: .seconds(self.sseInitializationTimeout))\n return false\n }\n\n let signalCompletionTask = Task {\n await signalTask.value\n return true // Indicates signal received\n }\n\n // Use TaskGroup to race the two tasks\n var signalReceived = false\n do {\n signalReceived = try await withThrowingTaskGroup(of: Bool.self) { group in\n group.addTask {\n await signalCompletionTask.value\n }\n group.addTask {\n await timeoutTask.value\n }\n\n // Take the first result and cancel the other task\n if let firstResult = try await group.next() {\n group.cancelAll()\n return firstResult\n }\n return false\n }\n } catch {\n logger.error(\"Error while waiting for session ID signal: \\(error)\")\n }\n\n // Clean up tasks\n timeoutTask.cancel()\n\n if signalReceived {\n logger.trace(\"SSE streaming task proceeding after initial sessionID signal.\")\n } else {\n logger.warning(\n \"Timeout waiting for initial sessionID signal. SSE stream will proceed (sessionID might be nil).\"\n )\n }\n } else if self.sessionID != nil {\n logger.trace(\n \"Initial sessionID already available. Proceeding with SSE streaming task immediately.\"\n )\n } else {\n logger.info(\n \"Proceeding with SSE connection attempt; sessionID is nil. This might be expected for stateless servers or if initialize hasn't provided one yet.\"\n )\n }\n\n // Retry loop for connection drops\n while isConnected && !Task.isCancelled {\n do {\n try await connectToEventStream()\n } catch {\n if !Task.isCancelled {\n logger.error(\"SSE connection error: \\(error)\")\n // Wait before retrying\n try? await Task.sleep(for: .seconds(1))\n }\n }\n }\n #endif\n }\n\n #if !os(Linux)\n /// Establishes an SSE connection to the server\n ///\n /// This initiates a GET request to the server endpoint with appropriate\n /// headers to establish an SSE stream according to the MCP specification.\n ///\n /// - Throws: MCPError for connection failures or server errors\n private func connectToEventStream() async throws {\n guard isConnected else { return }\n\n var request = URLRequest(url: endpoint)\n request.httpMethod = \"GET\"\n request.addValue(\"text/event-stream\", forHTTPHeaderField: \"Accept\")\n request.addValue(\"no-cache\", forHTTPHeaderField: \"Cache-Control\")\n\n // Add session ID if available\n if let sessionID = sessionID {\n request.addValue(sessionID, forHTTPHeaderField: \"Mcp-Session-Id\")\n }\n\n logger.debug(\"Starting SSE connection\")\n\n // Create URLSession task for SSE\n let (stream, response) = try await session.bytes(for: request)\n\n guard let httpResponse = response as? HTTPURLResponse else {\n throw MCPError.internalError(\"Invalid HTTP response\")\n }\n\n // Check response status\n guard httpResponse.statusCode == 200 else {\n // If the server returns 405 Method Not Allowed,\n // it indicates that the server doesn't support SSE streaming.\n // We should cancel the task instead of retrying the connection.\n if httpResponse.statusCode == 405 {\n self.streamingTask?.cancel()\n }\n throw MCPError.internalError(\"HTTP error: \\(httpResponse.statusCode)\")\n }\n\n // Extract session ID if present\n if let newSessionID = httpResponse.value(forHTTPHeaderField: \"Mcp-Session-Id\") {\n let wasSessionIDNil = (self.sessionID == nil)\n self.sessionID = newSessionID\n if wasSessionIDNil {\n // Trigger signal on first session ID, though this is unlikely to happen here\n // as GET usually follows a POST that would have already set the session ID\n triggerInitialSessionIDSignal()\n }\n logger.debug(\"Session ID received\", metadata: [\"sessionID\": \"\\(newSessionID)\"])\n }\n\n try await self.processSSE(stream)\n }\n\n /// Processes an SSE byte stream, extracting events and delivering them\n ///\n /// - Parameter stream: The URLSession.AsyncBytes stream to process\n /// - Throws: Error for stream processing failures\n private func processSSE(_ stream: URLSession.AsyncBytes) async throws {\n do {\n for try await event in stream.events {\n // Check if task has been cancelled\n if Task.isCancelled { break }\n\n logger.trace(\n \"SSE event received\",\n metadata: [\n \"type\": \"\\(event.event ?? \"message\")\",\n \"id\": \"\\(event.id ?? \"none\")\",\n ]\n )\n\n // Convert the event data to Data and yield it to the message stream\n if !event.data.isEmpty, let data = event.data.data(using: .utf8) {\n messageContinuation.yield(data)\n }\n }\n } catch {\n logger.error(\"Error processing SSE events: \\(error)\")\n throw error\n }\n }\n #endif\n}\n"], ["/swift-sdk/Sources/MCP/Base/Transports/StdioTransport.swift", "import Logging\n\nimport struct Foundation.Data\n\n#if canImport(System)\n import System\n#else\n @preconcurrency import SystemPackage\n#endif\n\n// Import for specific low-level operations not yet in Swift System\n#if canImport(Darwin)\n import Darwin.POSIX\n#elseif canImport(Glibc)\n import Glibc\n#endif\n\n#if canImport(Darwin) || canImport(Glibc)\n /// An implementation of the MCP stdio transport protocol.\n ///\n /// This transport implements the [stdio transport](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#stdio)\n /// specification from the Model Context Protocol.\n ///\n /// The stdio transport works by:\n /// - Reading JSON-RPC messages from standard input\n /// - Writing JSON-RPC messages to standard output\n /// - Using newline characters as message delimiters\n /// - Supporting non-blocking I/O operations\n ///\n /// This transport is the recommended option for most MCP applications due to its\n /// simplicity and broad platform support.\n ///\n /// - Important: This transport is available on Apple platforms and Linux distributions with glibc\n /// (Ubuntu, Debian, Fedora, CentOS, RHEL).\n ///\n /// ## Example Usage\n ///\n /// ```swift\n /// import MCP\n ///\n /// // Initialize the client\n /// let client = Client(name: \"MyApp\", version: \"1.0.0\")\n ///\n /// // Create a transport and connect\n /// let transport = StdioTransport()\n /// try await client.connect(transport: transport)\n /// ```\n public actor StdioTransport: Transport {\n private let input: FileDescriptor\n private let output: FileDescriptor\n /// Logger instance for transport-related events\n public nonisolated let logger: Logger\n\n private var isConnected = false\n private let messageStream: AsyncThrowingStream\n private let messageContinuation: AsyncThrowingStream.Continuation\n\n /// Creates a new stdio transport with the specified file descriptors\n ///\n /// - Parameters:\n /// - input: File descriptor for reading (defaults to standard input)\n /// - output: File descriptor for writing (defaults to standard output)\n /// - logger: Optional logger instance for transport events\n public init(\n input: FileDescriptor = FileDescriptor.standardInput,\n output: FileDescriptor = FileDescriptor.standardOutput,\n logger: Logger? = nil\n ) {\n self.input = input\n self.output = output\n self.logger =\n logger\n ?? Logger(\n label: \"mcp.transport.stdio\",\n factory: { _ in SwiftLogNoOpLogHandler() })\n\n // Create message stream\n var continuation: AsyncThrowingStream.Continuation!\n self.messageStream = AsyncThrowingStream { continuation = $0 }\n self.messageContinuation = continuation\n }\n\n /// Establishes connection with the transport\n ///\n /// This method configures the file descriptors for non-blocking I/O\n /// and starts the background message reading loop.\n ///\n /// - Throws: Error if the file descriptors cannot be configured\n public func connect() async throws {\n guard !isConnected else { return }\n\n // Set non-blocking mode\n try setNonBlocking(fileDescriptor: input)\n try setNonBlocking(fileDescriptor: output)\n\n isConnected = true\n logger.info(\"Transport connected successfully\")\n\n // Start reading loop in background\n Task {\n await readLoop()\n }\n }\n\n /// Configures a file descriptor for non-blocking I/O\n ///\n /// - Parameter fileDescriptor: The file descriptor to configure\n /// - Throws: Error if the operation fails\n private func setNonBlocking(fileDescriptor: FileDescriptor) throws {\n #if canImport(Darwin) || canImport(Glibc)\n // Get current flags\n let flags = fcntl(fileDescriptor.rawValue, F_GETFL)\n guard flags >= 0 else {\n throw MCPError.transportError(Errno(rawValue: CInt(errno)))\n }\n\n // Set non-blocking flag\n let result = fcntl(fileDescriptor.rawValue, F_SETFL, flags | O_NONBLOCK)\n guard result >= 0 else {\n throw MCPError.transportError(Errno(rawValue: CInt(errno)))\n }\n #else\n // For platforms where non-blocking operations aren't supported\n throw MCPError.internalError(\n \"Setting non-blocking mode not supported on this platform\")\n #endif\n }\n\n /// Continuous loop that reads and processes incoming messages\n ///\n /// This method runs in the background while the transport is connected,\n /// parsing complete messages delimited by newlines and yielding them\n /// to the message stream.\n private func readLoop() async {\n let bufferSize = 4096\n var buffer = [UInt8](repeating: 0, count: bufferSize)\n var pendingData = Data()\n\n while isConnected && !Task.isCancelled {\n do {\n let bytesRead = try buffer.withUnsafeMutableBufferPointer { pointer in\n try input.read(into: UnsafeMutableRawBufferPointer(pointer))\n }\n\n if bytesRead == 0 {\n logger.notice(\"EOF received\")\n break\n }\n\n pendingData.append(Data(buffer[.. 0 {\n remaining = remaining.dropFirst(written)\n }\n } catch let error where MCPError.isResourceTemporarilyUnavailable(error) {\n try await Task.sleep(for: .milliseconds(10))\n continue\n } catch {\n throw MCPError.transportError(error)\n }\n }\n }\n\n /// Receives messages from the transport.\n ///\n /// Messages may be individual JSON-RPC requests, notifications, responses,\n /// or batches containing multiple requests/notifications encoded as JSON arrays.\n /// Each message is guaranteed to be a complete JSON object or array.\n ///\n /// - Returns: An AsyncThrowingStream of Data objects representing JSON-RPC messages\n public func receive() -> AsyncThrowingStream {\n return messageStream\n }\n }\n#endif\n"], ["/swift-sdk/Sources/MCP/Client/Client.swift", "import Logging\n\nimport struct Foundation.Data\nimport struct Foundation.Date\nimport class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\n/// Model Context Protocol client\npublic actor Client {\n /// The client configuration\n public struct Configuration: Hashable, Codable, Sendable {\n /// The default configuration.\n public static let `default` = Configuration(strict: false)\n\n /// The strict configuration.\n public static let strict = Configuration(strict: true)\n\n /// When strict mode is enabled, the client:\n /// - Requires server capabilities to be initialized before making requests\n /// - Rejects all requests that require capabilities before initialization\n ///\n /// While the MCP specification requires servers to respond to initialize requests\n /// with their capabilities, some implementations may not follow this.\n /// Disabling strict mode allows the client to be more lenient with non-compliant\n /// servers, though this may lead to undefined behavior.\n public var strict: Bool\n\n public init(strict: Bool = false) {\n self.strict = strict\n }\n }\n\n /// Implementation information\n public struct Info: Hashable, Codable, Sendable {\n /// The client name\n public var name: String\n /// The client version\n public var version: String\n\n public init(name: String, version: String) {\n self.name = name\n self.version = version\n }\n }\n\n /// The client capabilities\n public struct Capabilities: Hashable, Codable, Sendable {\n /// The roots capabilities\n public struct Roots: Hashable, Codable, Sendable {\n /// Whether the list of roots has changed\n public var listChanged: Bool?\n\n public init(listChanged: Bool? = nil) {\n self.listChanged = listChanged\n }\n }\n\n /// The sampling capabilities\n public struct Sampling: Hashable, Codable, Sendable {\n public init() {}\n }\n\n /// Whether the client supports sampling\n public var sampling: Sampling?\n /// Experimental features supported by the client\n public var experimental: [String: String]?\n /// Whether the client supports roots\n public var roots: Capabilities.Roots?\n\n public init(\n sampling: Sampling? = nil,\n experimental: [String: String]? = nil,\n roots: Capabilities.Roots? = nil\n ) {\n self.sampling = sampling\n self.experimental = experimental\n self.roots = roots\n }\n }\n\n /// The connection to the server\n private var connection: (any Transport)?\n /// The logger for the client\n private var logger: Logger? {\n get async {\n await connection?.logger\n }\n }\n\n /// The client information\n private let clientInfo: Client.Info\n /// The client name\n public nonisolated var name: String { clientInfo.name }\n /// The client version\n public nonisolated var version: String { clientInfo.version }\n\n /// The client capabilities\n public var capabilities: Client.Capabilities\n /// The client configuration\n public var configuration: Configuration\n\n /// The server capabilities\n private var serverCapabilities: Server.Capabilities?\n /// The server version\n private var serverVersion: String?\n /// The server instructions\n private var instructions: String?\n\n /// A dictionary of type-erased notification handlers, keyed by method name\n private var notificationHandlers: [String: [NotificationHandlerBox]] = [:]\n /// The task for the message handling loop\n private var task: Task?\n\n /// An error indicating a type mismatch when decoding a pending request\n private struct TypeMismatchError: Swift.Error {}\n\n /// A pending request with a continuation for the result\n private struct PendingRequest {\n let continuation: CheckedContinuation\n }\n\n /// A type-erased pending request\n private struct AnyPendingRequest {\n private let _resume: (Result) -> Void\n\n init(_ request: PendingRequest) {\n _resume = { result in\n switch result {\n case .success(let value):\n if let typedValue = value as? T {\n request.continuation.resume(returning: typedValue)\n } else if let value = value as? Value,\n let data = try? JSONEncoder().encode(value),\n let decoded = try? JSONDecoder().decode(T.self, from: data)\n {\n request.continuation.resume(returning: decoded)\n } else {\n request.continuation.resume(throwing: TypeMismatchError())\n }\n case .failure(let error):\n request.continuation.resume(throwing: error)\n }\n }\n }\n func resume(returning value: Any) {\n _resume(.success(value))\n }\n\n func resume(throwing error: Swift.Error) {\n _resume(.failure(error))\n }\n }\n\n /// A dictionary of type-erased pending requests, keyed by request ID\n private var pendingRequests: [ID: AnyPendingRequest] = [:]\n // Add reusable JSON encoder/decoder\n private let encoder = JSONEncoder()\n private let decoder = JSONDecoder()\n\n public init(\n name: String,\n version: String,\n configuration: Configuration = .default\n ) {\n self.clientInfo = Client.Info(name: name, version: version)\n self.capabilities = Capabilities()\n self.configuration = configuration\n }\n\n /// Connect to the server using the given transport\n @discardableResult\n public func connect(transport: any Transport) async throws -> Initialize.Result {\n self.connection = transport\n try await self.connection?.connect()\n\n await logger?.info(\n \"Client connected\", metadata: [\"name\": \"\\(name)\", \"version\": \"\\(version)\"])\n\n // Start message handling loop\n task = Task {\n guard let connection = self.connection else { return }\n repeat {\n // Check for cancellation before starting the iteration\n if Task.isCancelled { break }\n\n do {\n let stream = await connection.receive()\n for try await data in stream {\n if Task.isCancelled { break } // Check inside loop too\n\n // Attempt to decode data\n // Try decoding as a batch response first\n if let batchResponse = try? decoder.decode([AnyResponse].self, from: data) {\n await handleBatchResponse(batchResponse)\n } else if let response = try? decoder.decode(AnyResponse.self, from: data) {\n await handleResponse(response)\n } else if let message = try? decoder.decode(AnyMessage.self, from: data) {\n await handleMessage(message)\n } else {\n var metadata: Logger.Metadata = [:]\n if let string = String(data: data, encoding: .utf8) {\n metadata[\"message\"] = .string(string)\n }\n await logger?.warning(\n \"Unexpected message received by client (not single/batch response or notification)\",\n metadata: metadata\n )\n }\n }\n } catch let error where MCPError.isResourceTemporarilyUnavailable(error) {\n try? await Task.sleep(for: .milliseconds(10))\n continue\n } catch {\n await logger?.error(\n \"Error in message handling loop\", metadata: [\"error\": \"\\(error)\"])\n break\n }\n } while true\n await self.logger?.info(\"Client message handling loop task is terminating.\")\n }\n\n // Automatically initialize after connecting\n return try await _initialize()\n }\n\n /// Disconnect the client and cancel all pending requests\n public func disconnect() async {\n await logger?.info(\"Initiating client disconnect...\")\n\n // Part 1: Inside actor - Grab state and clear internal references\n let taskToCancel = self.task\n let connectionToDisconnect = self.connection\n let pendingRequestsToCancel = self.pendingRequests\n\n self.task = nil\n self.connection = nil\n self.pendingRequests = [:] // Use empty dictionary literal\n\n // Part 2: Outside actor - Resume continuations, disconnect transport, await task\n\n // Resume continuations first\n for (_, request) in pendingRequestsToCancel {\n request.resume(throwing: MCPError.internalError(\"Client disconnected\"))\n }\n await logger?.info(\"Pending requests cancelled.\")\n\n // Cancel the task\n taskToCancel?.cancel()\n await logger?.info(\"Message loop task cancellation requested.\")\n\n // Disconnect the transport *before* awaiting the task\n // This should ensure the transport stream is finished, unblocking the loop.\n if let conn = connectionToDisconnect {\n await conn.disconnect()\n await logger?.info(\"Transport disconnected.\")\n } else {\n await logger?.info(\"No active transport connection to disconnect.\")\n }\n\n // Await the task completion *after* transport disconnect\n _ = await taskToCancel?.value\n await logger?.info(\"Client message loop task finished.\")\n\n await logger?.info(\"Client disconnect complete.\")\n }\n\n // MARK: - Registration\n\n /// Register a handler for a notification\n @discardableResult\n public func onNotification(\n _ type: N.Type,\n handler: @escaping @Sendable (Message) async throws -> Void\n ) async -> Self {\n let handlers = notificationHandlers[N.name, default: []]\n notificationHandlers[N.name] = handlers + [TypedNotificationHandler(handler)]\n return self\n }\n\n /// Send a notification to the server\n public func notify(_ notification: Message) async throws {\n guard let connection = connection else {\n throw MCPError.internalError(\"Client connection not initialized\")\n }\n\n let notificationData = try encoder.encode(notification)\n try await connection.send(notificationData)\n }\n\n // MARK: - Requests\n\n /// Send a request and receive its response\n public func send(_ request: Request) async throws -> M.Result {\n guard let connection = connection else {\n throw MCPError.internalError(\"Client connection not initialized\")\n }\n\n let requestData = try encoder.encode(request)\n\n // Store the pending request first\n return try await withCheckedThrowingContinuation { continuation in\n Task {\n // Add the pending request before attempting to send\n self.addPendingRequest(\n id: request.id,\n continuation: continuation,\n type: M.Result.self\n )\n\n // Send the request data\n do {\n // Use the existing connection send\n try await connection.send(requestData)\n } catch {\n // If send fails, try to remove the pending request.\n // Resume with the send error only if we successfully removed the request,\n // indicating the response handler hasn't processed it yet.\n if self.removePendingRequest(id: request.id) != nil {\n continuation.resume(throwing: error)\n }\n // Otherwise, the request was already removed by the response handler\n // or by disconnect, so the continuation was already resumed.\n // Do nothing here.\n }\n }\n }\n }\n\n private func addPendingRequest(\n id: ID,\n continuation: CheckedContinuation,\n type: T.Type // Keep type for AnyPendingRequest internal logic\n ) {\n pendingRequests[id] = AnyPendingRequest(PendingRequest(continuation: continuation))\n }\n\n private func removePendingRequest(id: ID) -> AnyPendingRequest? {\n return pendingRequests.removeValue(forKey: id)\n }\n\n // MARK: - Batching\n\n /// A batch of requests.\n ///\n /// Objects of this type are passed as an argument to the closure\n /// of the ``Client/withBatch(_:)`` method.\n public actor Batch {\n unowned let client: Client\n var requests: [AnyRequest] = []\n\n init(client: Client) {\n self.client = client\n }\n\n /// Adds a request to the batch and prepares its expected response task.\n /// The actual sending happens when the `withBatch` scope completes.\n /// - Returns: A `Task` that will eventually produce the result or throw an error.\n public func addRequest(_ request: Request) async throws -> Task<\n M.Result, Swift.Error\n > {\n requests.append(try AnyRequest(request))\n\n // Return a Task that registers the pending request and awaits its result.\n // The continuation is resumed when the response arrives.\n return Task {\n try await withCheckedThrowingContinuation { continuation in\n // We are already inside a Task, but need another Task\n // to bridge to the client actor's context.\n Task {\n await client.addPendingRequest(\n id: request.id,\n continuation: continuation,\n type: M.Result.self\n )\n }\n }\n }\n }\n }\n\n /// Executes multiple requests in a single batch.\n ///\n /// This method allows you to group multiple MCP requests together,\n /// which are then sent to the server as a single JSON array.\n /// The server processes these requests and sends back a corresponding\n /// JSON array of responses.\n ///\n /// Within the `body` closure, use the provided `Batch` actor to add\n /// requests using `batch.addRequest(_:)`. Each call to `addRequest`\n /// returns a `Task` handle representing the asynchronous operation\n /// for that specific request's result.\n ///\n /// It's recommended to collect these `Task` handles into an array\n /// within the `body` closure`. After the `withBatch` method returns\n /// (meaning the batch request has been sent), you can then process\n /// the results by awaiting each `Task` in the collected array.\n ///\n /// Example 1: Batching multiple tool calls and collecting typed tasks:\n /// ```swift\n /// // Array to hold the task handles for each tool call\n /// var toolTasks: [Task] = []\n /// try await client.withBatch { batch in\n /// for i in 0..<10 {\n /// toolTasks.append(\n /// try await batch.addRequest(\n /// CallTool.request(.init(name: \"square\", arguments: [\"n\": i]))\n /// )\n /// )\n /// }\n /// }\n ///\n /// // Process results after the batch is sent\n /// print(\"Processing \\(toolTasks.count) tool results...\")\n /// for (index, task) in toolTasks.enumerated() {\n /// do {\n /// let result = try await task.value\n /// print(\"\\(index): \\(result.content)\")\n /// } catch {\n /// print(\"\\(index) failed: \\(error)\")\n /// }\n /// }\n /// ```\n ///\n /// Example 2: Batching different request types and awaiting individual tasks:\n /// ```swift\n /// // Declare optional task variables beforehand\n /// var pingTask: Task?\n /// var promptTask: Task?\n ///\n /// try await client.withBatch { batch in\n /// // Assign the tasks within the batch closure\n /// pingTask = try await batch.addRequest(Ping.request())\n /// promptTask = try await batch.addRequest(GetPrompt.request(.init(name: \"greeting\")))\n /// }\n ///\n /// // Await the results after the batch is sent\n /// do {\n /// if let pingTask = pingTask {\n /// try await pingTask.value // Await ping result (throws if ping failed)\n /// print(\"Ping successful\")\n /// }\n /// if let promptTask = promptTask {\n /// let promptResult = try await promptTask.value // Await prompt result\n /// print(\"Prompt description: \\(promptResult.description ?? \"None\")\")\n /// }\n /// } catch {\n /// print(\"Error processing batch results: \\(error)\")\n /// }\n /// ```\n ///\n /// - Parameter body: An asynchronous closure that takes a `Batch` object as input.\n /// Use this object to add requests to the batch.\n /// - Throws: `MCPError.internalError` if the client is not connected.\n /// Can also rethrow errors from the `body` closure or from sending the batch request.\n public func withBatch(body: @escaping (Batch) async throws -> Void) async throws {\n guard let connection = connection else {\n throw MCPError.internalError(\"Client connection not initialized\")\n }\n\n // Create Batch actor, passing self (Client)\n let batch = Batch(client: self)\n\n // Populate the batch actor by calling the user's closure.\n try await body(batch)\n\n // Get the collected requests from the batch actor\n let requests = await batch.requests\n\n // Check if there are any requests to send\n guard !requests.isEmpty else {\n await logger?.info(\"Batch requested but no requests were added.\")\n return // Nothing to send\n }\n\n await logger?.debug(\n \"Sending batch request\", metadata: [\"count\": \"\\(requests.count)\"])\n\n // Encode the array of AnyMethod requests into a single JSON payload\n let data = try encoder.encode(requests)\n try await connection.send(data)\n\n // Responses will be handled asynchronously by the message loop and handleBatchResponse/handleResponse.\n }\n\n // MARK: - Lifecycle\n\n /// Initialize the connection with the server.\n ///\n /// - Important: This method is deprecated. Initialization now happens automatically\n /// when calling `connect(transport:)`. You should use that method instead.\n ///\n /// - Returns: The server's initialization response containing capabilities and server info\n @available(\n *, deprecated,\n message:\n \"Initialization now happens automatically during connect. Use connect(transport:) instead.\"\n )\n public func initialize() async throws -> Initialize.Result {\n return try await _initialize()\n }\n\n /// Internal initialization implementation\n private func _initialize() async throws -> Initialize.Result {\n let request = Initialize.request(\n .init(\n protocolVersion: Version.latest,\n capabilities: capabilities,\n clientInfo: clientInfo\n ))\n\n let result = try await send(request)\n\n self.serverCapabilities = result.capabilities\n self.serverVersion = result.protocolVersion\n self.instructions = result.instructions\n\n try await notify(InitializedNotification.message())\n\n return result\n }\n\n public func ping() async throws {\n let request = Ping.request()\n _ = try await send(request)\n }\n\n // MARK: - Prompts\n\n public func getPrompt(name: String, arguments: [String: Value]? = nil) async throws\n -> (description: String?, messages: [Prompt.Message])\n {\n try validateServerCapability(\\.prompts, \"Prompts\")\n let request = GetPrompt.request(.init(name: name, arguments: arguments))\n let result = try await send(request)\n return (description: result.description, messages: result.messages)\n }\n\n public func listPrompts(cursor: String? = nil) async throws\n -> (prompts: [Prompt], nextCursor: String?)\n {\n try validateServerCapability(\\.prompts, \"Prompts\")\n let request: Request\n if let cursor = cursor {\n request = ListPrompts.request(.init(cursor: cursor))\n } else {\n request = ListPrompts.request(.init())\n }\n let result = try await send(request)\n return (prompts: result.prompts, nextCursor: result.nextCursor)\n }\n\n // MARK: - Resources\n\n public func readResource(uri: String) async throws -> [Resource.Content] {\n try validateServerCapability(\\.resources, \"Resources\")\n let request = ReadResource.request(.init(uri: uri))\n let result = try await send(request)\n return result.contents\n }\n\n public func listResources(cursor: String? = nil) async throws -> (\n resources: [Resource], nextCursor: String?\n ) {\n try validateServerCapability(\\.resources, \"Resources\")\n let request: Request\n if let cursor = cursor {\n request = ListResources.request(.init(cursor: cursor))\n } else {\n request = ListResources.request(.init())\n }\n let result = try await send(request)\n return (resources: result.resources, nextCursor: result.nextCursor)\n }\n\n public func subscribeToResource(uri: String) async throws {\n try validateServerCapability(\\.resources?.subscribe, \"Resource subscription\")\n let request = ResourceSubscribe.request(.init(uri: uri))\n _ = try await send(request)\n }\n\n public func listResourceTemplates(cursor: String? = nil) async throws -> (\n templates: [Resource.Template], nextCursor: String?\n ) {\n try validateServerCapability(\\.resources, \"Resources\")\n let request: Request\n if let cursor = cursor {\n request = ListResourceTemplates.request(.init(cursor: cursor))\n } else {\n request = ListResourceTemplates.request(.init())\n }\n let result = try await send(request)\n return (templates: result.templates, nextCursor: result.nextCursor)\n }\n\n // MARK: - Tools\n\n public func listTools(cursor: String? = nil) async throws -> (\n tools: [Tool], nextCursor: String?\n ) {\n try validateServerCapability(\\.tools, \"Tools\")\n let request: Request\n if let cursor = cursor {\n request = ListTools.request(.init(cursor: cursor))\n } else {\n request = ListTools.request(.init())\n }\n let result = try await send(request)\n return (tools: result.tools, nextCursor: result.nextCursor)\n }\n\n public func callTool(name: String, arguments: [String: Value]? = nil) async throws -> (\n content: [Tool.Content], isError: Bool?\n ) {\n try validateServerCapability(\\.tools, \"Tools\")\n let request = CallTool.request(.init(name: name, arguments: arguments))\n let result = try await send(request)\n return (content: result.content, isError: result.isError)\n }\n\n // MARK: - Sampling\n\n /// Register a handler for sampling requests from servers\n ///\n /// Sampling allows servers to request LLM completions through the client,\n /// enabling sophisticated agentic behaviors while maintaining human-in-the-loop control.\n ///\n /// The sampling flow follows these steps:\n /// 1. Server sends a `sampling/createMessage` request to the client\n /// 2. Client reviews the request and can modify it (via this handler)\n /// 3. Client samples from an LLM (via this handler)\n /// 4. Client reviews the completion (via this handler)\n /// 5. Client returns the result to the server\n ///\n /// - Parameter handler: A closure that processes sampling requests and returns completions\n /// - Returns: Self for method chaining\n /// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/sampling#how-sampling-works\n @discardableResult\n public func withSamplingHandler(\n _ handler: @escaping @Sendable (CreateSamplingMessage.Parameters) async throws ->\n CreateSamplingMessage.Result\n ) -> Self {\n // Note: This would require extending the client architecture to handle incoming requests from servers.\n // The current MCP Swift SDK architecture assumes clients only send requests to servers,\n // but sampling requires bidirectional communication where servers can send requests to clients.\n //\n // A full implementation would need:\n // 1. Request handlers in the client (similar to how servers handle requests)\n // 2. Bidirectional transport support\n // 3. Request/response correlation for server-to-client requests\n //\n // For now, this serves as the correct API design for when bidirectional support is added.\n\n // This would register the handler similar to how servers register method handlers:\n // methodHandlers[CreateSamplingMessage.name] = TypedRequestHandler(handler)\n\n return self\n }\n\n // MARK: -\n\n private func handleResponse(_ response: Response) async {\n await logger?.trace(\n \"Processing response\",\n metadata: [\"id\": \"\\(response.id)\"])\n\n // Attempt to remove the pending request using the response ID.\n // Resume with the response only if it hadn't yet been removed.\n if let removedRequest = self.removePendingRequest(id: response.id) {\n // If we successfully removed it, resume its continuation.\n switch response.result {\n case .success(let value):\n removedRequest.resume(returning: value)\n case .failure(let error):\n removedRequest.resume(throwing: error)\n }\n } else {\n // Request was already removed (e.g., by send error handler or disconnect).\n // Log this, but it's not an error in race condition scenarios.\n await logger?.warning(\n \"Attempted to handle response for already removed request\",\n metadata: [\"id\": \"\\(response.id)\"]\n )\n }\n }\n\n private func handleMessage(_ message: Message) async {\n await logger?.trace(\n \"Processing notification\",\n metadata: [\"method\": \"\\(message.method)\"])\n\n // Find notification handlers for this method\n guard let handlers = notificationHandlers[message.method] else { return }\n\n // Convert notification parameters to concrete type and call handlers\n for handler in handlers {\n do {\n try await handler(message)\n } catch {\n await logger?.error(\n \"Error handling notification\",\n metadata: [\n \"method\": \"\\(message.method)\",\n \"error\": \"\\(error)\",\n ])\n }\n }\n }\n\n // MARK: -\n\n /// Validate the server capabilities.\n /// Throws an error if the client is configured to be strict and the capability is not supported.\n private func validateServerCapability(\n _ keyPath: KeyPath,\n _ name: String\n )\n throws\n {\n if configuration.strict {\n guard let capabilities = serverCapabilities else {\n throw MCPError.methodNotFound(\"Server capabilities not initialized\")\n }\n guard capabilities[keyPath: keyPath] != nil else {\n throw MCPError.methodNotFound(\"\\(name) is not supported by the server\")\n }\n }\n }\n\n // Add handler for batch responses\n private func handleBatchResponse(_ responses: [AnyResponse]) async {\n await logger?.trace(\"Processing batch response\", metadata: [\"count\": \"\\(responses.count)\"])\n for response in responses {\n // Attempt to remove the pending request.\n // If successful, pendingRequest contains the request.\n if let pendingRequest = self.removePendingRequest(id: response.id) {\n // If we successfully removed it, handle the response using the pending request.\n switch response.result {\n case .success(let value):\n pendingRequest.resume(returning: value)\n case .failure(let error):\n pendingRequest.resume(throwing: error)\n }\n } else {\n // If removal failed, it means the request ID was not found (or already handled).\n // Log a warning.\n await logger?.warning(\n \"Received response in batch for unknown or already handled request ID\",\n metadata: [\"id\": \"\\(response.id)\"]\n )\n }\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Server/Server.swift", "import Logging\n\nimport struct Foundation.Data\nimport struct Foundation.Date\nimport class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\n/// Model Context Protocol server\npublic actor Server {\n /// The server configuration\n public struct Configuration: Hashable, Codable, Sendable {\n /// The default configuration.\n public static let `default` = Configuration(strict: false)\n\n /// The strict configuration.\n public static let strict = Configuration(strict: true)\n\n /// When strict mode is enabled, the server:\n /// - Requires clients to send an initialize request before any other requests\n /// - Rejects all requests from uninitialized clients with a protocol error\n ///\n /// While the MCP specification requires clients to initialize the connection\n /// before sending other requests, some implementations may not follow this.\n /// Disabling strict mode allows the server to be more lenient with non-compliant\n /// clients, though this may lead to undefined behavior.\n public var strict: Bool\n }\n\n /// Implementation information\n public struct Info: Hashable, Codable, Sendable {\n /// The server name\n public let name: String\n /// The server version\n public let version: String\n\n public init(name: String, version: String) {\n self.name = name\n self.version = version\n }\n }\n\n /// Server capabilities\n public struct Capabilities: Hashable, Codable, Sendable {\n /// Resources capabilities\n public struct Resources: Hashable, Codable, Sendable {\n /// Whether the resource can be subscribed to\n public var subscribe: Bool?\n /// Whether the list of resources has changed\n public var listChanged: Bool?\n\n public init(\n subscribe: Bool? = nil,\n listChanged: Bool? = nil\n ) {\n self.subscribe = subscribe\n self.listChanged = listChanged\n }\n }\n\n /// Tools capabilities\n public struct Tools: Hashable, Codable, Sendable {\n /// Whether the server notifies clients when tools change\n public var listChanged: Bool?\n\n public init(listChanged: Bool? = nil) {\n self.listChanged = listChanged\n }\n }\n\n /// Prompts capabilities\n public struct Prompts: Hashable, Codable, Sendable {\n /// Whether the server notifies clients when prompts change\n public var listChanged: Bool?\n\n public init(listChanged: Bool? = nil) {\n self.listChanged = listChanged\n }\n }\n\n /// Logging capabilities\n public struct Logging: Hashable, Codable, Sendable {\n public init() {}\n }\n\n /// Sampling capabilities\n public struct Sampling: Hashable, Codable, Sendable {\n public init() {}\n }\n\n /// Logging capabilities\n public var logging: Logging?\n /// Prompts capabilities\n public var prompts: Prompts?\n /// Resources capabilities\n public var resources: Resources?\n /// Sampling capabilities\n public var sampling: Sampling?\n /// Tools capabilities\n public var tools: Tools?\n\n public init(\n logging: Logging? = nil,\n prompts: Prompts? = nil,\n resources: Resources? = nil,\n sampling: Sampling? = nil,\n tools: Tools? = nil\n ) {\n self.logging = logging\n self.prompts = prompts\n self.resources = resources\n self.sampling = sampling\n self.tools = tools\n }\n }\n\n /// Server information\n private let serverInfo: Server.Info\n /// The server connection\n private var connection: (any Transport)?\n /// The server logger\n private var logger: Logger? {\n get async {\n await connection?.logger\n }\n }\n\n /// The server name\n public nonisolated var name: String { serverInfo.name }\n /// The server version\n public nonisolated var version: String { serverInfo.version }\n /// The server capabilities\n public var capabilities: Capabilities\n /// The server configuration\n public var configuration: Configuration\n\n /// Request handlers\n private var methodHandlers: [String: RequestHandlerBox] = [:]\n /// Notification handlers\n private var notificationHandlers: [String: [NotificationHandlerBox]] = [:]\n\n /// Whether the server is initialized\n private var isInitialized = false\n /// The client information\n private var clientInfo: Client.Info?\n /// The client capabilities\n private var clientCapabilities: Client.Capabilities?\n /// The protocol version\n private var protocolVersion: String?\n /// The list of subscriptions\n private var subscriptions: [String: Set] = [:]\n /// The task for the message handling loop\n private var task: Task?\n\n public init(\n name: String,\n version: String,\n capabilities: Server.Capabilities = .init(),\n configuration: Configuration = .default\n ) {\n self.serverInfo = Server.Info(name: name, version: version)\n self.capabilities = capabilities\n self.configuration = configuration\n }\n\n /// Start the server\n /// - Parameters:\n /// - transport: The transport to use for the server\n /// - initializeHook: An optional hook that runs when the client sends an initialize request\n public func start(\n transport: any Transport,\n initializeHook: (@Sendable (Client.Info, Client.Capabilities) async throws -> Void)? = nil\n ) async throws {\n self.connection = transport\n registerDefaultHandlers(initializeHook: initializeHook)\n try await transport.connect()\n\n await logger?.info(\n \"Server started\", metadata: [\"name\": \"\\(name)\", \"version\": \"\\(version)\"])\n\n // Start message handling loop\n task = Task {\n do {\n let stream = await transport.receive()\n for try await data in stream {\n if Task.isCancelled { break } // Check cancellation inside loop\n\n var requestID: ID?\n do {\n // Attempt to decode as batch first, then as individual request or notification\n let decoder = JSONDecoder()\n if let batch = try? decoder.decode(Server.Batch.self, from: data) {\n try await handleBatch(batch)\n } else if let request = try? decoder.decode(AnyRequest.self, from: data) {\n _ = try await handleRequest(request, sendResponse: true)\n } else if let message = try? decoder.decode(AnyMessage.self, from: data) {\n try await handleMessage(message)\n } else {\n // Try to extract request ID from raw JSON if possible\n if let json = try? JSONDecoder().decode(\n [String: Value].self, from: data),\n let idValue = json[\"id\"]\n {\n if let strValue = idValue.stringValue {\n requestID = .string(strValue)\n } else if let intValue = idValue.intValue {\n requestID = .number(intValue)\n }\n }\n throw MCPError.parseError(\"Invalid message format\")\n }\n } catch let error where MCPError.isResourceTemporarilyUnavailable(error) {\n // Resource temporarily unavailable, retry after a short delay\n try? await Task.sleep(for: .milliseconds(10))\n continue\n } catch {\n await logger?.error(\n \"Error processing message\", metadata: [\"error\": \"\\(error)\"])\n let response = AnyMethod.response(\n id: requestID ?? .random,\n error: error as? MCPError\n ?? MCPError.internalError(error.localizedDescription)\n )\n try? await send(response)\n }\n }\n } catch {\n await logger?.error(\n \"Fatal error in message handling loop\", metadata: [\"error\": \"\\(error)\"])\n }\n await logger?.info(\"Server finished\", metadata: [:])\n }\n }\n\n /// Stop the server\n public func stop() async {\n task?.cancel()\n task = nil\n if let connection = connection {\n await connection.disconnect()\n }\n connection = nil\n }\n\n public func waitUntilCompleted() async {\n await task?.value\n }\n\n // MARK: - Registration\n\n /// Register a method handler\n @discardableResult\n public func withMethodHandler(\n _ type: M.Type,\n handler: @escaping @Sendable (M.Parameters) async throws -> M.Result\n ) -> Self {\n methodHandlers[M.name] = TypedRequestHandler { (request: Request) -> Response in\n let result = try await handler(request.params)\n return Response(id: request.id, result: result)\n }\n return self\n }\n\n /// Register a notification handler\n @discardableResult\n public func onNotification(\n _ type: N.Type,\n handler: @escaping @Sendable (Message) async throws -> Void\n ) -> Self {\n let handlers = notificationHandlers[N.name, default: []]\n notificationHandlers[N.name] = handlers + [TypedNotificationHandler(handler)]\n return self\n }\n\n // MARK: - Sending\n\n /// Send a response to a request\n public func send(_ response: Response) async throws {\n guard let connection = connection else {\n throw MCPError.internalError(\"Server connection not initialized\")\n }\n\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]\n\n let responseData = try encoder.encode(response)\n try await connection.send(responseData)\n }\n\n /// Send a notification to connected clients\n public func notify(_ notification: Message) async throws {\n guard let connection = connection else {\n throw MCPError.internalError(\"Server connection not initialized\")\n }\n\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]\n\n let notificationData = try encoder.encode(notification)\n try await connection.send(notificationData)\n }\n\n // MARK: - Sampling\n\n /// Request sampling from the connected client\n ///\n /// Sampling allows servers to request LLM completions through the client,\n /// enabling sophisticated agentic behaviors while maintaining human-in-the-loop control.\n ///\n /// The sampling flow follows these steps:\n /// 1. Server sends a `sampling/createMessage` request to the client\n /// 2. Client reviews the request and can modify it\n /// 3. Client samples from an LLM\n /// 4. Client reviews the completion\n /// 5. Client returns the result to the server\n ///\n /// - Parameters:\n /// - messages: The conversation history to send to the LLM\n /// - modelPreferences: Model selection preferences\n /// - systemPrompt: Optional system prompt\n /// - includeContext: What MCP context to include\n /// - temperature: Controls randomness (0.0 to 1.0)\n /// - maxTokens: Maximum tokens to generate\n /// - stopSequences: Array of sequences that stop generation\n /// - metadata: Additional provider-specific parameters\n /// - Returns: The sampling result containing the model used, stop reason, role, and content\n /// - Throws: MCPError if the request fails\n /// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/sampling#how-sampling-works\n public func requestSampling(\n messages: [Sampling.Message],\n modelPreferences: Sampling.ModelPreferences? = nil,\n systemPrompt: String? = nil,\n includeContext: Sampling.ContextInclusion? = nil,\n temperature: Double? = nil,\n maxTokens: Int,\n stopSequences: [String]? = nil,\n metadata: [String: Value]? = nil\n ) async throws -> CreateSamplingMessage.Result {\n guard connection != nil else {\n throw MCPError.internalError(\"Server connection not initialized\")\n }\n\n // Note: This is a conceptual implementation. The actual implementation would require\n // bidirectional communication support in the transport layer, allowing servers to\n // send requests to clients and receive responses.\n\n _ = CreateSamplingMessage.request(\n .init(\n messages: messages,\n modelPreferences: modelPreferences,\n systemPrompt: systemPrompt,\n includeContext: includeContext,\n temperature: temperature,\n maxTokens: maxTokens,\n stopSequences: stopSequences,\n metadata: metadata\n )\n )\n\n // This would need to be implemented with proper request/response handling\n // similar to how the client sends requests to servers\n throw MCPError.internalError(\n \"Bidirectional sampling requests not yet implemented in transport layer\")\n }\n\n /// A JSON-RPC batch containing multiple requests and/or notifications\n struct Batch: Sendable {\n /// An item in a JSON-RPC batch\n enum Item: Sendable {\n case request(Request)\n case notification(Message)\n\n }\n\n var items: [Item]\n\n init(items: [Item]) {\n self.items = items\n }\n }\n\n /// Process a batch of requests and/or notifications\n private func handleBatch(_ batch: Batch) async throws {\n await logger?.trace(\"Processing batch request\", metadata: [\"size\": \"\\(batch.items.count)\"])\n\n if batch.items.isEmpty {\n // Empty batch is invalid according to JSON-RPC spec\n let error = MCPError.invalidRequest(\"Batch array must not be empty\")\n let response = AnyMethod.response(id: .random, error: error)\n try await send(response)\n return\n }\n\n // Process each item in the batch and collect responses\n var responses: [Response] = []\n\n for item in batch.items {\n do {\n switch item {\n case .request(let request):\n // For batched requests, collect responses instead of sending immediately\n if let response = try await handleRequest(request, sendResponse: false) {\n responses.append(response)\n }\n\n case .notification(let notification):\n // Handle notification (no response needed)\n try await handleMessage(notification)\n }\n } catch {\n // Only add errors to response for requests (notifications don't have responses)\n if case .request(let request) = item {\n let mcpError =\n error as? MCPError ?? MCPError.internalError(error.localizedDescription)\n responses.append(AnyMethod.response(id: request.id, error: mcpError))\n }\n }\n }\n\n // Send collected responses if any\n if !responses.isEmpty {\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]\n let responseData = try encoder.encode(responses)\n\n guard let connection = connection else {\n throw MCPError.internalError(\"Server connection not initialized\")\n }\n\n try await connection.send(responseData)\n }\n }\n\n // MARK: - Request and Message Handling\n\n /// Handle a request and either send the response immediately or return it\n ///\n /// - Parameters:\n /// - request: The request to handle\n /// - sendResponse: Whether to send the response immediately (true) or return it (false)\n /// - Returns: The response when sendResponse is false\n private func handleRequest(_ request: Request, sendResponse: Bool = true)\n async throws -> Response?\n {\n // Check if this is a pre-processed error request (empty method)\n if request.method.isEmpty && !sendResponse {\n // This is a placeholder for an invalid request that couldn't be parsed in batch mode\n return AnyMethod.response(\n id: request.id,\n error: MCPError.invalidRequest(\"Invalid batch item format\")\n )\n }\n\n await logger?.trace(\n \"Processing request\",\n metadata: [\n \"method\": \"\\(request.method)\",\n \"id\": \"\\(request.id)\",\n ])\n\n if configuration.strict {\n // The client SHOULD NOT send requests other than pings\n // before the server has responded to the initialize request.\n switch request.method {\n case Initialize.name, Ping.name:\n break\n default:\n try checkInitialized()\n }\n }\n\n // Find handler for method name\n guard let handler = methodHandlers[request.method] else {\n let error = MCPError.methodNotFound(\"Unknown method: \\(request.method)\")\n let response = AnyMethod.response(id: request.id, error: error)\n\n if sendResponse {\n try await send(response)\n return nil\n }\n\n return response\n }\n\n do {\n // Handle request and get response\n let response = try await handler(request)\n\n if sendResponse {\n try await send(response)\n return nil\n }\n\n return response\n } catch {\n let mcpError = error as? MCPError ?? MCPError.internalError(error.localizedDescription)\n let response = AnyMethod.response(id: request.id, error: mcpError)\n\n if sendResponse {\n try await send(response)\n return nil\n }\n\n return response\n }\n }\n\n private func handleMessage(_ message: Message) async throws {\n await logger?.trace(\n \"Processing notification\",\n metadata: [\"method\": \"\\(message.method)\"])\n\n if configuration.strict {\n // Check initialization state unless this is an initialized notification\n if message.method != InitializedNotification.name {\n try checkInitialized()\n }\n }\n\n // Find notification handlers for this method\n guard let handlers = notificationHandlers[message.method] else { return }\n\n // Convert notification parameters to concrete type and call handlers\n for handler in handlers {\n do {\n try await handler(message)\n } catch {\n await logger?.error(\n \"Error handling notification\",\n metadata: [\n \"method\": \"\\(message.method)\",\n \"error\": \"\\(error)\",\n ])\n }\n }\n }\n\n private func checkInitialized() throws {\n guard isInitialized else {\n throw MCPError.invalidRequest(\"Server is not initialized\")\n }\n }\n\n private func registerDefaultHandlers(\n initializeHook: (@Sendable (Client.Info, Client.Capabilities) async throws -> Void)?\n ) {\n // Initialize\n withMethodHandler(Initialize.self) { [weak self] params in\n guard let self = self else {\n throw MCPError.internalError(\"Server was deallocated\")\n }\n\n guard await !self.isInitialized else {\n throw MCPError.invalidRequest(\"Server is already initialized\")\n }\n\n // Call initialization hook if registered\n if let hook = initializeHook {\n try await hook(params.clientInfo, params.capabilities)\n }\n\n // Perform version negotiation\n let clientRequestedVersion = params.protocolVersion\n let negotiatedProtocolVersion = Version.negotiate(\n clientRequestedVersion: clientRequestedVersion)\n\n // Set initial state with the negotiated protocol version\n await self.setInitialState(\n clientInfo: params.clientInfo,\n clientCapabilities: params.capabilities,\n protocolVersion: negotiatedProtocolVersion\n )\n\n return Initialize.Result(\n protocolVersion: negotiatedProtocolVersion,\n capabilities: await self.capabilities,\n serverInfo: self.serverInfo,\n instructions: nil\n )\n }\n\n // Ping\n withMethodHandler(Ping.self) { _ in return Empty() }\n }\n\n private func setInitialState(\n clientInfo: Client.Info,\n clientCapabilities: Client.Capabilities,\n protocolVersion: String\n ) async {\n self.clientInfo = clientInfo\n self.clientCapabilities = clientCapabilities\n self.protocolVersion = protocolVersion\n self.isInitialized = true\n }\n}\n\nextension Server.Batch: Codable {\n init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n\n let encoder = JSONEncoder()\n let decoder = JSONDecoder()\n\n var items: [Item] = []\n for item in try container.decode([Value].self) {\n let data = try encoder.encode(item)\n try items.append(decoder.decode(Item.self, from: data))\n }\n\n self.items = items\n }\n\n func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n try container.encode(items)\n }\n}\n\nextension Server.Batch.Item: Codable {\n private enum CodingKeys: String, CodingKey {\n case id\n }\n\n init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n // Check if it's a request (has id) or notification (no id)\n if container.contains(.id) {\n self = .request(try Request(from: decoder))\n } else {\n self = .notification(try Message(from: decoder))\n }\n }\n\n func encode(to encoder: Encoder) throws {\n switch self {\n case .request(let request):\n try request.encode(to: encoder)\n case .notification(let notification):\n try notification.encode(to: encoder)\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Error.swift", "import Foundation\n\n#if canImport(System)\n import System\n#else\n @preconcurrency import SystemPackage\n#endif\n\n/// A model context protocol error.\npublic enum MCPError: Swift.Error, Sendable {\n // Standard JSON-RPC 2.0 errors (-32700 to -32603)\n case parseError(String?) // -32700\n case invalidRequest(String?) // -32600\n case methodNotFound(String?) // -32601\n case invalidParams(String?) // -32602\n case internalError(String?) // -32603\n\n // Server errors (-32000 to -32099)\n case serverError(code: Int, message: String)\n\n // Transport specific errors\n case connectionClosed\n case transportError(Swift.Error)\n\n /// The JSON-RPC 2.0 error code\n public var code: Int {\n switch self {\n case .parseError: return -32700\n case .invalidRequest: return -32600\n case .methodNotFound: return -32601\n case .invalidParams: return -32602\n case .internalError: return -32603\n case .serverError(let code, _): return code\n case .connectionClosed: return -32000\n case .transportError: return -32001\n }\n }\n\n /// Check if an error represents a \"resource temporarily unavailable\" condition\n public static func isResourceTemporarilyUnavailable(_ error: Swift.Error) -> Bool {\n #if canImport(System)\n if let errno = error as? System.Errno, errno == .resourceTemporarilyUnavailable {\n return true\n }\n #else\n if let errno = error as? SystemPackage.Errno, errno == .resourceTemporarilyUnavailable {\n return true\n }\n #endif\n return false\n }\n}\n\n// MARK: LocalizedError\n\nextension MCPError: LocalizedError {\n public var errorDescription: String? {\n switch self {\n case .parseError(let detail):\n return \"Parse error: Invalid JSON\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .invalidRequest(let detail):\n return \"Invalid Request\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .methodNotFound(let detail):\n return \"Method not found\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .invalidParams(let detail):\n return \"Invalid params\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .internalError(let detail):\n return \"Internal error\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .serverError(_, let message):\n return \"Server error: \\(message)\"\n case .connectionClosed:\n return \"Connection closed\"\n case .transportError(let error):\n return \"Transport error: \\(error.localizedDescription)\"\n }\n }\n\n public var failureReason: String? {\n switch self {\n case .parseError:\n return \"The server received invalid JSON that could not be parsed\"\n case .invalidRequest:\n return \"The JSON sent is not a valid Request object\"\n case .methodNotFound:\n return \"The method does not exist or is not available\"\n case .invalidParams:\n return \"Invalid method parameter(s)\"\n case .internalError:\n return \"Internal JSON-RPC error\"\n case .serverError:\n return \"Server-defined error occurred\"\n case .connectionClosed:\n return \"The connection to the server was closed\"\n case .transportError(let error):\n return (error as? LocalizedError)?.failureReason ?? error.localizedDescription\n }\n }\n\n public var recoverySuggestion: String? {\n switch self {\n case .parseError:\n return \"Verify that the JSON being sent is valid and well-formed\"\n case .invalidRequest:\n return \"Ensure the request follows the JSON-RPC 2.0 specification format\"\n case .methodNotFound:\n return \"Check the method name and ensure it is supported by the server\"\n case .invalidParams:\n return \"Verify the parameters match the method's expected parameters\"\n case .connectionClosed:\n return \"Try reconnecting to the server\"\n default:\n return nil\n }\n }\n}\n\n// MARK: CustomDebugStringConvertible\n\nextension MCPError: CustomDebugStringConvertible {\n public var debugDescription: String {\n switch self {\n case .transportError(let error):\n return\n \"[\\(code)] \\(errorDescription ?? \"\") (Underlying error: \\(String(reflecting: error)))\"\n default:\n return \"[\\(code)] \\(errorDescription ?? \"\")\"\n }\n }\n\n}\n\n// MARK: Codable\n\nextension MCPError: Codable {\n private enum CodingKeys: String, CodingKey {\n case code, message, data\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(code, forKey: .code)\n try container.encode(errorDescription ?? \"Unknown error\", forKey: .message)\n\n // Encode additional data if available\n switch self {\n case .parseError(let detail),\n .invalidRequest(let detail),\n .methodNotFound(let detail),\n .invalidParams(let detail),\n .internalError(let detail):\n if let detail = detail {\n try container.encode([\"detail\": detail], forKey: .data)\n }\n case .serverError(_, _):\n // No additional data for server errors\n break\n case .connectionClosed:\n break\n case .transportError(let error):\n try container.encode(\n [\"error\": error.localizedDescription],\n forKey: .data\n )\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let code = try container.decode(Int.self, forKey: .code)\n let message = try container.decode(String.self, forKey: .message)\n let data = try container.decodeIfPresent([String: Value].self, forKey: .data)\n\n // Helper to extract detail from data, falling back to message if needed\n let unwrapDetail: (String?) -> String? = { fallback in\n guard let detailValue = data?[\"detail\"] else { return fallback }\n if case .string(let str) = detailValue { return str }\n return fallback\n }\n\n switch code {\n case -32700:\n self = .parseError(unwrapDetail(message))\n case -32600:\n self = .invalidRequest(unwrapDetail(message))\n case -32601:\n self = .methodNotFound(unwrapDetail(message))\n case -32602:\n self = .invalidParams(unwrapDetail(message))\n case -32603:\n self = .internalError(unwrapDetail(nil))\n case -32000:\n self = .connectionClosed\n case -32001:\n // Extract underlying error string if present\n let underlyingErrorString =\n data?[\"error\"].flatMap { val -> String? in\n if case .string(let str) = val { return str }\n return nil\n } ?? message\n self = .transportError(\n NSError(\n domain: \"org.jsonrpc.error\",\n code: code,\n userInfo: [NSLocalizedDescriptionKey: underlyingErrorString]\n )\n )\n default:\n self = .serverError(code: code, message: message)\n }\n }\n}\n\n// MARK: Equatable\n\nextension MCPError: Equatable {\n public static func == (lhs: MCPError, rhs: MCPError) -> Bool {\n lhs.code == rhs.code\n }\n}\n\n// MARK: Hashable\n\nextension MCPError: Hashable {\n public func hash(into hasher: inout Hasher) {\n hasher.combine(code)\n switch self {\n case .parseError(let detail):\n hasher.combine(detail)\n case .invalidRequest(let detail):\n hasher.combine(detail)\n case .methodNotFound(let detail):\n hasher.combine(detail)\n case .invalidParams(let detail):\n hasher.combine(detail)\n case .internalError(let detail):\n hasher.combine(detail)\n case .serverError(_, let message):\n hasher.combine(message)\n case .connectionClosed:\n break\n case .transportError(let error):\n hasher.combine(error.localizedDescription)\n }\n }\n}\n\n// MARK: -\n\n/// This is provided to allow existing code that uses `MCP.Error` to continue\n/// to work without modification.\n///\n/// The MCPError type is now the recommended way to handle errors in MCP.\n@available(*, deprecated, renamed: \"MCPError\", message: \"Use MCPError instead of MCP.Error\")\npublic typealias Error = MCPError\n"], ["/swift-sdk/Sources/MCP/Base/Messages.swift", "import class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\nprivate let jsonrpc = \"2.0\"\n\npublic protocol NotRequired {\n init()\n}\n\npublic struct Empty: NotRequired, Hashable, Codable, Sendable {\n public init() {}\n}\n\nextension Value: NotRequired {\n public init() {\n self = .null\n }\n}\n\n// MARK: -\n\n/// A method that can be used to send requests and receive responses.\npublic protocol Method {\n /// The parameters of the method.\n associatedtype Parameters: Codable, Hashable, Sendable = Empty\n /// The result of the method.\n associatedtype Result: Codable, Hashable, Sendable = Empty\n /// The name of the method.\n static var name: String { get }\n}\n\n/// Type-erased method for request/response handling\nstruct AnyMethod: Method, Sendable {\n static var name: String { \"\" }\n typealias Parameters = Value\n typealias Result = Value\n}\n\nextension Method where Parameters == Empty {\n public static func request(id: ID = .random) -> Request {\n Request(id: id, method: name, params: Empty())\n }\n}\n\nextension Method where Result == Empty {\n public static func response(id: ID) -> Response {\n Response(id: id, result: Empty())\n }\n}\n\nextension Method {\n /// Create a request with the given parameters.\n public static func request(id: ID = .random, _ parameters: Self.Parameters) -> Request {\n Request(id: id, method: name, params: parameters)\n }\n\n /// Create a response with the given result.\n public static func response(id: ID, result: Self.Result) -> Response {\n Response(id: id, result: result)\n }\n\n /// Create a response with the given error.\n public static func response(id: ID, error: MCPError) -> Response {\n Response(id: id, error: error)\n }\n}\n\n// MARK: -\n\n/// A request message.\npublic struct Request: Hashable, Identifiable, Codable, Sendable {\n /// The request ID.\n public let id: ID\n /// The method name.\n public let method: String\n /// The request parameters.\n public let params: M.Parameters\n\n init(id: ID = .random, method: String, params: M.Parameters) {\n self.id = id\n self.method = method\n self.params = params\n }\n\n private enum CodingKeys: String, CodingKey {\n case jsonrpc, id, method, params\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(jsonrpc, forKey: .jsonrpc)\n try container.encode(id, forKey: .id)\n try container.encode(method, forKey: .method)\n try container.encode(params, forKey: .params)\n }\n}\n\nextension Request {\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let version = try container.decode(String.self, forKey: .jsonrpc)\n guard version == jsonrpc else {\n throw DecodingError.dataCorruptedError(\n forKey: .jsonrpc, in: container, debugDescription: \"Invalid JSON-RPC version\")\n }\n id = try container.decode(ID.self, forKey: .id)\n method = try container.decode(String.self, forKey: .method)\n\n if M.Parameters.self is NotRequired.Type {\n // For NotRequired parameters, use decodeIfPresent or init()\n params =\n (try container.decodeIfPresent(M.Parameters.self, forKey: .params)\n ?? (M.Parameters.self as! NotRequired.Type).init() as! M.Parameters)\n } else if let value = try? container.decode(M.Parameters.self, forKey: .params) {\n // If params exists and can be decoded, use it\n params = value\n } else if !container.contains(.params)\n || (try? container.decodeNil(forKey: .params)) == true\n {\n // If params is missing or explicitly null, use Empty for Empty parameters\n // or throw for non-Empty parameters\n if M.Parameters.self == Empty.self {\n params = Empty() as! M.Parameters\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Missing required params field\"))\n }\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Invalid params field\"))\n }\n }\n}\n\n/// A type-erased request for request/response handling\ntypealias AnyRequest = Request\n\nextension AnyRequest {\n init(_ request: Request) throws {\n let encoder = JSONEncoder()\n let decoder = JSONDecoder()\n\n let data = try encoder.encode(request)\n self = try decoder.decode(AnyRequest.self, from: data)\n }\n}\n\n/// A box for request handlers that can be type-erased\nclass RequestHandlerBox: @unchecked Sendable {\n func callAsFunction(_ request: AnyRequest) async throws -> AnyResponse {\n fatalError(\"Must override\")\n }\n}\n\n/// A typed request handler that can be used to handle requests of a specific type\nfinal class TypedRequestHandler: RequestHandlerBox, @unchecked Sendable {\n private let _handle: @Sendable (Request) async throws -> Response\n\n init(_ handler: @escaping @Sendable (Request) async throws -> Response) {\n self._handle = handler\n super.init()\n }\n\n override func callAsFunction(_ request: AnyRequest) async throws -> AnyResponse {\n let encoder = JSONEncoder()\n let decoder = JSONDecoder()\n\n // Create a concrete request from the type-erased one\n let data = try encoder.encode(request)\n let request = try decoder.decode(Request.self, from: data)\n\n // Handle with concrete type\n let response = try await _handle(request)\n\n // Convert result to AnyMethod response\n switch response.result {\n case .success(let result):\n let resultData = try encoder.encode(result)\n let resultValue = try decoder.decode(Value.self, from: resultData)\n return Response(id: response.id, result: resultValue)\n case .failure(let error):\n return Response(id: response.id, error: error)\n }\n }\n}\n\n// MARK: -\n\n/// A response message.\npublic struct Response: Hashable, Identifiable, Codable, Sendable {\n /// The response ID.\n public let id: ID\n /// The response result.\n public let result: Swift.Result\n\n public init(id: ID, result: M.Result) {\n self.id = id\n self.result = .success(result)\n }\n\n public init(id: ID, error: MCPError) {\n self.id = id\n self.result = .failure(error)\n }\n\n private enum CodingKeys: String, CodingKey {\n case jsonrpc, id, result, error\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(jsonrpc, forKey: .jsonrpc)\n try container.encode(id, forKey: .id)\n switch result {\n case .success(let result):\n try container.encode(result, forKey: .result)\n case .failure(let error):\n try container.encode(error, forKey: .error)\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let version = try container.decode(String.self, forKey: .jsonrpc)\n guard version == jsonrpc else {\n throw DecodingError.dataCorruptedError(\n forKey: .jsonrpc, in: container, debugDescription: \"Invalid JSON-RPC version\")\n }\n id = try container.decode(ID.self, forKey: .id)\n if let result = try? container.decode(M.Result.self, forKey: .result) {\n self.result = .success(result)\n } else if let error = try? container.decode(MCPError.self, forKey: .error) {\n self.result = .failure(error)\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Invalid response\"))\n }\n }\n}\n\n/// A type-erased response for request/response handling\ntypealias AnyResponse = Response\n\nextension AnyResponse {\n init(_ response: Response) throws {\n // Instead of re-encoding/decoding which might double-wrap the error,\n // directly transfer the properties\n self.id = response.id\n switch response.result {\n case .success(let result):\n // For success, we still need to convert the result to a Value\n let data = try JSONEncoder().encode(result)\n let resultValue = try JSONDecoder().decode(Value.self, from: data)\n self.result = .success(resultValue)\n case .failure(let error):\n // Keep the original error without re-encoding/decoding\n self.result = .failure(error)\n }\n }\n}\n\n// MARK: -\n\n/// A notification message.\npublic protocol Notification: Hashable, Codable, Sendable {\n /// The parameters of the notification.\n associatedtype Parameters: Hashable, Codable, Sendable = Empty\n /// The name of the notification.\n static var name: String { get }\n}\n\n/// A type-erased notification for message handling\nstruct AnyNotification: Notification, Sendable {\n static var name: String { \"\" }\n typealias Parameters = Value\n}\n\nextension AnyNotification {\n init(_ notification: some Notification) throws {\n let encoder = JSONEncoder()\n let decoder = JSONDecoder()\n\n let data = try encoder.encode(notification)\n self = try decoder.decode(AnyNotification.self, from: data)\n }\n}\n\n/// A message that can be used to send notifications.\npublic struct Message: Hashable, Codable, Sendable {\n /// The method name.\n public let method: String\n /// The notification parameters.\n public let params: N.Parameters\n\n public init(method: String, params: N.Parameters) {\n self.method = method\n self.params = params\n }\n\n private enum CodingKeys: String, CodingKey {\n case jsonrpc, method, params\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(jsonrpc, forKey: .jsonrpc)\n try container.encode(method, forKey: .method)\n if N.Parameters.self != Empty.self {\n try container.encode(params, forKey: .params)\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let version = try container.decode(String.self, forKey: .jsonrpc)\n guard version == jsonrpc else {\n throw DecodingError.dataCorruptedError(\n forKey: .jsonrpc, in: container, debugDescription: \"Invalid JSON-RPC version\")\n }\n method = try container.decode(String.self, forKey: .method)\n\n if N.Parameters.self is NotRequired.Type {\n // For NotRequired parameters, use decodeIfPresent or init()\n params =\n (try container.decodeIfPresent(N.Parameters.self, forKey: .params)\n ?? (N.Parameters.self as! NotRequired.Type).init() as! N.Parameters)\n } else if let value = try? container.decode(N.Parameters.self, forKey: .params) {\n // If params exists and can be decoded, use it\n params = value\n } else if !container.contains(.params)\n || (try? container.decodeNil(forKey: .params)) == true\n {\n // If params is missing or explicitly null, use Empty for Empty parameters\n // or throw for non-Empty parameters\n if N.Parameters.self == Empty.self {\n params = Empty() as! N.Parameters\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Missing required params field\"))\n }\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Invalid params field\"))\n }\n }\n}\n\n/// A type-erased message for message handling\ntypealias AnyMessage = Message\n\nextension Notification where Parameters == Empty {\n /// Create a message with empty parameters.\n public static func message() -> Message {\n Message(method: name, params: Empty())\n }\n}\n\nextension Notification {\n /// Create a message with the given parameters.\n public static func message(_ parameters: Parameters) -> Message {\n Message(method: name, params: parameters)\n }\n}\n\n/// A box for notification handlers that can be type-erased\nclass NotificationHandlerBox: @unchecked Sendable {\n func callAsFunction(_ notification: Message) async throws {}\n}\n\n/// A typed notification handler that can be used to handle notifications of a specific type\nfinal class TypedNotificationHandler: NotificationHandlerBox,\n @unchecked Sendable\n{\n private let _handle: @Sendable (Message) async throws -> Void\n\n init(_ handler: @escaping @Sendable (Message) async throws -> Void) {\n self._handle = handler\n super.init()\n }\n\n override func callAsFunction(_ notification: Message) async throws {\n // Create a concrete notification from the type-erased one\n let data = try JSONEncoder().encode(notification)\n let typedNotification = try JSONDecoder().decode(Message.self, from: data)\n\n try await _handle(typedNotification)\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Value.swift", "import struct Foundation.Data\nimport class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\n/// A codable value.\npublic enum Value: Hashable, Sendable {\n case null\n case bool(Bool)\n case int(Int)\n case double(Double)\n case string(String)\n case data(mimeType: String? = nil, Data)\n case array([Value])\n case object([String: Value])\n\n /// Create a `Value` from a `Codable` value.\n /// - Parameter value: The codable value\n /// - Returns: A value\n public init(_ value: T) throws {\n if let valueAsValue = value as? Value {\n self = valueAsValue\n } else {\n let data = try JSONEncoder().encode(value)\n self = try JSONDecoder().decode(Value.self, from: data)\n }\n }\n\n /// Returns whether the value is `null`.\n public var isNull: Bool {\n return self == .null\n }\n\n /// Returns the `Bool` value if the value is a `bool`,\n /// otherwise returns `nil`.\n public var boolValue: Bool? {\n guard case let .bool(value) = self else { return nil }\n return value\n }\n\n /// Returns the `Int` value if the value is an `integer`,\n /// otherwise returns `nil`.\n public var intValue: Int? {\n guard case let .int(value) = self else { return nil }\n return value\n }\n\n /// Returns the `Double` value if the value is a `double`,\n /// otherwise returns `nil`.\n public var doubleValue: Double? {\n guard case let .double(value) = self else { return nil }\n return value\n }\n\n /// Returns the `String` value if the value is a `string`,\n /// otherwise returns `nil`.\n public var stringValue: String? {\n guard case let .string(value) = self else { return nil }\n return value\n }\n\n /// Returns the data value and optional MIME type if the value is `data`,\n /// otherwise returns `nil`.\n public var dataValue: (mimeType: String?, Data)? {\n guard case let .data(mimeType: mimeType, data) = self else { return nil }\n return (mimeType: mimeType, data)\n }\n\n /// Returns the `[Value]` value if the value is an `array`,\n /// otherwise returns `nil`.\n public var arrayValue: [Value]? {\n guard case let .array(value) = self else { return nil }\n return value\n }\n\n /// Returns the `[String: Value]` value if the value is an `object`,\n /// otherwise returns `nil`.\n public var objectValue: [String: Value]? {\n guard case let .object(value) = self else { return nil }\n return value\n }\n}\n\n// MARK: - Codable\n\nextension Value: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n\n if container.decodeNil() {\n self = .null\n } else if let value = try? container.decode(Bool.self) {\n self = .bool(value)\n } else if let value = try? container.decode(Int.self) {\n self = .int(value)\n } else if let value = try? container.decode(Double.self) {\n self = .double(value)\n } else if let value = try? container.decode(String.self) {\n if Data.isDataURL(string: value),\n case let (mimeType, data)? = Data.parseDataURL(value)\n {\n self = .data(mimeType: mimeType, data)\n } else {\n self = .string(value)\n }\n } else if let value = try? container.decode([Value].self) {\n self = .array(value)\n } else if let value = try? container.decode([String: Value].self) {\n self = .object(value)\n } else {\n throw DecodingError.dataCorruptedError(\n in: container, debugDescription: \"Value type not found\")\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n\n switch self {\n case .null:\n try container.encodeNil()\n case .bool(let value):\n try container.encode(value)\n case .int(let value):\n try container.encode(value)\n case .double(let value):\n try container.encode(value)\n case .string(let value):\n try container.encode(value)\n case let .data(mimeType, value):\n try container.encode(value.dataURLEncoded(mimeType: mimeType))\n case .array(let value):\n try container.encode(value)\n case .object(let value):\n try container.encode(value)\n }\n }\n}\n\nextension Value: CustomStringConvertible {\n public var description: String {\n switch self {\n case .null:\n return \"\"\n case .bool(let value):\n return value.description\n case .int(let value):\n return value.description\n case .double(let value):\n return value.description\n case .string(let value):\n return value.description\n case let .data(mimeType, value):\n return value.dataURLEncoded(mimeType: mimeType)\n case .array(let value):\n return value.description\n case .object(let value):\n return value.description\n }\n }\n}\n\n// MARK: - ExpressibleByNilLiteral\n\nextension Value: ExpressibleByNilLiteral {\n public init(nilLiteral: ()) {\n self = .null\n }\n}\n\n// MARK: - ExpressibleByBooleanLiteral\n\nextension Value: ExpressibleByBooleanLiteral {\n public init(booleanLiteral value: Bool) {\n self = .bool(value)\n }\n}\n\n// MARK: - ExpressibleByIntegerLiteral\n\nextension Value: ExpressibleByIntegerLiteral {\n public init(integerLiteral value: Int) {\n self = .int(value)\n }\n}\n\n// MARK: - ExpressibleByFloatLiteral\n\nextension Value: ExpressibleByFloatLiteral {\n public init(floatLiteral value: Double) {\n self = .double(value)\n }\n}\n\n// MARK: - ExpressibleByStringLiteral\n\nextension Value: ExpressibleByStringLiteral {\n public init(stringLiteral value: String) {\n self = .string(value)\n }\n}\n\n// MARK: - ExpressibleByArrayLiteral\n\nextension Value: ExpressibleByArrayLiteral {\n public init(arrayLiteral elements: Value...) {\n self = .array(elements)\n }\n}\n\n// MARK: - ExpressibleByDictionaryLiteral\n\nextension Value: ExpressibleByDictionaryLiteral {\n public init(dictionaryLiteral elements: (String, Value)...) {\n var dictionary: [String: Value] = [:]\n for (key, value) in elements {\n dictionary[key] = value\n }\n self = .object(dictionary)\n }\n}\n\n// MARK: - ExpressibleByStringInterpolation\n\nextension Value: ExpressibleByStringInterpolation {\n public struct StringInterpolation: StringInterpolationProtocol {\n var stringValue: String\n\n public init(literalCapacity: Int, interpolationCount: Int) {\n self.stringValue = \"\"\n self.stringValue.reserveCapacity(literalCapacity + interpolationCount)\n }\n\n public mutating func appendLiteral(_ literal: String) {\n self.stringValue.append(literal)\n }\n\n public mutating func appendInterpolation(_ value: T) {\n self.stringValue.append(value.description)\n }\n }\n\n public init(stringInterpolation: StringInterpolation) {\n self = .string(stringInterpolation.stringValue)\n }\n}\n\n// MARK: - Standard Library Type Extensions\n\nextension Bool {\n /// Creates a boolean value from a `Value` instance.\n ///\n /// In strict mode, only `.bool` values are converted. In non-strict mode, the following conversions are supported:\n /// - Integers: `1` is `true`, `0` is `false`\n /// - Doubles: `1.0` is `true`, `0.0` is `false`\n /// - Strings (lowercase only):\n /// - `true`: \"true\", \"t\", \"yes\", \"y\", \"on\", \"1\"\n /// - `false`: \"false\", \"f\", \"no\", \"n\", \"off\", \"0\"\n ///\n /// - Parameters:\n /// - value: The `Value` to convert\n /// - strict: When `true`, only converts from `.bool` values. Defaults to `true`\n /// - Returns: A boolean value if conversion is possible, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// Bool(Value.bool(true)) // Returns true\n /// Bool(Value.int(1), strict: false) // Returns true\n /// Bool(Value.string(\"yes\"), strict: false) // Returns true\n /// ```\n public init?(_ value: Value, strict: Bool = true) {\n switch value {\n case .bool(let b):\n self = b\n case .int(let i) where !strict:\n switch i {\n case 0: self = false\n case 1: self = true\n default: return nil\n }\n case .double(let d) where !strict:\n switch d {\n case 0.0: self = false\n case 1.0: self = true\n default: return nil\n }\n case .string(let s) where !strict:\n switch s {\n case \"true\", \"t\", \"yes\", \"y\", \"on\", \"1\":\n self = true\n case \"false\", \"f\", \"no\", \"n\", \"off\", \"0\":\n self = false\n default:\n return nil\n }\n default:\n return nil\n }\n }\n}\n\nextension Int {\n /// Creates an integer value from a `Value` instance.\n ///\n /// In strict mode, only `.int` values are converted. In non-strict mode, the following conversions are supported:\n /// - Doubles: Converted if they can be represented exactly as integers\n /// - Strings: Parsed if they contain a valid integer representation\n ///\n /// - Parameters:\n /// - value: The `Value` to convert\n /// - strict: When `true`, only converts from `.int` values. Defaults to `true`\n /// - Returns: An integer value if conversion is possible, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// Int(Value.int(42)) // Returns 42\n /// Int(Value.double(42.0), strict: false) // Returns 42\n /// Int(Value.string(\"42\"), strict: false) // Returns 42\n /// Int(Value.double(42.5), strict: false) // Returns nil\n /// ```\n public init?(_ value: Value, strict: Bool = true) {\n switch value {\n case .int(let i):\n self = i\n case .double(let d) where !strict:\n guard let intValue = Int(exactly: d) else { return nil }\n self = intValue\n case .string(let s) where !strict:\n guard let intValue = Int(s) else { return nil }\n self = intValue\n default:\n return nil\n }\n }\n}\n\nextension Double {\n /// Creates a double value from a `Value` instance.\n ///\n /// In strict mode, converts from `.double` and `.int` values. In non-strict mode, the following conversions are supported:\n /// - Integers: Converted to their double representation\n /// - Strings: Parsed if they contain a valid floating-point representation\n ///\n /// - Parameters:\n /// - value: The `Value` to convert\n /// - strict: When `true`, only converts from `.double` and `.int` values. Defaults to `true`\n /// - Returns: A double value if conversion is possible, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// Double(Value.double(42.5)) // Returns 42.5\n /// Double(Value.int(42)) // Returns 42.0\n /// Double(Value.string(\"42.5\"), strict: false) // Returns 42.5\n /// ```\n public init?(_ value: Value, strict: Bool = true) {\n switch value {\n case .double(let d):\n self = d\n case .int(let i):\n self = Double(i)\n case .string(let s) where !strict:\n guard let doubleValue = Double(s) else { return nil }\n self = doubleValue\n default:\n return nil\n }\n }\n}\n\nextension String {\n /// Creates a string value from a `Value` instance.\n ///\n /// In strict mode, only `.string` values are converted. In non-strict mode, the following conversions are supported:\n /// - Integers: Converted to their string representation\n /// - Doubles: Converted to their string representation\n /// - Booleans: Converted to \"true\" or \"false\"\n ///\n /// - Parameters:\n /// - value: The `Value` to convert\n /// - strict: When `true`, only converts from `.string` values. Defaults to `true`\n /// - Returns: A string value if conversion is possible, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// String(Value.string(\"hello\")) // Returns \"hello\"\n /// String(Value.int(42), strict: false) // Returns \"42\"\n /// String(Value.bool(true), strict: false) // Returns \"true\"\n /// ```\n public init?(_ value: Value, strict: Bool = true) {\n switch value {\n case .string(let s):\n self = s\n case .int(let i) where !strict:\n self = String(i)\n case .double(let d) where !strict:\n self = String(d)\n case .bool(let b) where !strict:\n self = String(b)\n default:\n return nil\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Extensions/Data+Extensions.swift", "import Foundation\nimport RegexBuilder\n\nextension Data {\n /// Regex pattern for data URLs\n @inline(__always) private static var dataURLRegex:\n Regex<(Substring, Substring, Substring?, Substring)>\n {\n Regex {\n \"data:\"\n Capture {\n ZeroOrMore(.reluctant) {\n CharacterClass.anyOf(\",;\").inverted\n }\n }\n Optionally {\n \";charset=\"\n Capture {\n OneOrMore(.reluctant) {\n CharacterClass.anyOf(\",;\").inverted\n }\n }\n }\n Optionally { \";base64\" }\n \",\"\n Capture {\n ZeroOrMore { .any }\n }\n }\n }\n\n /// Checks if a given string is a valid data URL.\n ///\n /// - Parameter string: The string to check.\n /// - Returns: `true` if the string is a valid data URL, otherwise `false`.\n /// - SeeAlso: [RFC 2397](https://www.rfc-editor.org/rfc/rfc2397.html)\n public static func isDataURL(string: String) -> Bool {\n return string.wholeMatch(of: dataURLRegex) != nil\n }\n\n /// Parses a data URL string into its MIME type and data components.\n ///\n /// - Parameter string: The data URL string to parse.\n /// - Returns: A tuple containing the MIME type and decoded data, or `nil` if parsing fails.\n /// - SeeAlso: [RFC 2397](https://www.rfc-editor.org/rfc/rfc2397.html)\n public static func parseDataURL(_ string: String) -> (mimeType: String, data: Data)? {\n guard let match = string.wholeMatch(of: dataURLRegex) else {\n return nil\n }\n\n // Extract components using strongly typed captures\n let (_, mediatype, charset, encodedData) = match.output\n\n let isBase64 = string.contains(\";base64,\")\n\n // Process MIME type\n var mimeType = mediatype.isEmpty ? \"text/plain\" : String(mediatype)\n if let charset = charset, !charset.isEmpty, mimeType.starts(with: \"text/\") {\n mimeType += \";charset=\\(charset)\"\n }\n\n // Decode data\n let decodedData: Data\n if isBase64 {\n guard let base64Data = Data(base64Encoded: String(encodedData)) else { return nil }\n decodedData = base64Data\n } else {\n guard\n let percentDecodedData = String(encodedData).removingPercentEncoding?.data(\n using: .utf8)\n else { return nil }\n decodedData = percentDecodedData\n }\n\n return (mimeType: mimeType, data: decodedData)\n }\n\n /// Encodes the data as a data URL string with an optional MIME type.\n ///\n /// - Parameter mimeType: The MIME type of the data. If `nil`, \"text/plain\" will be used.\n /// - Returns: A data URL string representation of the data.\n /// - SeeAlso: [RFC 2397](https://www.rfc-editor.org/rfc/rfc2397.html)\n public func dataURLEncoded(mimeType: String? = nil) -> String {\n let base64Data = self.base64EncodedString()\n return \"data:\\(mimeType ?? \"text/plain\");base64,\\(base64Data)\"\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/UnitInterval.swift", "/// A value constrained to the range 0.0 to 1.0, inclusive.\n///\n/// `UnitInterval` represents a normalized value that is guaranteed to be within\n/// the unit interval [0, 1]. This type is commonly used for representing\n/// priorities in sampling request model preferences.\n///\n/// The type provides safe initialization that returns `nil` for values outside\n/// the valid range, ensuring that all instances contain valid unit interval values.\n///\n/// - Example:\n/// ```swift\n/// let zero: UnitInterval = 0 // 0.0\n/// let half = UnitInterval(0.5)! // 0.5\n/// let one: UnitInterval = 1.0 // 1.0\n/// let invalid = UnitInterval(1.5) // nil\n/// ```\npublic struct UnitInterval: Hashable, Sendable {\n private let value: Double\n\n /// Creates a unit interval value from a `Double`.\n ///\n /// - Parameter value: A double value that must be in the range 0.0...1.0\n /// - Returns: A `UnitInterval` instance if the value is valid, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// let valid = UnitInterval(0.75) // Optional(0.75)\n /// let invalid = UnitInterval(-0.1) // nil\n /// let boundary = UnitInterval(1.0) // Optional(1.0)\n /// ```\n public init?(_ value: Double) {\n guard (0...1).contains(value) else { return nil }\n self.value = value\n }\n\n /// The underlying double value.\n ///\n /// This property provides access to the raw double value that is guaranteed\n /// to be within the range [0, 1].\n ///\n /// - Returns: The double value between 0.0 and 1.0, inclusive\n public var doubleValue: Double { value }\n}\n\n// MARK: - Comparable\n\nextension UnitInterval: Comparable {\n public static func < (lhs: UnitInterval, rhs: UnitInterval) -> Bool {\n lhs.value < rhs.value\n }\n}\n\n// MARK: - CustomStringConvertible\n\nextension UnitInterval: CustomStringConvertible {\n public var description: String { \"\\(value)\" }\n}\n\n// MARK: - Codable\n\nextension UnitInterval: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let doubleValue = try container.decode(Double.self)\n guard let interval = UnitInterval(doubleValue) else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: decoder.codingPath,\n debugDescription: \"Value \\(doubleValue) is not in range 0...1\")\n )\n }\n self = interval\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n try container.encode(value)\n }\n}\n\n// MARK: - ExpressibleByFloatLiteral\n\nextension UnitInterval: ExpressibleByFloatLiteral {\n /// Creates a unit interval from a floating-point literal.\n ///\n /// This initializer allows you to create `UnitInterval` instances using\n /// floating-point literals. The literal value must be in the range [0, 1]\n /// or a runtime error will occur.\n ///\n /// - Parameter value: A floating-point literal between 0.0 and 1.0\n ///\n /// - Warning: This initializer will crash if the literal is outside the valid range.\n /// Use the failable initializer `init(_:)` for runtime validation.\n ///\n /// - Example:\n /// ```swift\n /// let quarter: UnitInterval = 0.25\n /// let half: UnitInterval = 0.5\n /// ```\n public init(floatLiteral value: Double) {\n self.init(value)!\n }\n}\n\n// MARK: - ExpressibleByIntegerLiteral\n\nextension UnitInterval: ExpressibleByIntegerLiteral {\n /// Creates a unit interval from an integer literal.\n ///\n /// This initializer allows you to create `UnitInterval` instances using\n /// integer literals. Only the values 0 and 1 are valid.\n ///\n /// - Parameter value: An integer literal, either 0 or 1\n ///\n /// - Warning: This initializer will crash if the literal is outside the valid range.\n /// Use the failable initializer `init(_:)` for runtime validation.\n ///\n /// - Example:\n /// ```swift\n /// let zero: UnitInterval = 0\n /// let one: UnitInterval = 1\n /// ```\n public init(integerLiteral value: Int) {\n self.init(Double(value))!\n }\n}\n"], ["/swift-sdk/Sources/MCP/Server/Tools.swift", "import Foundation\n\n/// The Model Context Protocol (MCP) allows servers to expose tools\n/// that can be invoked by language models.\n/// Tools enable models to interact with external systems, such as\n/// querying databases, calling APIs, or performing computations.\n/// Each tool is uniquely identified by a name and includes metadata\n/// describing its schema.\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/\npublic struct Tool: Hashable, Codable, Sendable {\n /// The tool name\n public let name: String\n /// The tool description\n public let description: String\n /// The tool input schema\n public let inputSchema: Value?\n\n /// Annotations that provide display-facing and operational information for a Tool.\n ///\n /// - Note: All properties in `ToolAnnotations` are **hints**.\n /// They are not guaranteed to provide a faithful description of\n /// tool behavior (including descriptive properties like `title`).\n ///\n /// Clients should never make tool use decisions based on `ToolAnnotations`\n /// received from untrusted servers.\n public struct Annotations: Hashable, Codable, Sendable, ExpressibleByNilLiteral {\n /// A human-readable title for the tool\n public var title: String?\n\n /// If true, the tool may perform destructive updates to its environment.\n /// If false, the tool performs only additive updates.\n /// (This property is meaningful only when `readOnlyHint == false`)\n ///\n /// When unspecified, the implicit default is `true`.\n public var destructiveHint: Bool?\n\n /// If true, calling the tool repeatedly with the same arguments\n /// will have no additional effect on its environment.\n /// (This property is meaningful only when `readOnlyHint == false`)\n ///\n /// When unspecified, the implicit default is `false`.\n public var idempotentHint: Bool?\n\n /// If true, this tool may interact with an \"open world\" of external\n /// entities. If false, the tool's domain of interaction is closed.\n /// For example, the world of a web search tool is open, whereas that\n /// of a memory tool is not.\n ///\n /// When unspecified, the implicit default is `true`.\n public var openWorldHint: Bool?\n\n /// If true, the tool does not modify its environment.\n ///\n /// When unspecified, the implicit default is `false`.\n public var readOnlyHint: Bool?\n\n /// Returns true if all properties are nil\n public var isEmpty: Bool {\n title == nil && readOnlyHint == nil && destructiveHint == nil && idempotentHint == nil\n && openWorldHint == nil\n }\n\n public init(\n title: String? = nil,\n readOnlyHint: Bool? = nil,\n destructiveHint: Bool? = nil,\n idempotentHint: Bool? = nil,\n openWorldHint: Bool? = nil\n ) {\n self.title = title\n self.readOnlyHint = readOnlyHint\n self.destructiveHint = destructiveHint\n self.idempotentHint = idempotentHint\n self.openWorldHint = openWorldHint\n }\n\n /// Initialize an empty annotations object\n public init(nilLiteral: ()) {}\n }\n\n /// Annotations that provide display-facing and operational information\n public var annotations: Annotations\n\n /// Initialize a tool with a name, description, input schema, and annotations\n public init(\n name: String,\n description: String,\n inputSchema: Value? = nil,\n annotations: Annotations = nil\n ) {\n self.name = name\n self.description = description\n self.inputSchema = inputSchema\n self.annotations = annotations\n }\n\n /// Content types that can be returned by a tool\n public enum Content: Hashable, Codable, Sendable {\n /// Text content\n case text(String)\n /// Image content\n case image(data: String, mimeType: String, metadata: [String: String]?)\n /// Audio content\n case audio(data: String, mimeType: String)\n /// Embedded resource content\n case resource(uri: String, mimeType: String, text: String?)\n\n private enum CodingKeys: String, CodingKey {\n case type\n case text\n case image\n case resource\n case audio\n case uri\n case mimeType\n case data\n case metadata\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let type = try container.decode(String.self, forKey: .type)\n\n switch type {\n case \"text\":\n let text = try container.decode(String.self, forKey: .text)\n self = .text(text)\n case \"image\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n let metadata = try container.decodeIfPresent(\n [String: String].self, forKey: .metadata)\n self = .image(data: data, mimeType: mimeType, metadata: metadata)\n case \"audio\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n self = .audio(data: data, mimeType: mimeType)\n case \"resource\":\n let uri = try container.decode(String.self, forKey: .uri)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n let text = try container.decodeIfPresent(String.self, forKey: .text)\n self = .resource(uri: uri, mimeType: mimeType, text: text)\n default:\n throw DecodingError.dataCorruptedError(\n forKey: .type, in: container, debugDescription: \"Unknown tool content type\")\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n\n switch self {\n case .text(let text):\n try container.encode(\"text\", forKey: .type)\n try container.encode(text, forKey: .text)\n case .image(let data, let mimeType, let metadata):\n try container.encode(\"image\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n try container.encodeIfPresent(metadata, forKey: .metadata)\n case .audio(let data, let mimeType):\n try container.encode(\"audio\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n case .resource(let uri, let mimeType, let text):\n try container.encode(\"resource\", forKey: .type)\n try container.encode(uri, forKey: .uri)\n try container.encode(mimeType, forKey: .mimeType)\n try container.encodeIfPresent(text, forKey: .text)\n }\n }\n }\n\n private enum CodingKeys: String, CodingKey {\n case name\n case description\n case inputSchema\n case annotations\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n name = try container.decode(String.self, forKey: .name)\n description = try container.decode(String.self, forKey: .description)\n inputSchema = try container.decodeIfPresent(Value.self, forKey: .inputSchema)\n annotations =\n try container.decodeIfPresent(Tool.Annotations.self, forKey: .annotations) ?? .init()\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(name, forKey: .name)\n try container.encode(description, forKey: .description)\n if let schema = inputSchema {\n try container.encode(schema, forKey: .inputSchema)\n }\n if !annotations.isEmpty {\n try container.encode(annotations, forKey: .annotations)\n }\n }\n}\n\n// MARK: -\n\n/// To discover available tools, clients send a `tools/list` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/#listing-tools\npublic enum ListTools: Method {\n public static let name = \"tools/list\"\n\n public struct Parameters: NotRequired, Hashable, Codable, Sendable {\n public let cursor: String?\n\n public init() {\n self.cursor = nil\n }\n\n public init(cursor: String) {\n self.cursor = cursor\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let tools: [Tool]\n public let nextCursor: String?\n\n public init(tools: [Tool], nextCursor: String? = nil) {\n self.tools = tools\n self.nextCursor = nextCursor\n }\n }\n}\n\n/// To call a tool, clients send a `tools/call` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/#calling-tools\npublic enum CallTool: Method {\n public static let name = \"tools/call\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let name: String\n public let arguments: [String: Value]?\n\n public init(name: String, arguments: [String: Value]? = nil) {\n self.name = name\n self.arguments = arguments\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let content: [Tool.Content]\n public let isError: Bool?\n\n public init(content: [Tool.Content], isError: Bool? = nil) {\n self.content = content\n self.isError = isError\n }\n }\n}\n\n/// When the list of available tools changes, servers that declared the listChanged capability SHOULD send a notification:\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/#list-changed-notification\npublic struct ToolListChangedNotification: Notification {\n public static let name: String = \"notifications/tools/list_changed\"\n}\n"], ["/swift-sdk/Sources/MCP/Client/Sampling.swift", "import Foundation\n\n/// The Model Context Protocol (MCP) allows servers to request LLM completions\n/// through the client, enabling sophisticated agentic behaviors while maintaining\n/// security and privacy.\n///\n/// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/sampling#how-sampling-works\npublic enum Sampling {\n /// A message in the conversation history.\n public struct Message: Hashable, Codable, Sendable {\n /// The message role\n public enum Role: String, Hashable, Codable, Sendable {\n /// A user message\n case user\n /// An assistant message\n case assistant\n }\n\n /// The message role\n public let role: Role\n /// The message content\n public let content: Content\n\n /// Creates a message with the specified role and content\n @available(\n *, deprecated, message: \"Use static factory methods .user(_:) or .assistant(_:) instead\"\n )\n public init(role: Role, content: Content) {\n self.role = role\n self.content = content\n }\n\n /// Private initializer for convenience methods to avoid deprecation warnings\n private init(_role role: Role, _content content: Content) {\n self.role = role\n self.content = content\n }\n\n /// Creates a user message with the specified content\n public static func user(_ content: Content) -> Message {\n return Message(_role: .user, _content: content)\n }\n\n /// Creates an assistant message with the specified content\n public static func assistant(_ content: Content) -> Message {\n return Message(_role: .assistant, _content: content)\n }\n\n /// Content types for sampling messages\n public enum Content: Hashable, Sendable {\n /// Text content\n case text(String)\n /// Image content\n case image(data: String, mimeType: String)\n }\n }\n\n /// Model preferences for sampling requests\n public struct ModelPreferences: Hashable, Codable, Sendable {\n /// Model hints for selection\n public struct Hint: Hashable, Codable, Sendable {\n /// Suggested model name/family\n public let name: String?\n\n public init(name: String? = nil) {\n self.name = name\n }\n }\n\n /// Array of model name suggestions that clients can use to select an appropriate model\n public let hints: [Hint]?\n /// Importance of minimizing costs (0-1 normalized)\n public let costPriority: UnitInterval?\n /// Importance of low latency response (0-1 normalized)\n public let speedPriority: UnitInterval?\n /// Importance of advanced model capabilities (0-1 normalized)\n public let intelligencePriority: UnitInterval?\n\n public init(\n hints: [Hint]? = nil,\n costPriority: UnitInterval? = nil,\n speedPriority: UnitInterval? = nil,\n intelligencePriority: UnitInterval? = nil\n ) {\n self.hints = hints\n self.costPriority = costPriority\n self.speedPriority = speedPriority\n self.intelligencePriority = intelligencePriority\n }\n }\n\n /// Context inclusion options for sampling requests\n public enum ContextInclusion: String, Hashable, Codable, Sendable {\n /// No additional context\n case none\n /// Include context from the requesting server\n case thisServer\n /// Include context from all connected MCP servers\n case allServers\n }\n\n /// Stop reason for sampling completion\n public enum StopReason: String, Hashable, Codable, Sendable {\n /// Natural end of turn\n case endTurn\n /// Hit a stop sequence\n case stopSequence\n /// Reached maximum tokens\n case maxTokens\n }\n}\n\n// MARK: - Codable\n\nextension Sampling.Message.Content: Codable {\n private enum CodingKeys: String, CodingKey {\n case type, text, data, mimeType\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let type = try container.decode(String.self, forKey: .type)\n\n switch type {\n case \"text\":\n let text = try container.decode(String.self, forKey: .text)\n self = .text(text)\n case \"image\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n self = .image(data: data, mimeType: mimeType)\n default:\n throw DecodingError.dataCorruptedError(\n forKey: .type, in: container,\n debugDescription: \"Unknown sampling message content type\")\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n\n switch self {\n case .text(let text):\n try container.encode(\"text\", forKey: .type)\n try container.encode(text, forKey: .text)\n case .image(let data, let mimeType):\n try container.encode(\"image\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n }\n }\n}\n\n// MARK: - ExpressibleByStringLiteral\n\nextension Sampling.Message.Content: ExpressibleByStringLiteral {\n public init(stringLiteral value: String) {\n self = .text(value)\n }\n}\n\n// MARK: - ExpressibleByStringInterpolation\n\nextension Sampling.Message.Content: ExpressibleByStringInterpolation {\n public init(stringInterpolation: DefaultStringInterpolation) {\n self = .text(String(stringInterpolation: stringInterpolation))\n }\n}\n\n// MARK: -\n\n/// To request sampling from a client, servers send a `sampling/createMessage` request.\n/// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/sampling#how-sampling-works\npublic enum CreateSamplingMessage: Method {\n public static let name = \"sampling/createMessage\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n /// The conversation history to send to the LLM\n public let messages: [Sampling.Message]\n /// Model selection preferences\n public let modelPreferences: Sampling.ModelPreferences?\n /// Optional system prompt\n public let systemPrompt: String?\n /// What MCP context to include\n public let includeContext: Sampling.ContextInclusion?\n /// Controls randomness (0.0 to 1.0)\n public let temperature: Double?\n /// Maximum tokens to generate\n public let maxTokens: Int\n /// Array of sequences that stop generation\n public let stopSequences: [String]?\n /// Additional provider-specific parameters\n public let metadata: [String: Value]?\n\n public init(\n messages: [Sampling.Message],\n modelPreferences: Sampling.ModelPreferences? = nil,\n systemPrompt: String? = nil,\n includeContext: Sampling.ContextInclusion? = nil,\n temperature: Double? = nil,\n maxTokens: Int,\n stopSequences: [String]? = nil,\n metadata: [String: Value]? = nil\n ) {\n self.messages = messages\n self.modelPreferences = modelPreferences\n self.systemPrompt = systemPrompt\n self.includeContext = includeContext\n self.temperature = temperature\n self.maxTokens = maxTokens\n self.stopSequences = stopSequences\n self.metadata = metadata\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n /// Name of the model used\n public let model: String\n /// Why sampling stopped\n public let stopReason: Sampling.StopReason?\n /// The role of the completion\n public let role: Sampling.Message.Role\n /// The completion content\n public let content: Sampling.Message.Content\n\n public init(\n model: String,\n stopReason: Sampling.StopReason? = nil,\n role: Sampling.Message.Role,\n content: Sampling.Message.Content\n ) {\n self.model = model\n self.stopReason = stopReason\n self.role = role\n self.content = content\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Server/Prompts.swift", "import Foundation\n\n/// The Model Context Protocol (MCP) provides a standardized way\n/// for servers to expose prompt templates to clients.\n/// Prompts allow servers to provide structured messages and instructions\n/// for interacting with language models.\n/// Clients can discover available prompts, retrieve their contents,\n/// and provide arguments to customize them.\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/\npublic struct Prompt: Hashable, Codable, Sendable {\n /// The prompt name\n public let name: String\n /// The prompt description\n public let description: String?\n /// The prompt arguments\n public let arguments: [Argument]?\n\n public init(name: String, description: String? = nil, arguments: [Argument]? = nil) {\n self.name = name\n self.description = description\n self.arguments = arguments\n }\n\n /// An argument for a prompt\n public struct Argument: Hashable, Codable, Sendable {\n /// The argument name\n public let name: String\n /// The argument description\n public let description: String?\n /// Whether the argument is required\n public let required: Bool?\n\n public init(name: String, description: String? = nil, required: Bool? = nil) {\n self.name = name\n self.description = description\n self.required = required\n }\n }\n\n /// A message in a prompt\n public struct Message: Hashable, Codable, Sendable {\n /// The message role\n public enum Role: String, Hashable, Codable, Sendable {\n /// A user message\n case user\n /// An assistant message\n case assistant\n }\n\n /// The message role\n public let role: Role\n /// The message content\n public let content: Content\n\n /// Creates a message with the specified role and content\n @available(\n *, deprecated, message: \"Use static factory methods .user(_:) or .assistant(_:) instead\"\n )\n public init(role: Role, content: Content) {\n self.role = role\n self.content = content\n }\n\n /// Private initializer for convenience methods to avoid deprecation warnings\n private init(_role role: Role, _content content: Content) {\n self.role = role\n self.content = content\n }\n\n /// Creates a user message with the specified content\n public static func user(_ content: Content) -> Message {\n return Message(_role: .user, _content: content)\n }\n\n /// Creates an assistant message with the specified content\n public static func assistant(_ content: Content) -> Message {\n return Message(_role: .assistant, _content: content)\n }\n\n /// Content types for messages\n public enum Content: Hashable, Sendable {\n /// Text content\n case text(text: String)\n /// Image content\n case image(data: String, mimeType: String)\n /// Audio content\n case audio(data: String, mimeType: String)\n /// Embedded resource content\n case resource(uri: String, mimeType: String, text: String?, blob: String?)\n }\n }\n\n /// Reference type for prompts\n public struct Reference: Hashable, Codable, Sendable {\n /// The prompt reference name\n public let name: String\n\n public init(name: String) {\n self.name = name\n }\n\n private enum CodingKeys: String, CodingKey {\n case type, name\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(\"ref/prompt\", forKey: .type)\n try container.encode(name, forKey: .name)\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n _ = try container.decode(String.self, forKey: .type)\n name = try container.decode(String.self, forKey: .name)\n }\n }\n}\n\n// MARK: - Codable\n\nextension Prompt.Message.Content: Codable {\n private enum CodingKeys: String, CodingKey {\n case type, text, data, mimeType, uri, blob\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n\n switch self {\n case .text(let text):\n try container.encode(\"text\", forKey: .type)\n try container.encode(text, forKey: .text)\n case .image(let data, let mimeType):\n try container.encode(\"image\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n case .audio(let data, let mimeType):\n try container.encode(\"audio\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n case .resource(let uri, let mimeType, let text, let blob):\n try container.encode(\"resource\", forKey: .type)\n try container.encode(uri, forKey: .uri)\n try container.encode(mimeType, forKey: .mimeType)\n try container.encodeIfPresent(text, forKey: .text)\n try container.encodeIfPresent(blob, forKey: .blob)\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let type = try container.decode(String.self, forKey: .type)\n\n switch type {\n case \"text\":\n let text = try container.decode(String.self, forKey: .text)\n self = .text(text: text)\n case \"image\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n self = .image(data: data, mimeType: mimeType)\n case \"audio\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n self = .audio(data: data, mimeType: mimeType)\n case \"resource\":\n let uri = try container.decode(String.self, forKey: .uri)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n let text = try container.decodeIfPresent(String.self, forKey: .text)\n let blob = try container.decodeIfPresent(String.self, forKey: .blob)\n self = .resource(uri: uri, mimeType: mimeType, text: text, blob: blob)\n default:\n throw DecodingError.dataCorruptedError(\n forKey: .type,\n in: container,\n debugDescription: \"Unknown content type\")\n }\n }\n}\n\n// MARK: - ExpressibleByStringLiteral\n\nextension Prompt.Message.Content: ExpressibleByStringLiteral {\n public init(stringLiteral value: String) {\n self = .text(text: value)\n }\n}\n\n// MARK: - ExpressibleByStringInterpolation\n\nextension Prompt.Message.Content: ExpressibleByStringInterpolation {\n public init(stringInterpolation: DefaultStringInterpolation) {\n self = .text(text: String(stringInterpolation: stringInterpolation))\n }\n}\n\n// MARK: -\n\n/// To retrieve available prompts, clients send a `prompts/list` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/#listing-prompts\npublic enum ListPrompts: Method {\n public static let name: String = \"prompts/list\"\n\n public struct Parameters: NotRequired, Hashable, Codable, Sendable {\n public let cursor: String?\n\n public init() {\n self.cursor = nil\n }\n\n public init(cursor: String) {\n self.cursor = cursor\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let prompts: [Prompt]\n public let nextCursor: String?\n\n public init(prompts: [Prompt], nextCursor: String? = nil) {\n self.prompts = prompts\n self.nextCursor = nextCursor\n }\n }\n}\n\n/// To retrieve a specific prompt, clients send a `prompts/get` request.\n/// Arguments may be auto-completed through the completion API.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/#getting-a-prompt\npublic enum GetPrompt: Method {\n public static let name: String = \"prompts/get\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let name: String\n public let arguments: [String: Value]?\n\n public init(name: String, arguments: [String: Value]? = nil) {\n self.name = name\n self.arguments = arguments\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let description: String?\n public let messages: [Prompt.Message]\n\n public init(description: String?, messages: [Prompt.Message]) {\n self.description = description\n self.messages = messages\n }\n }\n}\n\n/// When the list of available prompts changes, servers that declared the listChanged capability SHOULD send a notification.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/#list-changed-notification\npublic struct PromptListChangedNotification: Notification {\n public static let name: String = \"notifications/prompts/list_changed\"\n}\n"], ["/swift-sdk/Sources/MCP/Server/Resources.swift", "import Foundation\n\n/// The Model Context Protocol (MCP) provides a standardized way\n/// for servers to expose resources to clients.\n/// Resources allow servers to share data that provides context to language models,\n/// such as files, database schemas, or application-specific information.\n/// Each resource is uniquely identified by a URI.\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/\npublic struct Resource: Hashable, Codable, Sendable {\n /// The resource name\n public var name: String\n /// The resource URI\n public var uri: String\n /// The resource description\n public var description: String?\n /// The resource MIME type\n public var mimeType: String?\n /// The resource metadata\n public var metadata: [String: String]?\n\n public init(\n name: String,\n uri: String,\n description: String? = nil,\n mimeType: String? = nil,\n metadata: [String: String]? = nil\n ) {\n self.name = name\n self.uri = uri\n self.description = description\n self.mimeType = mimeType\n self.metadata = metadata\n }\n\n /// Content of a resource.\n public struct Content: Hashable, Codable, Sendable {\n /// The resource URI\n public let uri: String\n /// The resource MIME type\n public let mimeType: String?\n /// The resource text content\n public let text: String?\n /// The resource binary content\n public let blob: String?\n\n public static func text(_ content: String, uri: String, mimeType: String? = nil) -> Self {\n .init(uri: uri, mimeType: mimeType, text: content)\n }\n\n public static func binary(_ data: Data, uri: String, mimeType: String? = nil) -> Self {\n .init(uri: uri, mimeType: mimeType, blob: data.base64EncodedString())\n }\n\n private init(uri: String, mimeType: String? = nil, text: String? = nil) {\n self.uri = uri\n self.mimeType = mimeType\n self.text = text\n self.blob = nil\n }\n\n private init(uri: String, mimeType: String? = nil, blob: String) {\n self.uri = uri\n self.mimeType = mimeType\n self.text = nil\n self.blob = blob\n }\n }\n\n /// A resource template.\n public struct Template: Hashable, Codable, Sendable {\n /// The URI template pattern\n public var uriTemplate: String\n /// The template name\n public var name: String\n /// The template description\n public var description: String?\n /// The resource MIME type\n public var mimeType: String?\n\n public init(\n uriTemplate: String,\n name: String,\n description: String? = nil,\n mimeType: String? = nil\n ) {\n self.uriTemplate = uriTemplate\n self.name = name\n self.description = description\n self.mimeType = mimeType\n }\n }\n}\n\n// MARK: -\n\n/// To discover available resources, clients send a `resources/list` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#listing-resources\npublic enum ListResources: Method {\n public static let name: String = \"resources/list\"\n\n public struct Parameters: NotRequired, Hashable, Codable, Sendable {\n public let cursor: String?\n\n public init() {\n self.cursor = nil\n }\n \n public init(cursor: String) {\n self.cursor = cursor\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let resources: [Resource]\n public let nextCursor: String?\n\n public init(resources: [Resource], nextCursor: String? = nil) {\n self.resources = resources\n self.nextCursor = nextCursor\n }\n }\n}\n\n/// To retrieve resource contents, clients send a `resources/read` request:\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#reading-resources\npublic enum ReadResource: Method {\n public static let name: String = \"resources/read\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let uri: String\n\n public init(uri: String) {\n self.uri = uri\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let contents: [Resource.Content]\n\n public init(contents: [Resource.Content]) {\n self.contents = contents\n }\n }\n}\n\n/// To discover available resource templates, clients send a `resources/templates/list` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#resource-templates\npublic enum ListResourceTemplates: Method {\n public static let name: String = \"resources/templates/list\"\n\n public struct Parameters: NotRequired, Hashable, Codable, Sendable {\n public let cursor: String?\n\n public init() {\n self.cursor = nil\n }\n \n public init(cursor: String) {\n self.cursor = cursor\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let templates: [Resource.Template]\n public let nextCursor: String?\n\n public init(templates: [Resource.Template], nextCursor: String? = nil) {\n self.templates = templates\n self.nextCursor = nextCursor\n }\n\n private enum CodingKeys: String, CodingKey {\n case templates = \"resourceTemplates\"\n case nextCursor\n }\n }\n}\n\n/// When the list of available resources changes, servers that declared the listChanged capability SHOULD send a notification.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#list-changed-notification\npublic struct ResourceListChangedNotification: Notification {\n public static let name: String = \"notifications/resources/list_changed\"\n\n public typealias Parameters = Empty\n}\n\n/// Clients can subscribe to specific resources and receive notifications when they change.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#subscriptions\npublic enum ResourceSubscribe: Method {\n public static let name: String = \"resources/subscribe\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let uri: String\n }\n\n public typealias Result = Empty\n}\n\n/// When a resource changes, servers that declared the updated capability SHOULD send a notification to subscribed clients.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#subscriptions\npublic struct ResourceUpdatedNotification: Notification {\n public static let name: String = \"notifications/resources/updated\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let uri: String\n\n public init(uri: String) {\n self.uri = uri\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/ID.swift", "import struct Foundation.UUID\n\n/// A unique identifier for a request.\npublic enum ID: Hashable, Sendable {\n /// A string ID.\n case string(String)\n\n /// A number ID.\n case number(Int)\n\n /// Generates a random string ID.\n public static var random: ID {\n return .string(UUID().uuidString)\n }\n}\n\n// MARK: - ExpressibleByStringLiteral\n\nextension ID: ExpressibleByStringLiteral {\n public init(stringLiteral value: String) {\n self = .string(value)\n }\n}\n\n// MARK: - ExpressibleByIntegerLiteral\n\nextension ID: ExpressibleByIntegerLiteral {\n public init(integerLiteral value: Int) {\n self = .number(value)\n }\n}\n\n// MARK: - CustomStringConvertible\n\nextension ID: CustomStringConvertible {\n public var description: String {\n switch self {\n case .string(let str): return str\n case .number(let num): return String(num)\n }\n }\n}\n\n// MARK: - Codable\n\nextension ID: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n if let string = try? container.decode(String.self) {\n self = .string(string)\n } else if let number = try? container.decode(Int.self) {\n self = .number(number)\n } else if container.decodeNil() {\n // Handle unspecified/null IDs as empty string\n self = .string(\"\")\n } else {\n throw DecodingError.dataCorruptedError(\n in: container, debugDescription: \"ID must be string or number\")\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n switch self {\n case .string(let str): try container.encode(str)\n case .number(let num): try container.encode(num)\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Transport.swift", "import Logging\n\nimport struct Foundation.Data\n\n/// Protocol defining the transport layer for MCP communication\npublic protocol Transport: Actor {\n var logger: Logger { get }\n\n /// Establishes connection with the transport\n func connect() async throws\n\n /// Disconnects from the transport\n func disconnect() async\n\n /// Sends data\n func send(_ data: Data) async throws\n\n /// Receives data in an async sequence\n func receive() -> AsyncThrowingStream\n}\n"], ["/swift-sdk/Sources/MCP/Base/Lifecycle.swift", "/// The initialization phase MUST be the first interaction between client and server.\n/// During this phase, the client and server:\n/// - Establish protocol version compatibility\n/// - Exchange and negotiate capabilities\n/// - Share implementation details\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle/#initialization\npublic enum Initialize: Method {\n public static let name: String = \"initialize\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let protocolVersion: String\n public let capabilities: Client.Capabilities\n public let clientInfo: Client.Info\n\n public init(\n protocolVersion: String = Version.latest,\n capabilities: Client.Capabilities,\n clientInfo: Client.Info\n ) {\n self.protocolVersion = protocolVersion\n self.capabilities = capabilities\n self.clientInfo = clientInfo\n }\n\n private enum CodingKeys: String, CodingKey {\n case protocolVersion, capabilities, clientInfo\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n protocolVersion =\n try container.decodeIfPresent(String.self, forKey: .protocolVersion)\n ?? Version.latest\n capabilities =\n try container.decodeIfPresent(Client.Capabilities.self, forKey: .capabilities)\n ?? .init()\n clientInfo =\n try container.decodeIfPresent(Client.Info.self, forKey: .clientInfo)\n ?? .init(name: \"unknown\", version: \"0.0.0\")\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let protocolVersion: String\n public let capabilities: Server.Capabilities\n public let serverInfo: Server.Info\n public let instructions: String?\n }\n}\n\n/// After successful initialization, the client MUST send an initialized notification to indicate it is ready to begin normal operations.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle/#initialization\npublic struct InitializedNotification: Notification {\n public static let name: String = \"notifications/initialized\"\n}\n"], ["/swift-sdk/Sources/MCP/Base/Versioning.swift", "import Foundation\n\n/// The Model Context Protocol uses string-based version identifiers\n/// following the format YYYY-MM-DD, to indicate\n/// the last date backwards incompatible changes were made.\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2025-03-26/\npublic enum Version {\n /// All protocol versions supported by this implementation, ordered from newest to oldest.\n static let supported: Set = [\n \"2025-03-26\",\n \"2024-11-05\",\n ]\n\n /// The latest protocol version supported by this implementation.\n public static let latest = supported.max()!\n\n /// Negotiates the protocol version based on the client's request and server's capabilities.\n /// - Parameter clientRequestedVersion: The protocol version requested by the client.\n /// - Returns: The negotiated protocol version. If the client's requested version is supported,\n /// that version is returned. Otherwise, the server's latest supported version is returned.\n static func negotiate(clientRequestedVersion: String) -> String {\n if supported.contains(clientRequestedVersion) {\n return clientRequestedVersion\n }\n return latest\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Utilities/Ping.swift", "/// The Model Context Protocol includes an optional ping mechanism that allows either party to verify that their counterpart is still responsive and the connection is alive.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/utilities/ping\npublic enum Ping: Method {\n public static let name: String = \"ping\"\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 03:25:14", "created_task_model": "DeepSeek-R1", "function_skeleton": "private func receiveLoop ( ) async { }", "code_description": "This code segment functions to: Process incoming data streams by buffering and splitting them on delimiter boundaries, monitor connection health through empty read detection and error handling, and implement recovery mechanisms with configurable retry logic for maintaining network communication continuity."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```swift\n[TASK_BEGIN]\nprivate func receiveLoop() async {\n var buffer = Data()\n \n while await isConnected && !isStopping {\n do {\n let data = try await receiveData()\n \n if data.isEmpty {\n // Connection closed by peer\n logger.trace(\"Connection closed by peer\")\n messageContinuation.finish(throwing: MCPError.connectionClosed)\n break\n }\n \n buffer.append(data)\n \n // Process potential heartbeats at buffer start\n while buffer.count >= 12 {\n let prefix = buffer.prefix(4)\n guard Heartbeat.isHeartbeat(prefix) else { break }\n \n let heartbeatData = buffer.prefix(12)\n if let heartbeat = Heartbeat(rawValue: Array(heartbeatData)) {\n logger.trace(\"Received heartbeat: \\(heartbeat.timestamp)\")\n await setLastHeartbeatTime(Date())\n } else {\n logger.error(\"Invalid heartbeat received\")\n }\n buffer.removeFirst(12)\n }\n \n // Process complete messages delimited by newline\n while let newlineIndex = buffer.firstIndex(of: 0x0A) {\n let message = Data(buffer[..= maxConsecutiveEmptyReads {\n logger.warning(\n \"Multiple consecutive empty reads (\\(consecutiveEmptyReads)), possible connection issue\"\n )\n if connection.state != .ready {\n logger.info(\"Connection no longer ready, exiting receive loop\")\n break\n }\n }\n try await Task.sleep(for: .milliseconds(100))\n continue\n }\n if Heartbeat.isHeartbeat(newData) {\n logger.trace(\"Received heartbeat from peer\")\n if let heartbeat = Heartbeat.from(data: newData) {\n logger.trace(\"Heartbeat timestamp: \\(heartbeat.timestamp)\")\n }\n consecutiveEmptyReads = 0\n continue \n }\n consecutiveEmptyReads = 0\n buffer.append(newData)\n while let newlineIndex = buffer.firstIndex(of: UInt8(ascii: \"\\n\")) {\n let messageData = buffer[..= 12 {\n let prefix = buffer.prefix(4)\n guard Heartbeat.isHeartbeat(prefix) else { break }\n let heartbeatData = buffer.prefix(12)\n if let heartbeat = Heartbeat(rawValue: Array(heartbeatData)) {\n logger.trace(\"Received heartbeat: \\(heartbeat.timestamp)\")\n await setLastHeartbeatTime(Date())\n } else {\n logger.error(\"Invalid heartbeat received\")\n }\n buffer.removeFirst(12)\n }\n while let newlineIndex = buffer.firstIndex(of: 0x0A) {\n let message = Data(buffer[..\n {\n Regex {\n \"data:\"\n Capture {\n ZeroOrMore(.reluctant) {\n CharacterClass.anyOf(\",;\").inverted\n }\n }\n Optionally {\n \";charset=\"\n Capture {\n OneOrMore(.reluctant) {\n CharacterClass.anyOf(\",;\").inverted\n }\n }\n }\n Optionally { \";base64\" }\n \",\"\n Capture {\n ZeroOrMore { .any }\n }\n }\n }\n\n /// Checks if a given string is a valid data URL.\n ///\n /// - Parameter string: The string to check.\n /// - Returns: `true` if the string is a valid data URL, otherwise `false`.\n /// - SeeAlso: [RFC 2397](https://www.rfc-editor.org/rfc/rfc2397.html)\n public static func isDataURL(string: String) -> Bool {\n return string.wholeMatch(of: dataURLRegex) != nil\n }\n\n /// Parses a data URL string into its MIME type and data components.\n ///\n /// - Parameter string: The data URL string to parse.\n /// - Returns: A tuple containing the MIME type and decoded data, or `nil` if parsing fails.\n /// - SeeAlso: [RFC 2397](https://www.rfc-editor.org/rfc/rfc2397.html)\n ", "suffix_code": "\n\n /// Encodes the data as a data URL string with an optional MIME type.\n ///\n /// - Parameter mimeType: The MIME type of the data. If `nil`, \"text/plain\" will be used.\n /// - Returns: A data URL string representation of the data.\n /// - SeeAlso: [RFC 2397](https://www.rfc-editor.org/rfc/rfc2397.html)\n public func dataURLEncoded(mimeType: String? = nil) -> String {\n let base64Data = self.base64EncodedString()\n return \"data:\\(mimeType ?? \"text/plain\");base64,\\(base64Data)\"\n }\n}\n", "middle_code": "public static func parseDataURL(_ string: String) -> (mimeType: String, data: Data)? {\n guard let match = string.wholeMatch(of: dataURLRegex) else {\n return nil\n }\n let (_, mediatype, charset, encodedData) = match.output\n let isBase64 = string.contains(\";base64,\")\n var mimeType = mediatype.isEmpty ? \"text/plain\" : String(mediatype)\n if let charset = charset, !charset.isEmpty, mimeType.starts(with: \"text/\") {\n mimeType += \";charset=\\(charset)\"\n }\n let decodedData: Data\n if isBase64 {\n guard let base64Data = Data(base64Encoded: String(encodedData)) else { return nil }\n decodedData = base64Data\n } else {\n guard\n let percentDecodedData = String(encodedData).removingPercentEncoding?.data(\n using: .utf8)\n else { return nil }\n decodedData = percentDecodedData\n }\n return (mimeType: mimeType, data: decodedData)\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "swift", "sub_task_type": null}, "context_code": [["/swift-sdk/Sources/MCP/Base/Value.swift", "import struct Foundation.Data\nimport class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\n/// A codable value.\npublic enum Value: Hashable, Sendable {\n case null\n case bool(Bool)\n case int(Int)\n case double(Double)\n case string(String)\n case data(mimeType: String? = nil, Data)\n case array([Value])\n case object([String: Value])\n\n /// Create a `Value` from a `Codable` value.\n /// - Parameter value: The codable value\n /// - Returns: A value\n public init(_ value: T) throws {\n if let valueAsValue = value as? Value {\n self = valueAsValue\n } else {\n let data = try JSONEncoder().encode(value)\n self = try JSONDecoder().decode(Value.self, from: data)\n }\n }\n\n /// Returns whether the value is `null`.\n public var isNull: Bool {\n return self == .null\n }\n\n /// Returns the `Bool` value if the value is a `bool`,\n /// otherwise returns `nil`.\n public var boolValue: Bool? {\n guard case let .bool(value) = self else { return nil }\n return value\n }\n\n /// Returns the `Int` value if the value is an `integer`,\n /// otherwise returns `nil`.\n public var intValue: Int? {\n guard case let .int(value) = self else { return nil }\n return value\n }\n\n /// Returns the `Double` value if the value is a `double`,\n /// otherwise returns `nil`.\n public var doubleValue: Double? {\n guard case let .double(value) = self else { return nil }\n return value\n }\n\n /// Returns the `String` value if the value is a `string`,\n /// otherwise returns `nil`.\n public var stringValue: String? {\n guard case let .string(value) = self else { return nil }\n return value\n }\n\n /// Returns the data value and optional MIME type if the value is `data`,\n /// otherwise returns `nil`.\n public var dataValue: (mimeType: String?, Data)? {\n guard case let .data(mimeType: mimeType, data) = self else { return nil }\n return (mimeType: mimeType, data)\n }\n\n /// Returns the `[Value]` value if the value is an `array`,\n /// otherwise returns `nil`.\n public var arrayValue: [Value]? {\n guard case let .array(value) = self else { return nil }\n return value\n }\n\n /// Returns the `[String: Value]` value if the value is an `object`,\n /// otherwise returns `nil`.\n public var objectValue: [String: Value]? {\n guard case let .object(value) = self else { return nil }\n return value\n }\n}\n\n// MARK: - Codable\n\nextension Value: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n\n if container.decodeNil() {\n self = .null\n } else if let value = try? container.decode(Bool.self) {\n self = .bool(value)\n } else if let value = try? container.decode(Int.self) {\n self = .int(value)\n } else if let value = try? container.decode(Double.self) {\n self = .double(value)\n } else if let value = try? container.decode(String.self) {\n if Data.isDataURL(string: value),\n case let (mimeType, data)? = Data.parseDataURL(value)\n {\n self = .data(mimeType: mimeType, data)\n } else {\n self = .string(value)\n }\n } else if let value = try? container.decode([Value].self) {\n self = .array(value)\n } else if let value = try? container.decode([String: Value].self) {\n self = .object(value)\n } else {\n throw DecodingError.dataCorruptedError(\n in: container, debugDescription: \"Value type not found\")\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n\n switch self {\n case .null:\n try container.encodeNil()\n case .bool(let value):\n try container.encode(value)\n case .int(let value):\n try container.encode(value)\n case .double(let value):\n try container.encode(value)\n case .string(let value):\n try container.encode(value)\n case let .data(mimeType, value):\n try container.encode(value.dataURLEncoded(mimeType: mimeType))\n case .array(let value):\n try container.encode(value)\n case .object(let value):\n try container.encode(value)\n }\n }\n}\n\nextension Value: CustomStringConvertible {\n public var description: String {\n switch self {\n case .null:\n return \"\"\n case .bool(let value):\n return value.description\n case .int(let value):\n return value.description\n case .double(let value):\n return value.description\n case .string(let value):\n return value.description\n case let .data(mimeType, value):\n return value.dataURLEncoded(mimeType: mimeType)\n case .array(let value):\n return value.description\n case .object(let value):\n return value.description\n }\n }\n}\n\n// MARK: - ExpressibleByNilLiteral\n\nextension Value: ExpressibleByNilLiteral {\n public init(nilLiteral: ()) {\n self = .null\n }\n}\n\n// MARK: - ExpressibleByBooleanLiteral\n\nextension Value: ExpressibleByBooleanLiteral {\n public init(booleanLiteral value: Bool) {\n self = .bool(value)\n }\n}\n\n// MARK: - ExpressibleByIntegerLiteral\n\nextension Value: ExpressibleByIntegerLiteral {\n public init(integerLiteral value: Int) {\n self = .int(value)\n }\n}\n\n// MARK: - ExpressibleByFloatLiteral\n\nextension Value: ExpressibleByFloatLiteral {\n public init(floatLiteral value: Double) {\n self = .double(value)\n }\n}\n\n// MARK: - ExpressibleByStringLiteral\n\nextension Value: ExpressibleByStringLiteral {\n public init(stringLiteral value: String) {\n self = .string(value)\n }\n}\n\n// MARK: - ExpressibleByArrayLiteral\n\nextension Value: ExpressibleByArrayLiteral {\n public init(arrayLiteral elements: Value...) {\n self = .array(elements)\n }\n}\n\n// MARK: - ExpressibleByDictionaryLiteral\n\nextension Value: ExpressibleByDictionaryLiteral {\n public init(dictionaryLiteral elements: (String, Value)...) {\n var dictionary: [String: Value] = [:]\n for (key, value) in elements {\n dictionary[key] = value\n }\n self = .object(dictionary)\n }\n}\n\n// MARK: - ExpressibleByStringInterpolation\n\nextension Value: ExpressibleByStringInterpolation {\n public struct StringInterpolation: StringInterpolationProtocol {\n var stringValue: String\n\n public init(literalCapacity: Int, interpolationCount: Int) {\n self.stringValue = \"\"\n self.stringValue.reserveCapacity(literalCapacity + interpolationCount)\n }\n\n public mutating func appendLiteral(_ literal: String) {\n self.stringValue.append(literal)\n }\n\n public mutating func appendInterpolation(_ value: T) {\n self.stringValue.append(value.description)\n }\n }\n\n public init(stringInterpolation: StringInterpolation) {\n self = .string(stringInterpolation.stringValue)\n }\n}\n\n// MARK: - Standard Library Type Extensions\n\nextension Bool {\n /// Creates a boolean value from a `Value` instance.\n ///\n /// In strict mode, only `.bool` values are converted. In non-strict mode, the following conversions are supported:\n /// - Integers: `1` is `true`, `0` is `false`\n /// - Doubles: `1.0` is `true`, `0.0` is `false`\n /// - Strings (lowercase only):\n /// - `true`: \"true\", \"t\", \"yes\", \"y\", \"on\", \"1\"\n /// - `false`: \"false\", \"f\", \"no\", \"n\", \"off\", \"0\"\n ///\n /// - Parameters:\n /// - value: The `Value` to convert\n /// - strict: When `true`, only converts from `.bool` values. Defaults to `true`\n /// - Returns: A boolean value if conversion is possible, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// Bool(Value.bool(true)) // Returns true\n /// Bool(Value.int(1), strict: false) // Returns true\n /// Bool(Value.string(\"yes\"), strict: false) // Returns true\n /// ```\n public init?(_ value: Value, strict: Bool = true) {\n switch value {\n case .bool(let b):\n self = b\n case .int(let i) where !strict:\n switch i {\n case 0: self = false\n case 1: self = true\n default: return nil\n }\n case .double(let d) where !strict:\n switch d {\n case 0.0: self = false\n case 1.0: self = true\n default: return nil\n }\n case .string(let s) where !strict:\n switch s {\n case \"true\", \"t\", \"yes\", \"y\", \"on\", \"1\":\n self = true\n case \"false\", \"f\", \"no\", \"n\", \"off\", \"0\":\n self = false\n default:\n return nil\n }\n default:\n return nil\n }\n }\n}\n\nextension Int {\n /// Creates an integer value from a `Value` instance.\n ///\n /// In strict mode, only `.int` values are converted. In non-strict mode, the following conversions are supported:\n /// - Doubles: Converted if they can be represented exactly as integers\n /// - Strings: Parsed if they contain a valid integer representation\n ///\n /// - Parameters:\n /// - value: The `Value` to convert\n /// - strict: When `true`, only converts from `.int` values. Defaults to `true`\n /// - Returns: An integer value if conversion is possible, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// Int(Value.int(42)) // Returns 42\n /// Int(Value.double(42.0), strict: false) // Returns 42\n /// Int(Value.string(\"42\"), strict: false) // Returns 42\n /// Int(Value.double(42.5), strict: false) // Returns nil\n /// ```\n public init?(_ value: Value, strict: Bool = true) {\n switch value {\n case .int(let i):\n self = i\n case .double(let d) where !strict:\n guard let intValue = Int(exactly: d) else { return nil }\n self = intValue\n case .string(let s) where !strict:\n guard let intValue = Int(s) else { return nil }\n self = intValue\n default:\n return nil\n }\n }\n}\n\nextension Double {\n /// Creates a double value from a `Value` instance.\n ///\n /// In strict mode, converts from `.double` and `.int` values. In non-strict mode, the following conversions are supported:\n /// - Integers: Converted to their double representation\n /// - Strings: Parsed if they contain a valid floating-point representation\n ///\n /// - Parameters:\n /// - value: The `Value` to convert\n /// - strict: When `true`, only converts from `.double` and `.int` values. Defaults to `true`\n /// - Returns: A double value if conversion is possible, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// Double(Value.double(42.5)) // Returns 42.5\n /// Double(Value.int(42)) // Returns 42.0\n /// Double(Value.string(\"42.5\"), strict: false) // Returns 42.5\n /// ```\n public init?(_ value: Value, strict: Bool = true) {\n switch value {\n case .double(let d):\n self = d\n case .int(let i):\n self = Double(i)\n case .string(let s) where !strict:\n guard let doubleValue = Double(s) else { return nil }\n self = doubleValue\n default:\n return nil\n }\n }\n}\n\nextension String {\n /// Creates a string value from a `Value` instance.\n ///\n /// In strict mode, only `.string` values are converted. In non-strict mode, the following conversions are supported:\n /// - Integers: Converted to their string representation\n /// - Doubles: Converted to their string representation\n /// - Booleans: Converted to \"true\" or \"false\"\n ///\n /// - Parameters:\n /// - value: The `Value` to convert\n /// - strict: When `true`, only converts from `.string` values. Defaults to `true`\n /// - Returns: A string value if conversion is possible, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// String(Value.string(\"hello\")) // Returns \"hello\"\n /// String(Value.int(42), strict: false) // Returns \"42\"\n /// String(Value.bool(true), strict: false) // Returns \"true\"\n /// ```\n public init?(_ value: Value, strict: Bool = true) {\n switch value {\n case .string(let s):\n self = s\n case .int(let i) where !strict:\n self = String(i)\n case .double(let d) where !strict:\n self = String(d)\n case .bool(let b) where !strict:\n self = String(b)\n default:\n return nil\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Transports/NetworkTransport.swift", "import Foundation\nimport Logging\n\n#if canImport(Network)\n import Network\n\n /// Protocol that abstracts the Network.NWConnection functionality needed for NetworkTransport\n @preconcurrency protocol NetworkConnectionProtocol {\n var state: NWConnection.State { get }\n var stateUpdateHandler: ((@Sendable (NWConnection.State) -> Void))? { get set }\n\n func start(queue: DispatchQueue)\n func cancel()\n func send(\n content: Data?, contentContext: NWConnection.ContentContext, isComplete: Bool,\n completion: NWConnection.SendCompletion)\n func receive(\n minimumIncompleteLength: Int, maximumLength: Int,\n completion: @escaping @Sendable (\n Data?, NWConnection.ContentContext?, Bool, NWError?\n ) -> Void)\n }\n\n /// Extension to conform NWConnection to internal NetworkConnectionProtocol\n extension NWConnection: NetworkConnectionProtocol {}\n\n /// An implementation of a custom MCP transport using Apple's Network framework.\n ///\n /// This transport allows MCP clients and servers to communicate over TCP/UDP connections\n /// using Apple's Network framework.\n ///\n /// - Important: This transport is available exclusively on Apple platforms\n /// (macOS, iOS, watchOS, tvOS, visionOS) as it depends on the Network framework.\n ///\n /// ## Example Usage\n ///\n /// ```swift\n /// import MCP\n /// import Network\n ///\n /// // Create a TCP connection to a server\n /// let connection = NWConnection(\n /// host: NWEndpoint.Host(\"localhost\"),\n /// port: NWEndpoint.Port(8080)!,\n /// using: .tcp\n /// )\n ///\n /// // Initialize the transport with the connection\n /// let transport = NetworkTransport(connection: connection)\n ///\n /// // For large messages (e.g., images), configure unlimited buffer size\n /// let largeBufferTransport = NetworkTransport(\n /// connection: connection,\n /// bufferConfig: .unlimited\n /// )\n ///\n /// // Use the transport with an MCP client\n /// let client = Client(name: \"MyApp\", version: \"1.0.0\")\n /// try await client.connect(transport: transport)\n /// ```\n public actor NetworkTransport: Transport {\n /// Represents a heartbeat message for connection health monitoring.\n public struct Heartbeat: RawRepresentable, Hashable, Sendable {\n /// Magic bytes used to identify a heartbeat message.\n private static let magicBytes: [UInt8] = [0xF0, 0x9F, 0x92, 0x93]\n\n /// The timestamp of when the heartbeat was created.\n public let timestamp: Date\n\n /// Creates a new heartbeat with the current timestamp.\n public init() {\n self.timestamp = Date()\n }\n\n /// Creates a heartbeat with a specific timestamp.\n ///\n /// - Parameter timestamp: The timestamp for the heartbeat.\n public init(timestamp: Date) {\n self.timestamp = timestamp\n }\n\n // MARK: - RawRepresentable\n\n public typealias RawValue = [UInt8]\n\n /// Creates a heartbeat from its raw representation.\n ///\n /// - Parameter rawValue: The raw bytes of the heartbeat message.\n /// - Returns: A heartbeat if the raw value is valid, nil otherwise.\n public init?(rawValue: [UInt8]) {\n // Check if the data has the correct format (magic bytes + timestamp)\n guard rawValue.count >= 12,\n rawValue.prefix(4).elementsEqual(Self.magicBytes)\n else {\n return nil\n }\n\n // Extract the timestamp\n let timestampData = Data(rawValue[4..<12])\n let timestamp = timestampData.withUnsafeBytes {\n $0.load(as: UInt64.self)\n }\n\n self.timestamp = Date(\n timeIntervalSinceReferenceDate: TimeInterval(timestamp) / 1000.0)\n }\n\n /// Converts the heartbeat to its raw representation.\n public var rawValue: [UInt8] {\n var result = Data(Self.magicBytes)\n\n // Add timestamp (milliseconds since reference date)\n let timestamp = UInt64(self.timestamp.timeIntervalSinceReferenceDate * 1000)\n withUnsafeBytes(of: timestamp) { buffer in\n result.append(contentsOf: buffer)\n }\n\n return Array(result)\n }\n\n /// Converts the heartbeat to Data.\n public var data: Data {\n return Data(self.rawValue)\n }\n\n /// Checks if the given data represents a heartbeat message.\n ///\n /// - Parameter data: The data to check.\n /// - Returns: true if the data is a heartbeat message, false otherwise.\n public static func isHeartbeat(_ data: Data) -> Bool {\n guard data.count >= 4 else {\n return false\n }\n\n return data.prefix(4).elementsEqual(Self.magicBytes)\n }\n\n /// Attempts to parse a heartbeat from the given data.\n ///\n /// - Parameter data: The data to parse.\n /// - Returns: A heartbeat if the data is valid, nil otherwise.\n public static func from(data: Data) -> Heartbeat? {\n guard data.count >= 12 else {\n return nil\n }\n\n return Heartbeat(rawValue: Array(data))\n }\n }\n\n /// Configuration for heartbeat behavior.\n public struct HeartbeatConfiguration: Hashable, Sendable {\n /// Whether heartbeats are enabled.\n public let enabled: Bool\n /// Interval between heartbeats in seconds.\n public let interval: TimeInterval\n\n /// Creates a new heartbeat configuration.\n ///\n /// - Parameters:\n /// - enabled: Whether heartbeats are enabled (default: true)\n /// - interval: Interval in seconds between heartbeats (default: 15.0)\n public init(enabled: Bool = true, interval: TimeInterval = 15.0) {\n self.enabled = enabled\n self.interval = interval\n }\n\n /// Default heartbeat configuration.\n public static let `default` = HeartbeatConfiguration()\n\n /// Configuration with heartbeats disabled.\n public static let disabled = HeartbeatConfiguration(enabled: false)\n }\n\n /// Configuration for connection retry behavior.\n public struct ReconnectionConfiguration: Hashable, Sendable {\n /// Whether the transport should attempt to reconnect on failure.\n public let enabled: Bool\n /// Maximum number of reconnection attempts.\n public let maxAttempts: Int\n /// Multiplier for exponential backoff on reconnect.\n public let backoffMultiplier: Double\n\n /// Creates a new reconnection configuration.\n ///\n /// - Parameters:\n /// - enabled: Whether reconnection should be attempted on failure (default: true)\n /// - maxAttempts: Maximum number of reconnection attempts (default: 5)\n /// - backoffMultiplier: Multiplier for exponential backoff on reconnect (default: 1.5)\n public init(\n enabled: Bool = true,\n maxAttempts: Int = 5,\n backoffMultiplier: Double = 1.5\n ) {\n self.enabled = enabled\n self.maxAttempts = maxAttempts\n self.backoffMultiplier = backoffMultiplier\n }\n\n /// Default reconnection configuration.\n public static let `default` = ReconnectionConfiguration()\n\n /// Configuration with reconnection disabled.\n public static let disabled = ReconnectionConfiguration(enabled: false)\n\n /// Calculates the backoff delay for a given attempt number.\n ///\n /// - Parameter attempt: The current attempt number (1-based)\n /// - Returns: The delay in seconds before the next attempt\n public func backoffDelay(for attempt: Int) -> TimeInterval {\n let baseDelay = 0.5 // 500ms\n return baseDelay * pow(backoffMultiplier, Double(attempt - 1))\n }\n }\n\n /// Configuration for buffer behavior.\n public struct BufferConfiguration: Hashable, Sendable {\n /// Maximum buffer size for receiving data chunks.\n /// Set to nil for unlimited (uses system default).\n public let maxReceiveBufferSize: Int?\n\n /// Creates a new buffer configuration.\n ///\n /// - Parameter maxReceiveBufferSize: Maximum buffer size in bytes (default: 10MB, nil for unlimited)\n public init(maxReceiveBufferSize: Int? = 10 * 1024 * 1024) {\n self.maxReceiveBufferSize = maxReceiveBufferSize\n }\n\n /// Default buffer configuration with 10MB limit.\n public static let `default` = BufferConfiguration()\n\n /// Configuration with no buffer size limit.\n public static let unlimited = BufferConfiguration(maxReceiveBufferSize: nil)\n }\n\n // State tracking\n private var isConnected = false\n private var isStopping = false\n private var reconnectAttempt = 0\n private var heartbeatTask: Task?\n private var lastHeartbeatTime: Date?\n private let messageStream: AsyncThrowingStream\n private let messageContinuation: AsyncThrowingStream.Continuation\n\n // Track connection state for continuations\n private var connectionContinuationResumed = false\n\n // Connection is marked nonisolated(unsafe) to allow access from closures\n private nonisolated(unsafe) var connection: NetworkConnectionProtocol\n\n /// Logger instance for transport-related events\n public nonisolated let logger: Logger\n\n // Configuration\n private let heartbeatConfig: HeartbeatConfiguration\n private let reconnectionConfig: ReconnectionConfiguration\n private let bufferConfig: BufferConfiguration\n\n /// Creates a new NetworkTransport with the specified NWConnection\n ///\n /// - Parameters:\n /// - connection: The NWConnection to use for communication\n /// - logger: Optional logger instance for transport events\n /// - reconnectionConfig: Configuration for reconnection behavior (default: .default)\n /// - heartbeatConfig: Configuration for heartbeat behavior (default: .default)\n /// - bufferConfig: Configuration for buffer behavior (default: .default)\n public init(\n connection: NWConnection,\n logger: Logger? = nil,\n heartbeatConfig: HeartbeatConfiguration = .default,\n reconnectionConfig: ReconnectionConfiguration = .default,\n bufferConfig: BufferConfiguration = .default\n ) {\n self.init(\n connection,\n logger: logger,\n heartbeatConfig: heartbeatConfig,\n reconnectionConfig: reconnectionConfig,\n bufferConfig: bufferConfig\n )\n }\n\n init(\n _ connection: NetworkConnectionProtocol,\n logger: Logger? = nil,\n heartbeatConfig: HeartbeatConfiguration = .default,\n reconnectionConfig: ReconnectionConfiguration = .default,\n bufferConfig: BufferConfiguration = .default\n ) {\n self.connection = connection\n self.logger =\n logger\n ?? Logger(\n label: \"mcp.transport.network\",\n factory: { _ in SwiftLogNoOpLogHandler() }\n )\n self.reconnectionConfig = reconnectionConfig\n self.heartbeatConfig = heartbeatConfig\n self.bufferConfig = bufferConfig\n\n // Create message stream\n var continuation: AsyncThrowingStream.Continuation!\n self.messageStream = AsyncThrowingStream { continuation = $0 }\n self.messageContinuation = continuation\n }\n\n /// Establishes connection with the transport\n ///\n /// This initiates the NWConnection and waits for it to become ready.\n /// Once the connection is established, it starts the message receiving loop.\n ///\n /// - Throws: Error if the connection fails to establish\n public func connect() async throws {\n guard !isConnected else { return }\n\n // Reset state for fresh connection\n isStopping = false\n reconnectAttempt = 0\n\n // Reset continuation state\n connectionContinuationResumed = false\n\n // Wait for connection to be ready\n try await withCheckedThrowingContinuation {\n [weak self] (continuation: CheckedContinuation) in\n guard let self = self else {\n continuation.resume(throwing: MCPError.internalError(\"Transport deallocated\"))\n return\n }\n\n connection.stateUpdateHandler = { [weak self] state in\n guard let self = self else { return }\n\n Task { @MainActor in\n switch state {\n case .ready:\n await self.handleConnectionReady(continuation: continuation)\n case .failed(let error):\n await self.handleConnectionFailed(\n error: error, continuation: continuation)\n case .cancelled:\n await self.handleConnectionCancelled(continuation: continuation)\n case .waiting(let error):\n self.logger.debug(\"Connection waiting: \\(error)\")\n case .preparing:\n self.logger.debug(\"Connection preparing...\")\n case .setup:\n self.logger.debug(\"Connection setup...\")\n @unknown default:\n self.logger.warning(\"Unknown connection state\")\n }\n }\n }\n\n connection.start(queue: .main)\n }\n }\n\n /// Handles when the connection reaches the ready state\n ///\n /// - Parameter continuation: The continuation to resume when connection is ready\n private func handleConnectionReady(continuation: CheckedContinuation)\n async\n {\n if !connectionContinuationResumed {\n connectionContinuationResumed = true\n isConnected = true\n\n // Reset reconnect attempt counter on successful connection\n reconnectAttempt = 0\n logger.info(\"Network transport connected successfully\")\n continuation.resume()\n\n // Start the receive loop after connection is established\n Task { await self.receiveLoop() }\n\n // Start heartbeat task if enabled\n if heartbeatConfig.enabled {\n startHeartbeat()\n }\n }\n }\n\n /// Starts a task to periodically send heartbeats to check connection health\n private func startHeartbeat() {\n // Cancel any existing heartbeat task\n heartbeatTask?.cancel()\n\n // Start a new heartbeat task\n heartbeatTask = Task { [weak self] in\n guard let self = self else { return }\n\n // Initial delay before starting heartbeats\n try? await Task.sleep(for: .seconds(1))\n\n while !Task.isCancelled {\n do {\n // Check actor-isolated properties first\n let isStopping = await self.isStopping\n let isConnected = await self.isConnected\n\n guard !isStopping && isConnected else { break }\n\n try await self.sendHeartbeat()\n try await Task.sleep(for: .seconds(self.heartbeatConfig.interval))\n } catch {\n // If heartbeat fails, log and retry after a shorter interval\n self.logger.warning(\"Heartbeat failed: \\(error)\")\n try? await Task.sleep(for: .seconds(2))\n }\n }\n }\n }\n\n /// Sends a heartbeat message to verify connection health\n private func sendHeartbeat() async throws {\n guard isConnected && !isStopping else { return }\n\n // Try to send the heartbeat (without the newline delimiter used for normal messages)\n try await withCheckedThrowingContinuation {\n [weak self] (continuation: CheckedContinuation) in\n guard let self = self else {\n continuation.resume(throwing: MCPError.internalError(\"Transport deallocated\"))\n return\n }\n\n connection.send(\n content: Heartbeat().data,\n contentContext: .defaultMessage,\n isComplete: true,\n completion: .contentProcessed { [weak self] error in\n if let error = error {\n continuation.resume(throwing: error)\n } else {\n Task { [weak self] in\n await self?.setLastHeartbeatTime(Date())\n }\n continuation.resume()\n }\n })\n }\n\n logger.trace(\"Heartbeat sent\")\n }\n\n /// Handles connection failure\n ///\n /// - Parameters:\n /// - error: The error that caused the connection to fail\n /// - continuation: The continuation to resume with the error\n private func handleConnectionFailed(\n error: Swift.Error, continuation: CheckedContinuation\n ) async {\n if !connectionContinuationResumed {\n connectionContinuationResumed = true\n logger.error(\"Connection failed: \\(error)\")\n\n await handleReconnection(\n error: error,\n continuation: continuation,\n context: \"failure\"\n )\n }\n }\n\n /// Handles connection cancellation\n ///\n /// - Parameter continuation: The continuation to resume with cancellation error\n private func handleConnectionCancelled(continuation: CheckedContinuation)\n async\n {\n if !connectionContinuationResumed {\n connectionContinuationResumed = true\n logger.warning(\"Connection cancelled\")\n\n await handleReconnection(\n error: MCPError.internalError(\"Connection cancelled\"),\n continuation: continuation,\n context: \"cancellation\"\n )\n }\n }\n\n /// Common reconnection handling logic\n ///\n /// - Parameters:\n /// - error: The error that triggered the reconnection\n /// - continuation: The continuation to resume with the error\n /// - context: The context of the reconnection (for logging)\n private func handleReconnection(\n error: Swift.Error,\n continuation: CheckedContinuation,\n context: String\n ) async {\n if !isStopping,\n reconnectionConfig.enabled,\n reconnectAttempt < reconnectionConfig.maxAttempts\n {\n // Try to reconnect with exponential backoff\n reconnectAttempt += 1\n logger.info(\n \"Attempting reconnection after \\(context) (\\(reconnectAttempt)/\\(reconnectionConfig.maxAttempts))...\"\n )\n\n // Calculate backoff delay\n let delay = reconnectionConfig.backoffDelay(for: reconnectAttempt)\n\n // Schedule reconnection attempt after delay\n Task {\n try? await Task.sleep(for: .seconds(delay))\n if !isStopping {\n // Cancel the current connection before attempting to reconnect.\n self.connection.cancel()\n // Resume original continuation with error; outer logic or a new call to connect() will handle retry.\n continuation.resume(throwing: error)\n } else {\n continuation.resume(throwing: error) // Stopping, so fail.\n }\n }\n } else {\n // Not configured to reconnect, exceeded max attempts, or stopping\n self.connection.cancel() // Ensure connection is cancelled\n continuation.resume(throwing: error)\n }\n }\n\n /// Disconnects from the transport\n ///\n /// This cancels the NWConnection, finalizes the message stream,\n /// and releases associated resources.\n public func disconnect() async {\n guard isConnected else { return }\n\n // Mark as stopping to prevent reconnection attempts during disconnect\n isStopping = true\n isConnected = false\n\n // Cancel heartbeat task if it exists\n heartbeatTask?.cancel()\n heartbeatTask = nil\n\n connection.cancel()\n messageContinuation.finish()\n logger.info(\"Network transport disconnected\")\n }\n\n /// Sends data through the network connection\n ///\n /// This sends a JSON-RPC message through the NWConnection, adding a newline\n /// delimiter to mark the end of the message.\n ///\n /// - Parameter message: The JSON-RPC message to send\n /// - Throws: MCPError for transport failures or connection issues\n public func send(_ message: Data) async throws {\n guard isConnected else {\n throw MCPError.internalError(\"Transport not connected\")\n }\n\n // Add newline as delimiter\n var messageWithNewline = message\n messageWithNewline.append(UInt8(ascii: \"\\n\"))\n\n // Use a local actor-isolated variable to track continuation state\n var sendContinuationResumed = false\n\n try await withCheckedThrowingContinuation {\n [weak self] (continuation: CheckedContinuation) in\n guard let self = self else {\n continuation.resume(throwing: MCPError.internalError(\"Transport deallocated\"))\n return\n }\n\n connection.send(\n content: messageWithNewline,\n contentContext: .defaultMessage,\n isComplete: true,\n completion: .contentProcessed { [weak self] error in\n guard let self = self else { return }\n\n Task { @MainActor in\n if !sendContinuationResumed {\n sendContinuationResumed = true\n if let error = error {\n self.logger.error(\"Send error: \\(error)\")\n\n // Check if we should attempt to reconnect on send failure\n let isStopping = await self.isStopping // Await actor-isolated property\n if !isStopping && self.reconnectionConfig.enabled {\n let isConnected = await self.isConnected\n if isConnected {\n if error.isConnectionLost {\n self.logger.warning(\n \"Connection appears broken, will attempt to reconnect...\"\n )\n\n // Schedule connection restart\n Task { [weak self] in // Operate on self's executor\n guard let self = self else { return }\n\n await self.setIsConnected(false)\n\n try? await Task.sleep(for: .milliseconds(500))\n\n let currentIsStopping = await self.isStopping\n if !currentIsStopping {\n // Cancel the connection, then attempt to reconnect fully.\n self.connection.cancel()\n try? await self.connect()\n }\n }\n }\n }\n }\n\n continuation.resume(\n throwing: MCPError.internalError(\"Send error: \\(error)\"))\n } else {\n continuation.resume()\n }\n }\n }\n })\n }\n }\n\n /// Receives data in an async sequence\n ///\n /// This returns an AsyncThrowingStream that emits Data objects representing\n /// each JSON-RPC message received from the network connection.\n ///\n /// - Returns: An AsyncThrowingStream of Data objects\n public func receive() -> AsyncThrowingStream {\n return messageStream\n }\n\n /// Continuous loop to receive and process incoming messages\n ///\n /// This method runs continuously while the connection is active,\n /// receiving data and yielding complete messages to the message stream.\n /// Messages are delimited by newline characters.\n private func receiveLoop() async {\n var buffer = Data()\n var consecutiveEmptyReads = 0\n let maxConsecutiveEmptyReads = 5\n\n while isConnected && !Task.isCancelled && !isStopping {\n do {\n let newData = try await receiveData()\n\n // Check for EOF or empty data\n if newData.isEmpty {\n consecutiveEmptyReads += 1\n\n if consecutiveEmptyReads >= maxConsecutiveEmptyReads {\n logger.warning(\n \"Multiple consecutive empty reads (\\(consecutiveEmptyReads)), possible connection issue\"\n )\n\n // Check connection state\n if connection.state != .ready {\n logger.info(\"Connection no longer ready, exiting receive loop\")\n break\n }\n }\n\n // Brief pause before retry\n try await Task.sleep(for: .milliseconds(100))\n continue\n }\n\n // Check if this is a heartbeat message\n if Heartbeat.isHeartbeat(newData) {\n logger.trace(\"Received heartbeat from peer\")\n\n // Extract timestamp if available\n if let heartbeat = Heartbeat.from(data: newData) {\n logger.trace(\"Heartbeat timestamp: \\(heartbeat.timestamp)\")\n }\n\n // Reset the counter since we got valid data\n consecutiveEmptyReads = 0\n continue // Skip regular message processing for heartbeats\n }\n\n // Reset counter on successful data read\n consecutiveEmptyReads = 0\n buffer.append(newData)\n\n // Process complete messages\n while let newlineIndex = buffer.firstIndex(of: UInt8(ascii: \"\\n\")) {\n let messageData = buffer[.. Data {\n var receiveContinuationResumed = false\n\n return try await withCheckedThrowingContinuation {\n [weak self] (continuation: CheckedContinuation) in\n guard let self = self else {\n continuation.resume(throwing: MCPError.internalError(\"Transport deallocated\"))\n return\n }\n\n let maxLength = bufferConfig.maxReceiveBufferSize ?? Int.max\n connection.receive(minimumIncompleteLength: 1, maximumLength: maxLength) {\n content, _, isComplete, error in\n Task { @MainActor in\n if !receiveContinuationResumed {\n receiveContinuationResumed = true\n if let error = error {\n continuation.resume(throwing: MCPError.transportError(error))\n } else if let content = content {\n continuation.resume(returning: content)\n } else if isComplete {\n self.logger.trace(\"Connection completed by peer\")\n continuation.resume(throwing: MCPError.connectionClosed)\n } else {\n // EOF: Resume with empty data instead of throwing an error\n continuation.resume(returning: Data())\n }\n }\n }\n }\n }\n }\n\n private func setLastHeartbeatTime(_ time: Date) {\n self.lastHeartbeatTime = time\n }\n\n private func setIsConnected(_ connected: Bool) {\n self.isConnected = connected\n }\n }\n\n extension NWError {\n /// Whether this error indicates a connection has been lost or reset.\n fileprivate var isConnectionLost: Bool {\n let nsError = self as NSError\n return nsError.code == 57 // Socket is not connected (EHOSTUNREACH or ENOTCONN)\n || nsError.code == 54 // Connection reset by peer (ECONNRESET)\n }\n }\n#endif\n"], ["/swift-sdk/Sources/MCP/Base/Transports/HTTPClientTransport.swift", "import Foundation\nimport Logging\n\n#if !os(Linux)\n import EventSource\n#endif\n\n#if canImport(FoundationNetworking)\n import FoundationNetworking\n#endif\n\n/// An implementation of the MCP Streamable HTTP transport protocol for clients.\n///\n/// This transport implements the [Streamable HTTP transport](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http)\n/// specification from the Model Context Protocol.\n///\n/// It supports:\n/// - Sending JSON-RPC messages via HTTP POST requests\n/// - Receiving responses via both direct JSON responses and SSE streams\n/// - Session management using the `Mcp-Session-Id` header\n/// - Automatic reconnection for dropped SSE streams\n/// - Platform-specific optimizations for different operating systems\n///\n/// The transport supports two modes:\n/// - Regular HTTP (`streaming=false`): Simple request/response pattern\n/// - Streaming HTTP with SSE (`streaming=true`): Enables server-to-client push messages\n///\n/// - Important: Server-Sent Events (SSE) functionality is not supported on Linux platforms.\n///\n/// ## Example Usage\n///\n/// ```swift\n/// import MCP\n///\n/// // Create a streaming HTTP transport\n/// let transport = HTTPClientTransport(\n/// endpoint: URL(string: \"http://localhost:8080\")!,\n/// )\n///\n/// // Initialize the client with streaming transport\n/// let client = Client(name: \"MyApp\", version: \"1.0.0\")\n/// try await client.connect(transport: transport)\n///\n/// // The transport will automatically handle SSE events\n/// // and deliver them through the client's notification handlers\n/// ```\npublic actor HTTPClientTransport: Transport {\n /// The server endpoint URL to connect to\n public let endpoint: URL\n private let session: URLSession\n\n /// The session ID assigned by the server, used for maintaining state across requests\n public private(set) var sessionID: String?\n private let streaming: Bool\n private var streamingTask: Task?\n\n /// Logger instance for transport-related events\n public nonisolated let logger: Logger\n\n /// Maximum time to wait for a session ID before proceeding with SSE connection\n public let sseInitializationTimeout: TimeInterval\n\n private var isConnected = false\n private let messageStream: AsyncThrowingStream\n private let messageContinuation: AsyncThrowingStream.Continuation\n\n private var initialSessionIDSignalTask: Task?\n private var initialSessionIDContinuation: CheckedContinuation?\n\n /// Creates a new HTTP transport client with the specified endpoint\n ///\n /// - Parameters:\n /// - endpoint: The server URL to connect to\n /// - configuration: URLSession configuration to use for HTTP requests\n /// - streaming: Whether to enable SSE streaming mode (default: true)\n /// - sseInitializationTimeout: Maximum time to wait for session ID before proceeding with SSE (default: 10 seconds)\n /// - logger: Optional logger instance for transport events\n public init(\n endpoint: URL,\n configuration: URLSessionConfiguration = .default,\n streaming: Bool = true,\n sseInitializationTimeout: TimeInterval = 10,\n logger: Logger? = nil\n ) {\n self.init(\n endpoint: endpoint,\n session: URLSession(configuration: configuration),\n streaming: streaming,\n sseInitializationTimeout: sseInitializationTimeout,\n logger: logger\n )\n }\n\n internal init(\n endpoint: URL,\n session: URLSession,\n streaming: Bool = false,\n sseInitializationTimeout: TimeInterval = 10,\n logger: Logger? = nil\n ) {\n self.endpoint = endpoint\n self.session = session\n self.streaming = streaming\n self.sseInitializationTimeout = sseInitializationTimeout\n\n // Create message stream\n var continuation: AsyncThrowingStream.Continuation!\n self.messageStream = AsyncThrowingStream { continuation = $0 }\n self.messageContinuation = continuation\n\n self.logger =\n logger\n ?? Logger(\n label: \"mcp.transport.http.client\",\n factory: { _ in SwiftLogNoOpLogHandler() }\n )\n }\n\n // Setup the initial session ID signal\n private func setupInitialSessionIDSignal() {\n self.initialSessionIDSignalTask = Task {\n await withCheckedContinuation { continuation in\n self.initialSessionIDContinuation = continuation\n // This task will suspend here until continuation.resume() is called\n }\n }\n }\n\n // Trigger the initial session ID signal when a session ID is established\n private func triggerInitialSessionIDSignal() {\n if let continuation = self.initialSessionIDContinuation {\n continuation.resume()\n self.initialSessionIDContinuation = nil // Consume the continuation\n logger.trace(\"Initial session ID signal triggered for SSE task.\")\n }\n }\n\n /// Establishes connection with the transport\n ///\n /// This prepares the transport for communication and sets up SSE streaming\n /// if streaming mode is enabled. The actual HTTP connection happens with the\n /// first message sent.\n public func connect() async throws {\n guard !isConnected else { return }\n isConnected = true\n\n // Setup initial session ID signal\n setupInitialSessionIDSignal()\n\n if streaming {\n // Start listening to server events\n streamingTask = Task { await startListeningForServerEvents() }\n }\n\n logger.info(\"HTTP transport connected\")\n }\n\n /// Disconnects from the transport\n ///\n /// This terminates any active connections, cancels the streaming task,\n /// and releases any resources being used by the transport.\n public func disconnect() async {\n guard isConnected else { return }\n isConnected = false\n\n // Cancel streaming task if active\n streamingTask?.cancel()\n streamingTask = nil\n\n // Cancel any in-progress requests\n session.invalidateAndCancel()\n\n // Clean up message stream\n messageContinuation.finish()\n\n // Cancel the initial session ID signal task if active\n initialSessionIDSignalTask?.cancel()\n initialSessionIDSignalTask = nil\n // Resume the continuation if it's still pending to avoid leaks\n initialSessionIDContinuation?.resume()\n initialSessionIDContinuation = nil\n\n logger.info(\"HTTP clienttransport disconnected\")\n }\n\n /// Sends data through an HTTP POST request\n ///\n /// This sends a JSON-RPC message to the server via HTTP POST and processes\n /// the response according to the MCP Streamable HTTP specification. It handles:\n ///\n /// - Adding appropriate Accept headers for both JSON and SSE\n /// - Including the session ID in requests if one has been established\n /// - Processing different response types (JSON vs SSE)\n /// - Handling HTTP error codes according to the specification\n ///\n /// - Parameter data: The JSON-RPC message to send\n /// - Throws: MCPError for transport failures or server errors\n public func send(_ data: Data) async throws {\n guard isConnected else {\n throw MCPError.internalError(\"Transport not connected\")\n }\n\n var request = URLRequest(url: endpoint)\n request.httpMethod = \"POST\"\n request.addValue(\"application/json, text/event-stream\", forHTTPHeaderField: \"Accept\")\n request.addValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\n request.httpBody = data\n\n // Add session ID if available\n if let sessionID = sessionID {\n request.addValue(sessionID, forHTTPHeaderField: \"Mcp-Session-Id\")\n }\n\n #if os(Linux)\n // Linux implementation using data(for:) instead of bytes(for:)\n let (responseData, response) = try await session.data(for: request)\n try await processResponse(response: response, data: responseData)\n #else\n // macOS and other platforms with bytes(for:) support\n let (responseStream, response) = try await session.bytes(for: request)\n try await processResponse(response: response, stream: responseStream)\n #endif\n }\n\n #if os(Linux)\n // Process response with data payload (Linux)\n private func processResponse(response: URLResponse, data: Data) async throws {\n guard let httpResponse = response as? HTTPURLResponse else {\n throw MCPError.internalError(\"Invalid HTTP response\")\n }\n\n // Process the response based on content type and status code\n let contentType = httpResponse.value(forHTTPHeaderField: \"Content-Type\") ?? \"\"\n\n // Extract session ID if present\n if let newSessionID = httpResponse.value(forHTTPHeaderField: \"Mcp-Session-Id\") {\n let wasSessionIDNil = (self.sessionID == nil)\n self.sessionID = newSessionID\n if wasSessionIDNil {\n // Trigger signal on first session ID\n triggerInitialSessionIDSignal()\n }\n logger.debug(\"Session ID received\", metadata: [\"sessionID\": \"\\(newSessionID)\"])\n }\n\n try processHTTPResponse(httpResponse, contentType: contentType)\n guard case 200..<300 = httpResponse.statusCode else { return }\n\n // For JSON responses, yield the data\n if contentType.contains(\"text/event-stream\") {\n logger.warning(\"SSE responses aren't fully supported on Linux\")\n messageContinuation.yield(data)\n } else if contentType.contains(\"application/json\") {\n logger.trace(\"Received JSON response\", metadata: [\"size\": \"\\(data.count)\"])\n messageContinuation.yield(data)\n } else {\n logger.warning(\"Unexpected content type: \\(contentType)\")\n }\n }\n #else\n // Process response with byte stream (macOS, iOS, etc.)\n private func processResponse(response: URLResponse, stream: URLSession.AsyncBytes)\n async throws\n {\n guard let httpResponse = response as? HTTPURLResponse else {\n throw MCPError.internalError(\"Invalid HTTP response\")\n }\n\n // Process the response based on content type and status code\n let contentType = httpResponse.value(forHTTPHeaderField: \"Content-Type\") ?? \"\"\n\n // Extract session ID if present\n if let newSessionID = httpResponse.value(forHTTPHeaderField: \"Mcp-Session-Id\") {\n let wasSessionIDNil = (self.sessionID == nil)\n self.sessionID = newSessionID\n if wasSessionIDNil {\n // Trigger signal on first session ID\n triggerInitialSessionIDSignal()\n }\n logger.debug(\"Session ID received\", metadata: [\"sessionID\": \"\\(newSessionID)\"])\n }\n\n try processHTTPResponse(httpResponse, contentType: contentType)\n guard case 200..<300 = httpResponse.statusCode else { return }\n\n if contentType.contains(\"text/event-stream\") {\n // For SSE, processing happens via the stream\n logger.trace(\"Received SSE response, processing in streaming task\")\n try await self.processSSE(stream)\n } else if contentType.contains(\"application/json\") {\n // For JSON responses, collect and deliver the data\n var buffer = Data()\n for try await byte in stream {\n buffer.append(byte)\n }\n logger.trace(\"Received JSON response\", metadata: [\"size\": \"\\(buffer.count)\"])\n messageContinuation.yield(buffer)\n } else {\n logger.warning(\"Unexpected content type: \\(contentType)\")\n }\n }\n #endif\n\n // Common HTTP response handling for all platforms\n private func processHTTPResponse(_ response: HTTPURLResponse, contentType: String) throws {\n // Handle status codes according to HTTP semantics\n switch response.statusCode {\n case 200..<300:\n // Success range - these are handled by the platform-specific code\n return\n\n case 400:\n throw MCPError.internalError(\"Bad request\")\n\n case 401:\n throw MCPError.internalError(\"Authentication required\")\n\n case 403:\n throw MCPError.internalError(\"Access forbidden\")\n\n case 404:\n // If we get a 404 with a session ID, it means our session is invalid\n if sessionID != nil {\n logger.warning(\"Session has expired\")\n sessionID = nil\n throw MCPError.internalError(\"Session expired\")\n }\n throw MCPError.internalError(\"Endpoint not found\")\n\n case 405:\n // If we get a 405, it means the server does not support the requested method\n // If streaming was requested, we should cancel the streaming task\n if streaming {\n self.streamingTask?.cancel()\n throw MCPError.internalError(\"Server does not support streaming\")\n }\n throw MCPError.internalError(\"Method not allowed\")\n\n case 408:\n throw MCPError.internalError(\"Request timeout\")\n\n case 429:\n throw MCPError.internalError(\"Too many requests\")\n\n case 500..<600:\n // Server error range\n throw MCPError.internalError(\"Server error: \\(response.statusCode)\")\n\n default:\n throw MCPError.internalError(\n \"Unexpected HTTP response: \\(response.statusCode) (\\(contentType))\")\n }\n }\n\n /// Receives data in an async sequence\n ///\n /// This returns an AsyncThrowingStream that emits Data objects representing\n /// each JSON-RPC message received from the server. This includes:\n ///\n /// - Direct responses to client requests\n /// - Server-initiated messages delivered via SSE streams\n ///\n /// - Returns: An AsyncThrowingStream of Data objects\n public func receive() -> AsyncThrowingStream {\n return messageStream\n }\n\n // MARK: - SSE\n\n /// Starts listening for server events using SSE\n ///\n /// This establishes a long-lived HTTP connection using Server-Sent Events (SSE)\n /// to enable server-to-client push messaging. It handles:\n ///\n /// - Waiting for session ID if needed\n /// - Opening the SSE connection\n /// - Automatic reconnection on connection drops\n /// - Processing received events\n private func startListeningForServerEvents() async {\n #if os(Linux)\n // SSE is not fully supported on Linux\n if streaming {\n logger.warning(\n \"SSE streaming was requested but is not fully supported on Linux. SSE connection will not be attempted.\"\n )\n }\n #else\n // This is the original code for platforms that support SSE\n guard isConnected else { return }\n\n // Wait for the initial session ID signal, but only if sessionID isn't already set\n if self.sessionID == nil, let signalTask = self.initialSessionIDSignalTask {\n logger.trace(\"SSE streaming task waiting for initial sessionID signal...\")\n\n // Race the signalTask against a timeout\n let timeoutTask = Task {\n try? await Task.sleep(for: .seconds(self.sseInitializationTimeout))\n return false\n }\n\n let signalCompletionTask = Task {\n await signalTask.value\n return true // Indicates signal received\n }\n\n // Use TaskGroup to race the two tasks\n var signalReceived = false\n do {\n signalReceived = try await withThrowingTaskGroup(of: Bool.self) { group in\n group.addTask {\n await signalCompletionTask.value\n }\n group.addTask {\n await timeoutTask.value\n }\n\n // Take the first result and cancel the other task\n if let firstResult = try await group.next() {\n group.cancelAll()\n return firstResult\n }\n return false\n }\n } catch {\n logger.error(\"Error while waiting for session ID signal: \\(error)\")\n }\n\n // Clean up tasks\n timeoutTask.cancel()\n\n if signalReceived {\n logger.trace(\"SSE streaming task proceeding after initial sessionID signal.\")\n } else {\n logger.warning(\n \"Timeout waiting for initial sessionID signal. SSE stream will proceed (sessionID might be nil).\"\n )\n }\n } else if self.sessionID != nil {\n logger.trace(\n \"Initial sessionID already available. Proceeding with SSE streaming task immediately.\"\n )\n } else {\n logger.info(\n \"Proceeding with SSE connection attempt; sessionID is nil. This might be expected for stateless servers or if initialize hasn't provided one yet.\"\n )\n }\n\n // Retry loop for connection drops\n while isConnected && !Task.isCancelled {\n do {\n try await connectToEventStream()\n } catch {\n if !Task.isCancelled {\n logger.error(\"SSE connection error: \\(error)\")\n // Wait before retrying\n try? await Task.sleep(for: .seconds(1))\n }\n }\n }\n #endif\n }\n\n #if !os(Linux)\n /// Establishes an SSE connection to the server\n ///\n /// This initiates a GET request to the server endpoint with appropriate\n /// headers to establish an SSE stream according to the MCP specification.\n ///\n /// - Throws: MCPError for connection failures or server errors\n private func connectToEventStream() async throws {\n guard isConnected else { return }\n\n var request = URLRequest(url: endpoint)\n request.httpMethod = \"GET\"\n request.addValue(\"text/event-stream\", forHTTPHeaderField: \"Accept\")\n request.addValue(\"no-cache\", forHTTPHeaderField: \"Cache-Control\")\n\n // Add session ID if available\n if let sessionID = sessionID {\n request.addValue(sessionID, forHTTPHeaderField: \"Mcp-Session-Id\")\n }\n\n logger.debug(\"Starting SSE connection\")\n\n // Create URLSession task for SSE\n let (stream, response) = try await session.bytes(for: request)\n\n guard let httpResponse = response as? HTTPURLResponse else {\n throw MCPError.internalError(\"Invalid HTTP response\")\n }\n\n // Check response status\n guard httpResponse.statusCode == 200 else {\n // If the server returns 405 Method Not Allowed,\n // it indicates that the server doesn't support SSE streaming.\n // We should cancel the task instead of retrying the connection.\n if httpResponse.statusCode == 405 {\n self.streamingTask?.cancel()\n }\n throw MCPError.internalError(\"HTTP error: \\(httpResponse.statusCode)\")\n }\n\n // Extract session ID if present\n if let newSessionID = httpResponse.value(forHTTPHeaderField: \"Mcp-Session-Id\") {\n let wasSessionIDNil = (self.sessionID == nil)\n self.sessionID = newSessionID\n if wasSessionIDNil {\n // Trigger signal on first session ID, though this is unlikely to happen here\n // as GET usually follows a POST that would have already set the session ID\n triggerInitialSessionIDSignal()\n }\n logger.debug(\"Session ID received\", metadata: [\"sessionID\": \"\\(newSessionID)\"])\n }\n\n try await self.processSSE(stream)\n }\n\n /// Processes an SSE byte stream, extracting events and delivering them\n ///\n /// - Parameter stream: The URLSession.AsyncBytes stream to process\n /// - Throws: Error for stream processing failures\n private func processSSE(_ stream: URLSession.AsyncBytes) async throws {\n do {\n for try await event in stream.events {\n // Check if task has been cancelled\n if Task.isCancelled { break }\n\n logger.trace(\n \"SSE event received\",\n metadata: [\n \"type\": \"\\(event.event ?? \"message\")\",\n \"id\": \"\\(event.id ?? \"none\")\",\n ]\n )\n\n // Convert the event data to Data and yield it to the message stream\n if !event.data.isEmpty, let data = event.data.data(using: .utf8) {\n messageContinuation.yield(data)\n }\n }\n } catch {\n logger.error(\"Error processing SSE events: \\(error)\")\n throw error\n }\n }\n #endif\n}\n"], ["/swift-sdk/Sources/MCP/Base/Transports/StdioTransport.swift", "import Logging\n\nimport struct Foundation.Data\n\n#if canImport(System)\n import System\n#else\n @preconcurrency import SystemPackage\n#endif\n\n// Import for specific low-level operations not yet in Swift System\n#if canImport(Darwin)\n import Darwin.POSIX\n#elseif canImport(Glibc)\n import Glibc\n#endif\n\n#if canImport(Darwin) || canImport(Glibc)\n /// An implementation of the MCP stdio transport protocol.\n ///\n /// This transport implements the [stdio transport](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#stdio)\n /// specification from the Model Context Protocol.\n ///\n /// The stdio transport works by:\n /// - Reading JSON-RPC messages from standard input\n /// - Writing JSON-RPC messages to standard output\n /// - Using newline characters as message delimiters\n /// - Supporting non-blocking I/O operations\n ///\n /// This transport is the recommended option for most MCP applications due to its\n /// simplicity and broad platform support.\n ///\n /// - Important: This transport is available on Apple platforms and Linux distributions with glibc\n /// (Ubuntu, Debian, Fedora, CentOS, RHEL).\n ///\n /// ## Example Usage\n ///\n /// ```swift\n /// import MCP\n ///\n /// // Initialize the client\n /// let client = Client(name: \"MyApp\", version: \"1.0.0\")\n ///\n /// // Create a transport and connect\n /// let transport = StdioTransport()\n /// try await client.connect(transport: transport)\n /// ```\n public actor StdioTransport: Transport {\n private let input: FileDescriptor\n private let output: FileDescriptor\n /// Logger instance for transport-related events\n public nonisolated let logger: Logger\n\n private var isConnected = false\n private let messageStream: AsyncThrowingStream\n private let messageContinuation: AsyncThrowingStream.Continuation\n\n /// Creates a new stdio transport with the specified file descriptors\n ///\n /// - Parameters:\n /// - input: File descriptor for reading (defaults to standard input)\n /// - output: File descriptor for writing (defaults to standard output)\n /// - logger: Optional logger instance for transport events\n public init(\n input: FileDescriptor = FileDescriptor.standardInput,\n output: FileDescriptor = FileDescriptor.standardOutput,\n logger: Logger? = nil\n ) {\n self.input = input\n self.output = output\n self.logger =\n logger\n ?? Logger(\n label: \"mcp.transport.stdio\",\n factory: { _ in SwiftLogNoOpLogHandler() })\n\n // Create message stream\n var continuation: AsyncThrowingStream.Continuation!\n self.messageStream = AsyncThrowingStream { continuation = $0 }\n self.messageContinuation = continuation\n }\n\n /// Establishes connection with the transport\n ///\n /// This method configures the file descriptors for non-blocking I/O\n /// and starts the background message reading loop.\n ///\n /// - Throws: Error if the file descriptors cannot be configured\n public func connect() async throws {\n guard !isConnected else { return }\n\n // Set non-blocking mode\n try setNonBlocking(fileDescriptor: input)\n try setNonBlocking(fileDescriptor: output)\n\n isConnected = true\n logger.info(\"Transport connected successfully\")\n\n // Start reading loop in background\n Task {\n await readLoop()\n }\n }\n\n /// Configures a file descriptor for non-blocking I/O\n ///\n /// - Parameter fileDescriptor: The file descriptor to configure\n /// - Throws: Error if the operation fails\n private func setNonBlocking(fileDescriptor: FileDescriptor) throws {\n #if canImport(Darwin) || canImport(Glibc)\n // Get current flags\n let flags = fcntl(fileDescriptor.rawValue, F_GETFL)\n guard flags >= 0 else {\n throw MCPError.transportError(Errno(rawValue: CInt(errno)))\n }\n\n // Set non-blocking flag\n let result = fcntl(fileDescriptor.rawValue, F_SETFL, flags | O_NONBLOCK)\n guard result >= 0 else {\n throw MCPError.transportError(Errno(rawValue: CInt(errno)))\n }\n #else\n // For platforms where non-blocking operations aren't supported\n throw MCPError.internalError(\n \"Setting non-blocking mode not supported on this platform\")\n #endif\n }\n\n /// Continuous loop that reads and processes incoming messages\n ///\n /// This method runs in the background while the transport is connected,\n /// parsing complete messages delimited by newlines and yielding them\n /// to the message stream.\n private func readLoop() async {\n let bufferSize = 4096\n var buffer = [UInt8](repeating: 0, count: bufferSize)\n var pendingData = Data()\n\n while isConnected && !Task.isCancelled {\n do {\n let bytesRead = try buffer.withUnsafeMutableBufferPointer { pointer in\n try input.read(into: UnsafeMutableRawBufferPointer(pointer))\n }\n\n if bytesRead == 0 {\n logger.notice(\"EOF received\")\n break\n }\n\n pendingData.append(Data(buffer[.. 0 {\n remaining = remaining.dropFirst(written)\n }\n } catch let error where MCPError.isResourceTemporarilyUnavailable(error) {\n try await Task.sleep(for: .milliseconds(10))\n continue\n } catch {\n throw MCPError.transportError(error)\n }\n }\n }\n\n /// Receives messages from the transport.\n ///\n /// Messages may be individual JSON-RPC requests, notifications, responses,\n /// or batches containing multiple requests/notifications encoded as JSON arrays.\n /// Each message is guaranteed to be a complete JSON object or array.\n ///\n /// - Returns: An AsyncThrowingStream of Data objects representing JSON-RPC messages\n public func receive() -> AsyncThrowingStream {\n return messageStream\n }\n }\n#endif\n"], ["/swift-sdk/Sources/MCP/Base/Error.swift", "import Foundation\n\n#if canImport(System)\n import System\n#else\n @preconcurrency import SystemPackage\n#endif\n\n/// A model context protocol error.\npublic enum MCPError: Swift.Error, Sendable {\n // Standard JSON-RPC 2.0 errors (-32700 to -32603)\n case parseError(String?) // -32700\n case invalidRequest(String?) // -32600\n case methodNotFound(String?) // -32601\n case invalidParams(String?) // -32602\n case internalError(String?) // -32603\n\n // Server errors (-32000 to -32099)\n case serverError(code: Int, message: String)\n\n // Transport specific errors\n case connectionClosed\n case transportError(Swift.Error)\n\n /// The JSON-RPC 2.0 error code\n public var code: Int {\n switch self {\n case .parseError: return -32700\n case .invalidRequest: return -32600\n case .methodNotFound: return -32601\n case .invalidParams: return -32602\n case .internalError: return -32603\n case .serverError(let code, _): return code\n case .connectionClosed: return -32000\n case .transportError: return -32001\n }\n }\n\n /// Check if an error represents a \"resource temporarily unavailable\" condition\n public static func isResourceTemporarilyUnavailable(_ error: Swift.Error) -> Bool {\n #if canImport(System)\n if let errno = error as? System.Errno, errno == .resourceTemporarilyUnavailable {\n return true\n }\n #else\n if let errno = error as? SystemPackage.Errno, errno == .resourceTemporarilyUnavailable {\n return true\n }\n #endif\n return false\n }\n}\n\n// MARK: LocalizedError\n\nextension MCPError: LocalizedError {\n public var errorDescription: String? {\n switch self {\n case .parseError(let detail):\n return \"Parse error: Invalid JSON\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .invalidRequest(let detail):\n return \"Invalid Request\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .methodNotFound(let detail):\n return \"Method not found\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .invalidParams(let detail):\n return \"Invalid params\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .internalError(let detail):\n return \"Internal error\" + (detail.map { \": \\($0)\" } ?? \"\")\n case .serverError(_, let message):\n return \"Server error: \\(message)\"\n case .connectionClosed:\n return \"Connection closed\"\n case .transportError(let error):\n return \"Transport error: \\(error.localizedDescription)\"\n }\n }\n\n public var failureReason: String? {\n switch self {\n case .parseError:\n return \"The server received invalid JSON that could not be parsed\"\n case .invalidRequest:\n return \"The JSON sent is not a valid Request object\"\n case .methodNotFound:\n return \"The method does not exist or is not available\"\n case .invalidParams:\n return \"Invalid method parameter(s)\"\n case .internalError:\n return \"Internal JSON-RPC error\"\n case .serverError:\n return \"Server-defined error occurred\"\n case .connectionClosed:\n return \"The connection to the server was closed\"\n case .transportError(let error):\n return (error as? LocalizedError)?.failureReason ?? error.localizedDescription\n }\n }\n\n public var recoverySuggestion: String? {\n switch self {\n case .parseError:\n return \"Verify that the JSON being sent is valid and well-formed\"\n case .invalidRequest:\n return \"Ensure the request follows the JSON-RPC 2.0 specification format\"\n case .methodNotFound:\n return \"Check the method name and ensure it is supported by the server\"\n case .invalidParams:\n return \"Verify the parameters match the method's expected parameters\"\n case .connectionClosed:\n return \"Try reconnecting to the server\"\n default:\n return nil\n }\n }\n}\n\n// MARK: CustomDebugStringConvertible\n\nextension MCPError: CustomDebugStringConvertible {\n public var debugDescription: String {\n switch self {\n case .transportError(let error):\n return\n \"[\\(code)] \\(errorDescription ?? \"\") (Underlying error: \\(String(reflecting: error)))\"\n default:\n return \"[\\(code)] \\(errorDescription ?? \"\")\"\n }\n }\n\n}\n\n// MARK: Codable\n\nextension MCPError: Codable {\n private enum CodingKeys: String, CodingKey {\n case code, message, data\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(code, forKey: .code)\n try container.encode(errorDescription ?? \"Unknown error\", forKey: .message)\n\n // Encode additional data if available\n switch self {\n case .parseError(let detail),\n .invalidRequest(let detail),\n .methodNotFound(let detail),\n .invalidParams(let detail),\n .internalError(let detail):\n if let detail = detail {\n try container.encode([\"detail\": detail], forKey: .data)\n }\n case .serverError(_, _):\n // No additional data for server errors\n break\n case .connectionClosed:\n break\n case .transportError(let error):\n try container.encode(\n [\"error\": error.localizedDescription],\n forKey: .data\n )\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let code = try container.decode(Int.self, forKey: .code)\n let message = try container.decode(String.self, forKey: .message)\n let data = try container.decodeIfPresent([String: Value].self, forKey: .data)\n\n // Helper to extract detail from data, falling back to message if needed\n let unwrapDetail: (String?) -> String? = { fallback in\n guard let detailValue = data?[\"detail\"] else { return fallback }\n if case .string(let str) = detailValue { return str }\n return fallback\n }\n\n switch code {\n case -32700:\n self = .parseError(unwrapDetail(message))\n case -32600:\n self = .invalidRequest(unwrapDetail(message))\n case -32601:\n self = .methodNotFound(unwrapDetail(message))\n case -32602:\n self = .invalidParams(unwrapDetail(message))\n case -32603:\n self = .internalError(unwrapDetail(nil))\n case -32000:\n self = .connectionClosed\n case -32001:\n // Extract underlying error string if present\n let underlyingErrorString =\n data?[\"error\"].flatMap { val -> String? in\n if case .string(let str) = val { return str }\n return nil\n } ?? message\n self = .transportError(\n NSError(\n domain: \"org.jsonrpc.error\",\n code: code,\n userInfo: [NSLocalizedDescriptionKey: underlyingErrorString]\n )\n )\n default:\n self = .serverError(code: code, message: message)\n }\n }\n}\n\n// MARK: Equatable\n\nextension MCPError: Equatable {\n public static func == (lhs: MCPError, rhs: MCPError) -> Bool {\n lhs.code == rhs.code\n }\n}\n\n// MARK: Hashable\n\nextension MCPError: Hashable {\n public func hash(into hasher: inout Hasher) {\n hasher.combine(code)\n switch self {\n case .parseError(let detail):\n hasher.combine(detail)\n case .invalidRequest(let detail):\n hasher.combine(detail)\n case .methodNotFound(let detail):\n hasher.combine(detail)\n case .invalidParams(let detail):\n hasher.combine(detail)\n case .internalError(let detail):\n hasher.combine(detail)\n case .serverError(_, let message):\n hasher.combine(message)\n case .connectionClosed:\n break\n case .transportError(let error):\n hasher.combine(error.localizedDescription)\n }\n }\n}\n\n// MARK: -\n\n/// This is provided to allow existing code that uses `MCP.Error` to continue\n/// to work without modification.\n///\n/// The MCPError type is now the recommended way to handle errors in MCP.\n@available(*, deprecated, renamed: \"MCPError\", message: \"Use MCPError instead of MCP.Error\")\npublic typealias Error = MCPError\n"], ["/swift-sdk/Sources/MCP/Client/Client.swift", "import Logging\n\nimport struct Foundation.Data\nimport struct Foundation.Date\nimport class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\n/// Model Context Protocol client\npublic actor Client {\n /// The client configuration\n public struct Configuration: Hashable, Codable, Sendable {\n /// The default configuration.\n public static let `default` = Configuration(strict: false)\n\n /// The strict configuration.\n public static let strict = Configuration(strict: true)\n\n /// When strict mode is enabled, the client:\n /// - Requires server capabilities to be initialized before making requests\n /// - Rejects all requests that require capabilities before initialization\n ///\n /// While the MCP specification requires servers to respond to initialize requests\n /// with their capabilities, some implementations may not follow this.\n /// Disabling strict mode allows the client to be more lenient with non-compliant\n /// servers, though this may lead to undefined behavior.\n public var strict: Bool\n\n public init(strict: Bool = false) {\n self.strict = strict\n }\n }\n\n /// Implementation information\n public struct Info: Hashable, Codable, Sendable {\n /// The client name\n public var name: String\n /// The client version\n public var version: String\n\n public init(name: String, version: String) {\n self.name = name\n self.version = version\n }\n }\n\n /// The client capabilities\n public struct Capabilities: Hashable, Codable, Sendable {\n /// The roots capabilities\n public struct Roots: Hashable, Codable, Sendable {\n /// Whether the list of roots has changed\n public var listChanged: Bool?\n\n public init(listChanged: Bool? = nil) {\n self.listChanged = listChanged\n }\n }\n\n /// The sampling capabilities\n public struct Sampling: Hashable, Codable, Sendable {\n public init() {}\n }\n\n /// Whether the client supports sampling\n public var sampling: Sampling?\n /// Experimental features supported by the client\n public var experimental: [String: String]?\n /// Whether the client supports roots\n public var roots: Capabilities.Roots?\n\n public init(\n sampling: Sampling? = nil,\n experimental: [String: String]? = nil,\n roots: Capabilities.Roots? = nil\n ) {\n self.sampling = sampling\n self.experimental = experimental\n self.roots = roots\n }\n }\n\n /// The connection to the server\n private var connection: (any Transport)?\n /// The logger for the client\n private var logger: Logger? {\n get async {\n await connection?.logger\n }\n }\n\n /// The client information\n private let clientInfo: Client.Info\n /// The client name\n public nonisolated var name: String { clientInfo.name }\n /// The client version\n public nonisolated var version: String { clientInfo.version }\n\n /// The client capabilities\n public var capabilities: Client.Capabilities\n /// The client configuration\n public var configuration: Configuration\n\n /// The server capabilities\n private var serverCapabilities: Server.Capabilities?\n /// The server version\n private var serverVersion: String?\n /// The server instructions\n private var instructions: String?\n\n /// A dictionary of type-erased notification handlers, keyed by method name\n private var notificationHandlers: [String: [NotificationHandlerBox]] = [:]\n /// The task for the message handling loop\n private var task: Task?\n\n /// An error indicating a type mismatch when decoding a pending request\n private struct TypeMismatchError: Swift.Error {}\n\n /// A pending request with a continuation for the result\n private struct PendingRequest {\n let continuation: CheckedContinuation\n }\n\n /// A type-erased pending request\n private struct AnyPendingRequest {\n private let _resume: (Result) -> Void\n\n init(_ request: PendingRequest) {\n _resume = { result in\n switch result {\n case .success(let value):\n if let typedValue = value as? T {\n request.continuation.resume(returning: typedValue)\n } else if let value = value as? Value,\n let data = try? JSONEncoder().encode(value),\n let decoded = try? JSONDecoder().decode(T.self, from: data)\n {\n request.continuation.resume(returning: decoded)\n } else {\n request.continuation.resume(throwing: TypeMismatchError())\n }\n case .failure(let error):\n request.continuation.resume(throwing: error)\n }\n }\n }\n func resume(returning value: Any) {\n _resume(.success(value))\n }\n\n func resume(throwing error: Swift.Error) {\n _resume(.failure(error))\n }\n }\n\n /// A dictionary of type-erased pending requests, keyed by request ID\n private var pendingRequests: [ID: AnyPendingRequest] = [:]\n // Add reusable JSON encoder/decoder\n private let encoder = JSONEncoder()\n private let decoder = JSONDecoder()\n\n public init(\n name: String,\n version: String,\n configuration: Configuration = .default\n ) {\n self.clientInfo = Client.Info(name: name, version: version)\n self.capabilities = Capabilities()\n self.configuration = configuration\n }\n\n /// Connect to the server using the given transport\n @discardableResult\n public func connect(transport: any Transport) async throws -> Initialize.Result {\n self.connection = transport\n try await self.connection?.connect()\n\n await logger?.info(\n \"Client connected\", metadata: [\"name\": \"\\(name)\", \"version\": \"\\(version)\"])\n\n // Start message handling loop\n task = Task {\n guard let connection = self.connection else { return }\n repeat {\n // Check for cancellation before starting the iteration\n if Task.isCancelled { break }\n\n do {\n let stream = await connection.receive()\n for try await data in stream {\n if Task.isCancelled { break } // Check inside loop too\n\n // Attempt to decode data\n // Try decoding as a batch response first\n if let batchResponse = try? decoder.decode([AnyResponse].self, from: data) {\n await handleBatchResponse(batchResponse)\n } else if let response = try? decoder.decode(AnyResponse.self, from: data) {\n await handleResponse(response)\n } else if let message = try? decoder.decode(AnyMessage.self, from: data) {\n await handleMessage(message)\n } else {\n var metadata: Logger.Metadata = [:]\n if let string = String(data: data, encoding: .utf8) {\n metadata[\"message\"] = .string(string)\n }\n await logger?.warning(\n \"Unexpected message received by client (not single/batch response or notification)\",\n metadata: metadata\n )\n }\n }\n } catch let error where MCPError.isResourceTemporarilyUnavailable(error) {\n try? await Task.sleep(for: .milliseconds(10))\n continue\n } catch {\n await logger?.error(\n \"Error in message handling loop\", metadata: [\"error\": \"\\(error)\"])\n break\n }\n } while true\n await self.logger?.info(\"Client message handling loop task is terminating.\")\n }\n\n // Automatically initialize after connecting\n return try await _initialize()\n }\n\n /// Disconnect the client and cancel all pending requests\n public func disconnect() async {\n await logger?.info(\"Initiating client disconnect...\")\n\n // Part 1: Inside actor - Grab state and clear internal references\n let taskToCancel = self.task\n let connectionToDisconnect = self.connection\n let pendingRequestsToCancel = self.pendingRequests\n\n self.task = nil\n self.connection = nil\n self.pendingRequests = [:] // Use empty dictionary literal\n\n // Part 2: Outside actor - Resume continuations, disconnect transport, await task\n\n // Resume continuations first\n for (_, request) in pendingRequestsToCancel {\n request.resume(throwing: MCPError.internalError(\"Client disconnected\"))\n }\n await logger?.info(\"Pending requests cancelled.\")\n\n // Cancel the task\n taskToCancel?.cancel()\n await logger?.info(\"Message loop task cancellation requested.\")\n\n // Disconnect the transport *before* awaiting the task\n // This should ensure the transport stream is finished, unblocking the loop.\n if let conn = connectionToDisconnect {\n await conn.disconnect()\n await logger?.info(\"Transport disconnected.\")\n } else {\n await logger?.info(\"No active transport connection to disconnect.\")\n }\n\n // Await the task completion *after* transport disconnect\n _ = await taskToCancel?.value\n await logger?.info(\"Client message loop task finished.\")\n\n await logger?.info(\"Client disconnect complete.\")\n }\n\n // MARK: - Registration\n\n /// Register a handler for a notification\n @discardableResult\n public func onNotification(\n _ type: N.Type,\n handler: @escaping @Sendable (Message) async throws -> Void\n ) async -> Self {\n let handlers = notificationHandlers[N.name, default: []]\n notificationHandlers[N.name] = handlers + [TypedNotificationHandler(handler)]\n return self\n }\n\n /// Send a notification to the server\n public func notify(_ notification: Message) async throws {\n guard let connection = connection else {\n throw MCPError.internalError(\"Client connection not initialized\")\n }\n\n let notificationData = try encoder.encode(notification)\n try await connection.send(notificationData)\n }\n\n // MARK: - Requests\n\n /// Send a request and receive its response\n public func send(_ request: Request) async throws -> M.Result {\n guard let connection = connection else {\n throw MCPError.internalError(\"Client connection not initialized\")\n }\n\n let requestData = try encoder.encode(request)\n\n // Store the pending request first\n return try await withCheckedThrowingContinuation { continuation in\n Task {\n // Add the pending request before attempting to send\n self.addPendingRequest(\n id: request.id,\n continuation: continuation,\n type: M.Result.self\n )\n\n // Send the request data\n do {\n // Use the existing connection send\n try await connection.send(requestData)\n } catch {\n // If send fails, try to remove the pending request.\n // Resume with the send error only if we successfully removed the request,\n // indicating the response handler hasn't processed it yet.\n if self.removePendingRequest(id: request.id) != nil {\n continuation.resume(throwing: error)\n }\n // Otherwise, the request was already removed by the response handler\n // or by disconnect, so the continuation was already resumed.\n // Do nothing here.\n }\n }\n }\n }\n\n private func addPendingRequest(\n id: ID,\n continuation: CheckedContinuation,\n type: T.Type // Keep type for AnyPendingRequest internal logic\n ) {\n pendingRequests[id] = AnyPendingRequest(PendingRequest(continuation: continuation))\n }\n\n private func removePendingRequest(id: ID) -> AnyPendingRequest? {\n return pendingRequests.removeValue(forKey: id)\n }\n\n // MARK: - Batching\n\n /// A batch of requests.\n ///\n /// Objects of this type are passed as an argument to the closure\n /// of the ``Client/withBatch(_:)`` method.\n public actor Batch {\n unowned let client: Client\n var requests: [AnyRequest] = []\n\n init(client: Client) {\n self.client = client\n }\n\n /// Adds a request to the batch and prepares its expected response task.\n /// The actual sending happens when the `withBatch` scope completes.\n /// - Returns: A `Task` that will eventually produce the result or throw an error.\n public func addRequest(_ request: Request) async throws -> Task<\n M.Result, Swift.Error\n > {\n requests.append(try AnyRequest(request))\n\n // Return a Task that registers the pending request and awaits its result.\n // The continuation is resumed when the response arrives.\n return Task {\n try await withCheckedThrowingContinuation { continuation in\n // We are already inside a Task, but need another Task\n // to bridge to the client actor's context.\n Task {\n await client.addPendingRequest(\n id: request.id,\n continuation: continuation,\n type: M.Result.self\n )\n }\n }\n }\n }\n }\n\n /// Executes multiple requests in a single batch.\n ///\n /// This method allows you to group multiple MCP requests together,\n /// which are then sent to the server as a single JSON array.\n /// The server processes these requests and sends back a corresponding\n /// JSON array of responses.\n ///\n /// Within the `body` closure, use the provided `Batch` actor to add\n /// requests using `batch.addRequest(_:)`. Each call to `addRequest`\n /// returns a `Task` handle representing the asynchronous operation\n /// for that specific request's result.\n ///\n /// It's recommended to collect these `Task` handles into an array\n /// within the `body` closure`. After the `withBatch` method returns\n /// (meaning the batch request has been sent), you can then process\n /// the results by awaiting each `Task` in the collected array.\n ///\n /// Example 1: Batching multiple tool calls and collecting typed tasks:\n /// ```swift\n /// // Array to hold the task handles for each tool call\n /// var toolTasks: [Task] = []\n /// try await client.withBatch { batch in\n /// for i in 0..<10 {\n /// toolTasks.append(\n /// try await batch.addRequest(\n /// CallTool.request(.init(name: \"square\", arguments: [\"n\": i]))\n /// )\n /// )\n /// }\n /// }\n ///\n /// // Process results after the batch is sent\n /// print(\"Processing \\(toolTasks.count) tool results...\")\n /// for (index, task) in toolTasks.enumerated() {\n /// do {\n /// let result = try await task.value\n /// print(\"\\(index): \\(result.content)\")\n /// } catch {\n /// print(\"\\(index) failed: \\(error)\")\n /// }\n /// }\n /// ```\n ///\n /// Example 2: Batching different request types and awaiting individual tasks:\n /// ```swift\n /// // Declare optional task variables beforehand\n /// var pingTask: Task?\n /// var promptTask: Task?\n ///\n /// try await client.withBatch { batch in\n /// // Assign the tasks within the batch closure\n /// pingTask = try await batch.addRequest(Ping.request())\n /// promptTask = try await batch.addRequest(GetPrompt.request(.init(name: \"greeting\")))\n /// }\n ///\n /// // Await the results after the batch is sent\n /// do {\n /// if let pingTask = pingTask {\n /// try await pingTask.value // Await ping result (throws if ping failed)\n /// print(\"Ping successful\")\n /// }\n /// if let promptTask = promptTask {\n /// let promptResult = try await promptTask.value // Await prompt result\n /// print(\"Prompt description: \\(promptResult.description ?? \"None\")\")\n /// }\n /// } catch {\n /// print(\"Error processing batch results: \\(error)\")\n /// }\n /// ```\n ///\n /// - Parameter body: An asynchronous closure that takes a `Batch` object as input.\n /// Use this object to add requests to the batch.\n /// - Throws: `MCPError.internalError` if the client is not connected.\n /// Can also rethrow errors from the `body` closure or from sending the batch request.\n public func withBatch(body: @escaping (Batch) async throws -> Void) async throws {\n guard let connection = connection else {\n throw MCPError.internalError(\"Client connection not initialized\")\n }\n\n // Create Batch actor, passing self (Client)\n let batch = Batch(client: self)\n\n // Populate the batch actor by calling the user's closure.\n try await body(batch)\n\n // Get the collected requests from the batch actor\n let requests = await batch.requests\n\n // Check if there are any requests to send\n guard !requests.isEmpty else {\n await logger?.info(\"Batch requested but no requests were added.\")\n return // Nothing to send\n }\n\n await logger?.debug(\n \"Sending batch request\", metadata: [\"count\": \"\\(requests.count)\"])\n\n // Encode the array of AnyMethod requests into a single JSON payload\n let data = try encoder.encode(requests)\n try await connection.send(data)\n\n // Responses will be handled asynchronously by the message loop and handleBatchResponse/handleResponse.\n }\n\n // MARK: - Lifecycle\n\n /// Initialize the connection with the server.\n ///\n /// - Important: This method is deprecated. Initialization now happens automatically\n /// when calling `connect(transport:)`. You should use that method instead.\n ///\n /// - Returns: The server's initialization response containing capabilities and server info\n @available(\n *, deprecated,\n message:\n \"Initialization now happens automatically during connect. Use connect(transport:) instead.\"\n )\n public func initialize() async throws -> Initialize.Result {\n return try await _initialize()\n }\n\n /// Internal initialization implementation\n private func _initialize() async throws -> Initialize.Result {\n let request = Initialize.request(\n .init(\n protocolVersion: Version.latest,\n capabilities: capabilities,\n clientInfo: clientInfo\n ))\n\n let result = try await send(request)\n\n self.serverCapabilities = result.capabilities\n self.serverVersion = result.protocolVersion\n self.instructions = result.instructions\n\n try await notify(InitializedNotification.message())\n\n return result\n }\n\n public func ping() async throws {\n let request = Ping.request()\n _ = try await send(request)\n }\n\n // MARK: - Prompts\n\n public func getPrompt(name: String, arguments: [String: Value]? = nil) async throws\n -> (description: String?, messages: [Prompt.Message])\n {\n try validateServerCapability(\\.prompts, \"Prompts\")\n let request = GetPrompt.request(.init(name: name, arguments: arguments))\n let result = try await send(request)\n return (description: result.description, messages: result.messages)\n }\n\n public func listPrompts(cursor: String? = nil) async throws\n -> (prompts: [Prompt], nextCursor: String?)\n {\n try validateServerCapability(\\.prompts, \"Prompts\")\n let request: Request\n if let cursor = cursor {\n request = ListPrompts.request(.init(cursor: cursor))\n } else {\n request = ListPrompts.request(.init())\n }\n let result = try await send(request)\n return (prompts: result.prompts, nextCursor: result.nextCursor)\n }\n\n // MARK: - Resources\n\n public func readResource(uri: String) async throws -> [Resource.Content] {\n try validateServerCapability(\\.resources, \"Resources\")\n let request = ReadResource.request(.init(uri: uri))\n let result = try await send(request)\n return result.contents\n }\n\n public func listResources(cursor: String? = nil) async throws -> (\n resources: [Resource], nextCursor: String?\n ) {\n try validateServerCapability(\\.resources, \"Resources\")\n let request: Request\n if let cursor = cursor {\n request = ListResources.request(.init(cursor: cursor))\n } else {\n request = ListResources.request(.init())\n }\n let result = try await send(request)\n return (resources: result.resources, nextCursor: result.nextCursor)\n }\n\n public func subscribeToResource(uri: String) async throws {\n try validateServerCapability(\\.resources?.subscribe, \"Resource subscription\")\n let request = ResourceSubscribe.request(.init(uri: uri))\n _ = try await send(request)\n }\n\n public func listResourceTemplates(cursor: String? = nil) async throws -> (\n templates: [Resource.Template], nextCursor: String?\n ) {\n try validateServerCapability(\\.resources, \"Resources\")\n let request: Request\n if let cursor = cursor {\n request = ListResourceTemplates.request(.init(cursor: cursor))\n } else {\n request = ListResourceTemplates.request(.init())\n }\n let result = try await send(request)\n return (templates: result.templates, nextCursor: result.nextCursor)\n }\n\n // MARK: - Tools\n\n public func listTools(cursor: String? = nil) async throws -> (\n tools: [Tool], nextCursor: String?\n ) {\n try validateServerCapability(\\.tools, \"Tools\")\n let request: Request\n if let cursor = cursor {\n request = ListTools.request(.init(cursor: cursor))\n } else {\n request = ListTools.request(.init())\n }\n let result = try await send(request)\n return (tools: result.tools, nextCursor: result.nextCursor)\n }\n\n public func callTool(name: String, arguments: [String: Value]? = nil) async throws -> (\n content: [Tool.Content], isError: Bool?\n ) {\n try validateServerCapability(\\.tools, \"Tools\")\n let request = CallTool.request(.init(name: name, arguments: arguments))\n let result = try await send(request)\n return (content: result.content, isError: result.isError)\n }\n\n // MARK: - Sampling\n\n /// Register a handler for sampling requests from servers\n ///\n /// Sampling allows servers to request LLM completions through the client,\n /// enabling sophisticated agentic behaviors while maintaining human-in-the-loop control.\n ///\n /// The sampling flow follows these steps:\n /// 1. Server sends a `sampling/createMessage` request to the client\n /// 2. Client reviews the request and can modify it (via this handler)\n /// 3. Client samples from an LLM (via this handler)\n /// 4. Client reviews the completion (via this handler)\n /// 5. Client returns the result to the server\n ///\n /// - Parameter handler: A closure that processes sampling requests and returns completions\n /// - Returns: Self for method chaining\n /// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/sampling#how-sampling-works\n @discardableResult\n public func withSamplingHandler(\n _ handler: @escaping @Sendable (CreateSamplingMessage.Parameters) async throws ->\n CreateSamplingMessage.Result\n ) -> Self {\n // Note: This would require extending the client architecture to handle incoming requests from servers.\n // The current MCP Swift SDK architecture assumes clients only send requests to servers,\n // but sampling requires bidirectional communication where servers can send requests to clients.\n //\n // A full implementation would need:\n // 1. Request handlers in the client (similar to how servers handle requests)\n // 2. Bidirectional transport support\n // 3. Request/response correlation for server-to-client requests\n //\n // For now, this serves as the correct API design for when bidirectional support is added.\n\n // This would register the handler similar to how servers register method handlers:\n // methodHandlers[CreateSamplingMessage.name] = TypedRequestHandler(handler)\n\n return self\n }\n\n // MARK: -\n\n private func handleResponse(_ response: Response) async {\n await logger?.trace(\n \"Processing response\",\n metadata: [\"id\": \"\\(response.id)\"])\n\n // Attempt to remove the pending request using the response ID.\n // Resume with the response only if it hadn't yet been removed.\n if let removedRequest = self.removePendingRequest(id: response.id) {\n // If we successfully removed it, resume its continuation.\n switch response.result {\n case .success(let value):\n removedRequest.resume(returning: value)\n case .failure(let error):\n removedRequest.resume(throwing: error)\n }\n } else {\n // Request was already removed (e.g., by send error handler or disconnect).\n // Log this, but it's not an error in race condition scenarios.\n await logger?.warning(\n \"Attempted to handle response for already removed request\",\n metadata: [\"id\": \"\\(response.id)\"]\n )\n }\n }\n\n private func handleMessage(_ message: Message) async {\n await logger?.trace(\n \"Processing notification\",\n metadata: [\"method\": \"\\(message.method)\"])\n\n // Find notification handlers for this method\n guard let handlers = notificationHandlers[message.method] else { return }\n\n // Convert notification parameters to concrete type and call handlers\n for handler in handlers {\n do {\n try await handler(message)\n } catch {\n await logger?.error(\n \"Error handling notification\",\n metadata: [\n \"method\": \"\\(message.method)\",\n \"error\": \"\\(error)\",\n ])\n }\n }\n }\n\n // MARK: -\n\n /// Validate the server capabilities.\n /// Throws an error if the client is configured to be strict and the capability is not supported.\n private func validateServerCapability(\n _ keyPath: KeyPath,\n _ name: String\n )\n throws\n {\n if configuration.strict {\n guard let capabilities = serverCapabilities else {\n throw MCPError.methodNotFound(\"Server capabilities not initialized\")\n }\n guard capabilities[keyPath: keyPath] != nil else {\n throw MCPError.methodNotFound(\"\\(name) is not supported by the server\")\n }\n }\n }\n\n // Add handler for batch responses\n private func handleBatchResponse(_ responses: [AnyResponse]) async {\n await logger?.trace(\"Processing batch response\", metadata: [\"count\": \"\\(responses.count)\"])\n for response in responses {\n // Attempt to remove the pending request.\n // If successful, pendingRequest contains the request.\n if let pendingRequest = self.removePendingRequest(id: response.id) {\n // If we successfully removed it, handle the response using the pending request.\n switch response.result {\n case .success(let value):\n pendingRequest.resume(returning: value)\n case .failure(let error):\n pendingRequest.resume(throwing: error)\n }\n } else {\n // If removal failed, it means the request ID was not found (or already handled).\n // Log a warning.\n await logger?.warning(\n \"Received response in batch for unknown or already handled request ID\",\n metadata: [\"id\": \"\\(response.id)\"]\n )\n }\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Server/Server.swift", "import Logging\n\nimport struct Foundation.Data\nimport struct Foundation.Date\nimport class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\n/// Model Context Protocol server\npublic actor Server {\n /// The server configuration\n public struct Configuration: Hashable, Codable, Sendable {\n /// The default configuration.\n public static let `default` = Configuration(strict: false)\n\n /// The strict configuration.\n public static let strict = Configuration(strict: true)\n\n /// When strict mode is enabled, the server:\n /// - Requires clients to send an initialize request before any other requests\n /// - Rejects all requests from uninitialized clients with a protocol error\n ///\n /// While the MCP specification requires clients to initialize the connection\n /// before sending other requests, some implementations may not follow this.\n /// Disabling strict mode allows the server to be more lenient with non-compliant\n /// clients, though this may lead to undefined behavior.\n public var strict: Bool\n }\n\n /// Implementation information\n public struct Info: Hashable, Codable, Sendable {\n /// The server name\n public let name: String\n /// The server version\n public let version: String\n\n public init(name: String, version: String) {\n self.name = name\n self.version = version\n }\n }\n\n /// Server capabilities\n public struct Capabilities: Hashable, Codable, Sendable {\n /// Resources capabilities\n public struct Resources: Hashable, Codable, Sendable {\n /// Whether the resource can be subscribed to\n public var subscribe: Bool?\n /// Whether the list of resources has changed\n public var listChanged: Bool?\n\n public init(\n subscribe: Bool? = nil,\n listChanged: Bool? = nil\n ) {\n self.subscribe = subscribe\n self.listChanged = listChanged\n }\n }\n\n /// Tools capabilities\n public struct Tools: Hashable, Codable, Sendable {\n /// Whether the server notifies clients when tools change\n public var listChanged: Bool?\n\n public init(listChanged: Bool? = nil) {\n self.listChanged = listChanged\n }\n }\n\n /// Prompts capabilities\n public struct Prompts: Hashable, Codable, Sendable {\n /// Whether the server notifies clients when prompts change\n public var listChanged: Bool?\n\n public init(listChanged: Bool? = nil) {\n self.listChanged = listChanged\n }\n }\n\n /// Logging capabilities\n public struct Logging: Hashable, Codable, Sendable {\n public init() {}\n }\n\n /// Sampling capabilities\n public struct Sampling: Hashable, Codable, Sendable {\n public init() {}\n }\n\n /// Logging capabilities\n public var logging: Logging?\n /// Prompts capabilities\n public var prompts: Prompts?\n /// Resources capabilities\n public var resources: Resources?\n /// Sampling capabilities\n public var sampling: Sampling?\n /// Tools capabilities\n public var tools: Tools?\n\n public init(\n logging: Logging? = nil,\n prompts: Prompts? = nil,\n resources: Resources? = nil,\n sampling: Sampling? = nil,\n tools: Tools? = nil\n ) {\n self.logging = logging\n self.prompts = prompts\n self.resources = resources\n self.sampling = sampling\n self.tools = tools\n }\n }\n\n /// Server information\n private let serverInfo: Server.Info\n /// The server connection\n private var connection: (any Transport)?\n /// The server logger\n private var logger: Logger? {\n get async {\n await connection?.logger\n }\n }\n\n /// The server name\n public nonisolated var name: String { serverInfo.name }\n /// The server version\n public nonisolated var version: String { serverInfo.version }\n /// The server capabilities\n public var capabilities: Capabilities\n /// The server configuration\n public var configuration: Configuration\n\n /// Request handlers\n private var methodHandlers: [String: RequestHandlerBox] = [:]\n /// Notification handlers\n private var notificationHandlers: [String: [NotificationHandlerBox]] = [:]\n\n /// Whether the server is initialized\n private var isInitialized = false\n /// The client information\n private var clientInfo: Client.Info?\n /// The client capabilities\n private var clientCapabilities: Client.Capabilities?\n /// The protocol version\n private var protocolVersion: String?\n /// The list of subscriptions\n private var subscriptions: [String: Set] = [:]\n /// The task for the message handling loop\n private var task: Task?\n\n public init(\n name: String,\n version: String,\n capabilities: Server.Capabilities = .init(),\n configuration: Configuration = .default\n ) {\n self.serverInfo = Server.Info(name: name, version: version)\n self.capabilities = capabilities\n self.configuration = configuration\n }\n\n /// Start the server\n /// - Parameters:\n /// - transport: The transport to use for the server\n /// - initializeHook: An optional hook that runs when the client sends an initialize request\n public func start(\n transport: any Transport,\n initializeHook: (@Sendable (Client.Info, Client.Capabilities) async throws -> Void)? = nil\n ) async throws {\n self.connection = transport\n registerDefaultHandlers(initializeHook: initializeHook)\n try await transport.connect()\n\n await logger?.info(\n \"Server started\", metadata: [\"name\": \"\\(name)\", \"version\": \"\\(version)\"])\n\n // Start message handling loop\n task = Task {\n do {\n let stream = await transport.receive()\n for try await data in stream {\n if Task.isCancelled { break } // Check cancellation inside loop\n\n var requestID: ID?\n do {\n // Attempt to decode as batch first, then as individual request or notification\n let decoder = JSONDecoder()\n if let batch = try? decoder.decode(Server.Batch.self, from: data) {\n try await handleBatch(batch)\n } else if let request = try? decoder.decode(AnyRequest.self, from: data) {\n _ = try await handleRequest(request, sendResponse: true)\n } else if let message = try? decoder.decode(AnyMessage.self, from: data) {\n try await handleMessage(message)\n } else {\n // Try to extract request ID from raw JSON if possible\n if let json = try? JSONDecoder().decode(\n [String: Value].self, from: data),\n let idValue = json[\"id\"]\n {\n if let strValue = idValue.stringValue {\n requestID = .string(strValue)\n } else if let intValue = idValue.intValue {\n requestID = .number(intValue)\n }\n }\n throw MCPError.parseError(\"Invalid message format\")\n }\n } catch let error where MCPError.isResourceTemporarilyUnavailable(error) {\n // Resource temporarily unavailable, retry after a short delay\n try? await Task.sleep(for: .milliseconds(10))\n continue\n } catch {\n await logger?.error(\n \"Error processing message\", metadata: [\"error\": \"\\(error)\"])\n let response = AnyMethod.response(\n id: requestID ?? .random,\n error: error as? MCPError\n ?? MCPError.internalError(error.localizedDescription)\n )\n try? await send(response)\n }\n }\n } catch {\n await logger?.error(\n \"Fatal error in message handling loop\", metadata: [\"error\": \"\\(error)\"])\n }\n await logger?.info(\"Server finished\", metadata: [:])\n }\n }\n\n /// Stop the server\n public func stop() async {\n task?.cancel()\n task = nil\n if let connection = connection {\n await connection.disconnect()\n }\n connection = nil\n }\n\n public func waitUntilCompleted() async {\n await task?.value\n }\n\n // MARK: - Registration\n\n /// Register a method handler\n @discardableResult\n public func withMethodHandler(\n _ type: M.Type,\n handler: @escaping @Sendable (M.Parameters) async throws -> M.Result\n ) -> Self {\n methodHandlers[M.name] = TypedRequestHandler { (request: Request) -> Response in\n let result = try await handler(request.params)\n return Response(id: request.id, result: result)\n }\n return self\n }\n\n /// Register a notification handler\n @discardableResult\n public func onNotification(\n _ type: N.Type,\n handler: @escaping @Sendable (Message) async throws -> Void\n ) -> Self {\n let handlers = notificationHandlers[N.name, default: []]\n notificationHandlers[N.name] = handlers + [TypedNotificationHandler(handler)]\n return self\n }\n\n // MARK: - Sending\n\n /// Send a response to a request\n public func send(_ response: Response) async throws {\n guard let connection = connection else {\n throw MCPError.internalError(\"Server connection not initialized\")\n }\n\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]\n\n let responseData = try encoder.encode(response)\n try await connection.send(responseData)\n }\n\n /// Send a notification to connected clients\n public func notify(_ notification: Message) async throws {\n guard let connection = connection else {\n throw MCPError.internalError(\"Server connection not initialized\")\n }\n\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]\n\n let notificationData = try encoder.encode(notification)\n try await connection.send(notificationData)\n }\n\n // MARK: - Sampling\n\n /// Request sampling from the connected client\n ///\n /// Sampling allows servers to request LLM completions through the client,\n /// enabling sophisticated agentic behaviors while maintaining human-in-the-loop control.\n ///\n /// The sampling flow follows these steps:\n /// 1. Server sends a `sampling/createMessage` request to the client\n /// 2. Client reviews the request and can modify it\n /// 3. Client samples from an LLM\n /// 4. Client reviews the completion\n /// 5. Client returns the result to the server\n ///\n /// - Parameters:\n /// - messages: The conversation history to send to the LLM\n /// - modelPreferences: Model selection preferences\n /// - systemPrompt: Optional system prompt\n /// - includeContext: What MCP context to include\n /// - temperature: Controls randomness (0.0 to 1.0)\n /// - maxTokens: Maximum tokens to generate\n /// - stopSequences: Array of sequences that stop generation\n /// - metadata: Additional provider-specific parameters\n /// - Returns: The sampling result containing the model used, stop reason, role, and content\n /// - Throws: MCPError if the request fails\n /// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/sampling#how-sampling-works\n public func requestSampling(\n messages: [Sampling.Message],\n modelPreferences: Sampling.ModelPreferences? = nil,\n systemPrompt: String? = nil,\n includeContext: Sampling.ContextInclusion? = nil,\n temperature: Double? = nil,\n maxTokens: Int,\n stopSequences: [String]? = nil,\n metadata: [String: Value]? = nil\n ) async throws -> CreateSamplingMessage.Result {\n guard connection != nil else {\n throw MCPError.internalError(\"Server connection not initialized\")\n }\n\n // Note: This is a conceptual implementation. The actual implementation would require\n // bidirectional communication support in the transport layer, allowing servers to\n // send requests to clients and receive responses.\n\n _ = CreateSamplingMessage.request(\n .init(\n messages: messages,\n modelPreferences: modelPreferences,\n systemPrompt: systemPrompt,\n includeContext: includeContext,\n temperature: temperature,\n maxTokens: maxTokens,\n stopSequences: stopSequences,\n metadata: metadata\n )\n )\n\n // This would need to be implemented with proper request/response handling\n // similar to how the client sends requests to servers\n throw MCPError.internalError(\n \"Bidirectional sampling requests not yet implemented in transport layer\")\n }\n\n /// A JSON-RPC batch containing multiple requests and/or notifications\n struct Batch: Sendable {\n /// An item in a JSON-RPC batch\n enum Item: Sendable {\n case request(Request)\n case notification(Message)\n\n }\n\n var items: [Item]\n\n init(items: [Item]) {\n self.items = items\n }\n }\n\n /// Process a batch of requests and/or notifications\n private func handleBatch(_ batch: Batch) async throws {\n await logger?.trace(\"Processing batch request\", metadata: [\"size\": \"\\(batch.items.count)\"])\n\n if batch.items.isEmpty {\n // Empty batch is invalid according to JSON-RPC spec\n let error = MCPError.invalidRequest(\"Batch array must not be empty\")\n let response = AnyMethod.response(id: .random, error: error)\n try await send(response)\n return\n }\n\n // Process each item in the batch and collect responses\n var responses: [Response] = []\n\n for item in batch.items {\n do {\n switch item {\n case .request(let request):\n // For batched requests, collect responses instead of sending immediately\n if let response = try await handleRequest(request, sendResponse: false) {\n responses.append(response)\n }\n\n case .notification(let notification):\n // Handle notification (no response needed)\n try await handleMessage(notification)\n }\n } catch {\n // Only add errors to response for requests (notifications don't have responses)\n if case .request(let request) = item {\n let mcpError =\n error as? MCPError ?? MCPError.internalError(error.localizedDescription)\n responses.append(AnyMethod.response(id: request.id, error: mcpError))\n }\n }\n }\n\n // Send collected responses if any\n if !responses.isEmpty {\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]\n let responseData = try encoder.encode(responses)\n\n guard let connection = connection else {\n throw MCPError.internalError(\"Server connection not initialized\")\n }\n\n try await connection.send(responseData)\n }\n }\n\n // MARK: - Request and Message Handling\n\n /// Handle a request and either send the response immediately or return it\n ///\n /// - Parameters:\n /// - request: The request to handle\n /// - sendResponse: Whether to send the response immediately (true) or return it (false)\n /// - Returns: The response when sendResponse is false\n private func handleRequest(_ request: Request, sendResponse: Bool = true)\n async throws -> Response?\n {\n // Check if this is a pre-processed error request (empty method)\n if request.method.isEmpty && !sendResponse {\n // This is a placeholder for an invalid request that couldn't be parsed in batch mode\n return AnyMethod.response(\n id: request.id,\n error: MCPError.invalidRequest(\"Invalid batch item format\")\n )\n }\n\n await logger?.trace(\n \"Processing request\",\n metadata: [\n \"method\": \"\\(request.method)\",\n \"id\": \"\\(request.id)\",\n ])\n\n if configuration.strict {\n // The client SHOULD NOT send requests other than pings\n // before the server has responded to the initialize request.\n switch request.method {\n case Initialize.name, Ping.name:\n break\n default:\n try checkInitialized()\n }\n }\n\n // Find handler for method name\n guard let handler = methodHandlers[request.method] else {\n let error = MCPError.methodNotFound(\"Unknown method: \\(request.method)\")\n let response = AnyMethod.response(id: request.id, error: error)\n\n if sendResponse {\n try await send(response)\n return nil\n }\n\n return response\n }\n\n do {\n // Handle request and get response\n let response = try await handler(request)\n\n if sendResponse {\n try await send(response)\n return nil\n }\n\n return response\n } catch {\n let mcpError = error as? MCPError ?? MCPError.internalError(error.localizedDescription)\n let response = AnyMethod.response(id: request.id, error: mcpError)\n\n if sendResponse {\n try await send(response)\n return nil\n }\n\n return response\n }\n }\n\n private func handleMessage(_ message: Message) async throws {\n await logger?.trace(\n \"Processing notification\",\n metadata: [\"method\": \"\\(message.method)\"])\n\n if configuration.strict {\n // Check initialization state unless this is an initialized notification\n if message.method != InitializedNotification.name {\n try checkInitialized()\n }\n }\n\n // Find notification handlers for this method\n guard let handlers = notificationHandlers[message.method] else { return }\n\n // Convert notification parameters to concrete type and call handlers\n for handler in handlers {\n do {\n try await handler(message)\n } catch {\n await logger?.error(\n \"Error handling notification\",\n metadata: [\n \"method\": \"\\(message.method)\",\n \"error\": \"\\(error)\",\n ])\n }\n }\n }\n\n private func checkInitialized() throws {\n guard isInitialized else {\n throw MCPError.invalidRequest(\"Server is not initialized\")\n }\n }\n\n private func registerDefaultHandlers(\n initializeHook: (@Sendable (Client.Info, Client.Capabilities) async throws -> Void)?\n ) {\n // Initialize\n withMethodHandler(Initialize.self) { [weak self] params in\n guard let self = self else {\n throw MCPError.internalError(\"Server was deallocated\")\n }\n\n guard await !self.isInitialized else {\n throw MCPError.invalidRequest(\"Server is already initialized\")\n }\n\n // Call initialization hook if registered\n if let hook = initializeHook {\n try await hook(params.clientInfo, params.capabilities)\n }\n\n // Perform version negotiation\n let clientRequestedVersion = params.protocolVersion\n let negotiatedProtocolVersion = Version.negotiate(\n clientRequestedVersion: clientRequestedVersion)\n\n // Set initial state with the negotiated protocol version\n await self.setInitialState(\n clientInfo: params.clientInfo,\n clientCapabilities: params.capabilities,\n protocolVersion: negotiatedProtocolVersion\n )\n\n return Initialize.Result(\n protocolVersion: negotiatedProtocolVersion,\n capabilities: await self.capabilities,\n serverInfo: self.serverInfo,\n instructions: nil\n )\n }\n\n // Ping\n withMethodHandler(Ping.self) { _ in return Empty() }\n }\n\n private func setInitialState(\n clientInfo: Client.Info,\n clientCapabilities: Client.Capabilities,\n protocolVersion: String\n ) async {\n self.clientInfo = clientInfo\n self.clientCapabilities = clientCapabilities\n self.protocolVersion = protocolVersion\n self.isInitialized = true\n }\n}\n\nextension Server.Batch: Codable {\n init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n\n let encoder = JSONEncoder()\n let decoder = JSONDecoder()\n\n var items: [Item] = []\n for item in try container.decode([Value].self) {\n let data = try encoder.encode(item)\n try items.append(decoder.decode(Item.self, from: data))\n }\n\n self.items = items\n }\n\n func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n try container.encode(items)\n }\n}\n\nextension Server.Batch.Item: Codable {\n private enum CodingKeys: String, CodingKey {\n case id\n }\n\n init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n // Check if it's a request (has id) or notification (no id)\n if container.contains(.id) {\n self = .request(try Request(from: decoder))\n } else {\n self = .notification(try Message(from: decoder))\n }\n }\n\n func encode(to encoder: Encoder) throws {\n switch self {\n case .request(let request):\n try request.encode(to: encoder)\n case .notification(let notification):\n try notification.encode(to: encoder)\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Server/Tools.swift", "import Foundation\n\n/// The Model Context Protocol (MCP) allows servers to expose tools\n/// that can be invoked by language models.\n/// Tools enable models to interact with external systems, such as\n/// querying databases, calling APIs, or performing computations.\n/// Each tool is uniquely identified by a name and includes metadata\n/// describing its schema.\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/\npublic struct Tool: Hashable, Codable, Sendable {\n /// The tool name\n public let name: String\n /// The tool description\n public let description: String\n /// The tool input schema\n public let inputSchema: Value?\n\n /// Annotations that provide display-facing and operational information for a Tool.\n ///\n /// - Note: All properties in `ToolAnnotations` are **hints**.\n /// They are not guaranteed to provide a faithful description of\n /// tool behavior (including descriptive properties like `title`).\n ///\n /// Clients should never make tool use decisions based on `ToolAnnotations`\n /// received from untrusted servers.\n public struct Annotations: Hashable, Codable, Sendable, ExpressibleByNilLiteral {\n /// A human-readable title for the tool\n public var title: String?\n\n /// If true, the tool may perform destructive updates to its environment.\n /// If false, the tool performs only additive updates.\n /// (This property is meaningful only when `readOnlyHint == false`)\n ///\n /// When unspecified, the implicit default is `true`.\n public var destructiveHint: Bool?\n\n /// If true, calling the tool repeatedly with the same arguments\n /// will have no additional effect on its environment.\n /// (This property is meaningful only when `readOnlyHint == false`)\n ///\n /// When unspecified, the implicit default is `false`.\n public var idempotentHint: Bool?\n\n /// If true, this tool may interact with an \"open world\" of external\n /// entities. If false, the tool's domain of interaction is closed.\n /// For example, the world of a web search tool is open, whereas that\n /// of a memory tool is not.\n ///\n /// When unspecified, the implicit default is `true`.\n public var openWorldHint: Bool?\n\n /// If true, the tool does not modify its environment.\n ///\n /// When unspecified, the implicit default is `false`.\n public var readOnlyHint: Bool?\n\n /// Returns true if all properties are nil\n public var isEmpty: Bool {\n title == nil && readOnlyHint == nil && destructiveHint == nil && idempotentHint == nil\n && openWorldHint == nil\n }\n\n public init(\n title: String? = nil,\n readOnlyHint: Bool? = nil,\n destructiveHint: Bool? = nil,\n idempotentHint: Bool? = nil,\n openWorldHint: Bool? = nil\n ) {\n self.title = title\n self.readOnlyHint = readOnlyHint\n self.destructiveHint = destructiveHint\n self.idempotentHint = idempotentHint\n self.openWorldHint = openWorldHint\n }\n\n /// Initialize an empty annotations object\n public init(nilLiteral: ()) {}\n }\n\n /// Annotations that provide display-facing and operational information\n public var annotations: Annotations\n\n /// Initialize a tool with a name, description, input schema, and annotations\n public init(\n name: String,\n description: String,\n inputSchema: Value? = nil,\n annotations: Annotations = nil\n ) {\n self.name = name\n self.description = description\n self.inputSchema = inputSchema\n self.annotations = annotations\n }\n\n /// Content types that can be returned by a tool\n public enum Content: Hashable, Codable, Sendable {\n /// Text content\n case text(String)\n /// Image content\n case image(data: String, mimeType: String, metadata: [String: String]?)\n /// Audio content\n case audio(data: String, mimeType: String)\n /// Embedded resource content\n case resource(uri: String, mimeType: String, text: String?)\n\n private enum CodingKeys: String, CodingKey {\n case type\n case text\n case image\n case resource\n case audio\n case uri\n case mimeType\n case data\n case metadata\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let type = try container.decode(String.self, forKey: .type)\n\n switch type {\n case \"text\":\n let text = try container.decode(String.self, forKey: .text)\n self = .text(text)\n case \"image\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n let metadata = try container.decodeIfPresent(\n [String: String].self, forKey: .metadata)\n self = .image(data: data, mimeType: mimeType, metadata: metadata)\n case \"audio\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n self = .audio(data: data, mimeType: mimeType)\n case \"resource\":\n let uri = try container.decode(String.self, forKey: .uri)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n let text = try container.decodeIfPresent(String.self, forKey: .text)\n self = .resource(uri: uri, mimeType: mimeType, text: text)\n default:\n throw DecodingError.dataCorruptedError(\n forKey: .type, in: container, debugDescription: \"Unknown tool content type\")\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n\n switch self {\n case .text(let text):\n try container.encode(\"text\", forKey: .type)\n try container.encode(text, forKey: .text)\n case .image(let data, let mimeType, let metadata):\n try container.encode(\"image\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n try container.encodeIfPresent(metadata, forKey: .metadata)\n case .audio(let data, let mimeType):\n try container.encode(\"audio\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n case .resource(let uri, let mimeType, let text):\n try container.encode(\"resource\", forKey: .type)\n try container.encode(uri, forKey: .uri)\n try container.encode(mimeType, forKey: .mimeType)\n try container.encodeIfPresent(text, forKey: .text)\n }\n }\n }\n\n private enum CodingKeys: String, CodingKey {\n case name\n case description\n case inputSchema\n case annotations\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n name = try container.decode(String.self, forKey: .name)\n description = try container.decode(String.self, forKey: .description)\n inputSchema = try container.decodeIfPresent(Value.self, forKey: .inputSchema)\n annotations =\n try container.decodeIfPresent(Tool.Annotations.self, forKey: .annotations) ?? .init()\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(name, forKey: .name)\n try container.encode(description, forKey: .description)\n if let schema = inputSchema {\n try container.encode(schema, forKey: .inputSchema)\n }\n if !annotations.isEmpty {\n try container.encode(annotations, forKey: .annotations)\n }\n }\n}\n\n// MARK: -\n\n/// To discover available tools, clients send a `tools/list` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/#listing-tools\npublic enum ListTools: Method {\n public static let name = \"tools/list\"\n\n public struct Parameters: NotRequired, Hashable, Codable, Sendable {\n public let cursor: String?\n\n public init() {\n self.cursor = nil\n }\n\n public init(cursor: String) {\n self.cursor = cursor\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let tools: [Tool]\n public let nextCursor: String?\n\n public init(tools: [Tool], nextCursor: String? = nil) {\n self.tools = tools\n self.nextCursor = nextCursor\n }\n }\n}\n\n/// To call a tool, clients send a `tools/call` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/#calling-tools\npublic enum CallTool: Method {\n public static let name = \"tools/call\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let name: String\n public let arguments: [String: Value]?\n\n public init(name: String, arguments: [String: Value]? = nil) {\n self.name = name\n self.arguments = arguments\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let content: [Tool.Content]\n public let isError: Bool?\n\n public init(content: [Tool.Content], isError: Bool? = nil) {\n self.content = content\n self.isError = isError\n }\n }\n}\n\n/// When the list of available tools changes, servers that declared the listChanged capability SHOULD send a notification:\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/#list-changed-notification\npublic struct ToolListChangedNotification: Notification {\n public static let name: String = \"notifications/tools/list_changed\"\n}\n"], ["/swift-sdk/Sources/MCP/Server/Prompts.swift", "import Foundation\n\n/// The Model Context Protocol (MCP) provides a standardized way\n/// for servers to expose prompt templates to clients.\n/// Prompts allow servers to provide structured messages and instructions\n/// for interacting with language models.\n/// Clients can discover available prompts, retrieve their contents,\n/// and provide arguments to customize them.\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/\npublic struct Prompt: Hashable, Codable, Sendable {\n /// The prompt name\n public let name: String\n /// The prompt description\n public let description: String?\n /// The prompt arguments\n public let arguments: [Argument]?\n\n public init(name: String, description: String? = nil, arguments: [Argument]? = nil) {\n self.name = name\n self.description = description\n self.arguments = arguments\n }\n\n /// An argument for a prompt\n public struct Argument: Hashable, Codable, Sendable {\n /// The argument name\n public let name: String\n /// The argument description\n public let description: String?\n /// Whether the argument is required\n public let required: Bool?\n\n public init(name: String, description: String? = nil, required: Bool? = nil) {\n self.name = name\n self.description = description\n self.required = required\n }\n }\n\n /// A message in a prompt\n public struct Message: Hashable, Codable, Sendable {\n /// The message role\n public enum Role: String, Hashable, Codable, Sendable {\n /// A user message\n case user\n /// An assistant message\n case assistant\n }\n\n /// The message role\n public let role: Role\n /// The message content\n public let content: Content\n\n /// Creates a message with the specified role and content\n @available(\n *, deprecated, message: \"Use static factory methods .user(_:) or .assistant(_:) instead\"\n )\n public init(role: Role, content: Content) {\n self.role = role\n self.content = content\n }\n\n /// Private initializer for convenience methods to avoid deprecation warnings\n private init(_role role: Role, _content content: Content) {\n self.role = role\n self.content = content\n }\n\n /// Creates a user message with the specified content\n public static func user(_ content: Content) -> Message {\n return Message(_role: .user, _content: content)\n }\n\n /// Creates an assistant message with the specified content\n public static func assistant(_ content: Content) -> Message {\n return Message(_role: .assistant, _content: content)\n }\n\n /// Content types for messages\n public enum Content: Hashable, Sendable {\n /// Text content\n case text(text: String)\n /// Image content\n case image(data: String, mimeType: String)\n /// Audio content\n case audio(data: String, mimeType: String)\n /// Embedded resource content\n case resource(uri: String, mimeType: String, text: String?, blob: String?)\n }\n }\n\n /// Reference type for prompts\n public struct Reference: Hashable, Codable, Sendable {\n /// The prompt reference name\n public let name: String\n\n public init(name: String) {\n self.name = name\n }\n\n private enum CodingKeys: String, CodingKey {\n case type, name\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(\"ref/prompt\", forKey: .type)\n try container.encode(name, forKey: .name)\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n _ = try container.decode(String.self, forKey: .type)\n name = try container.decode(String.self, forKey: .name)\n }\n }\n}\n\n// MARK: - Codable\n\nextension Prompt.Message.Content: Codable {\n private enum CodingKeys: String, CodingKey {\n case type, text, data, mimeType, uri, blob\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n\n switch self {\n case .text(let text):\n try container.encode(\"text\", forKey: .type)\n try container.encode(text, forKey: .text)\n case .image(let data, let mimeType):\n try container.encode(\"image\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n case .audio(let data, let mimeType):\n try container.encode(\"audio\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n case .resource(let uri, let mimeType, let text, let blob):\n try container.encode(\"resource\", forKey: .type)\n try container.encode(uri, forKey: .uri)\n try container.encode(mimeType, forKey: .mimeType)\n try container.encodeIfPresent(text, forKey: .text)\n try container.encodeIfPresent(blob, forKey: .blob)\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let type = try container.decode(String.self, forKey: .type)\n\n switch type {\n case \"text\":\n let text = try container.decode(String.self, forKey: .text)\n self = .text(text: text)\n case \"image\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n self = .image(data: data, mimeType: mimeType)\n case \"audio\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n self = .audio(data: data, mimeType: mimeType)\n case \"resource\":\n let uri = try container.decode(String.self, forKey: .uri)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n let text = try container.decodeIfPresent(String.self, forKey: .text)\n let blob = try container.decodeIfPresent(String.self, forKey: .blob)\n self = .resource(uri: uri, mimeType: mimeType, text: text, blob: blob)\n default:\n throw DecodingError.dataCorruptedError(\n forKey: .type,\n in: container,\n debugDescription: \"Unknown content type\")\n }\n }\n}\n\n// MARK: - ExpressibleByStringLiteral\n\nextension Prompt.Message.Content: ExpressibleByStringLiteral {\n public init(stringLiteral value: String) {\n self = .text(text: value)\n }\n}\n\n// MARK: - ExpressibleByStringInterpolation\n\nextension Prompt.Message.Content: ExpressibleByStringInterpolation {\n public init(stringInterpolation: DefaultStringInterpolation) {\n self = .text(text: String(stringInterpolation: stringInterpolation))\n }\n}\n\n// MARK: -\n\n/// To retrieve available prompts, clients send a `prompts/list` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/#listing-prompts\npublic enum ListPrompts: Method {\n public static let name: String = \"prompts/list\"\n\n public struct Parameters: NotRequired, Hashable, Codable, Sendable {\n public let cursor: String?\n\n public init() {\n self.cursor = nil\n }\n\n public init(cursor: String) {\n self.cursor = cursor\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let prompts: [Prompt]\n public let nextCursor: String?\n\n public init(prompts: [Prompt], nextCursor: String? = nil) {\n self.prompts = prompts\n self.nextCursor = nextCursor\n }\n }\n}\n\n/// To retrieve a specific prompt, clients send a `prompts/get` request.\n/// Arguments may be auto-completed through the completion API.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/#getting-a-prompt\npublic enum GetPrompt: Method {\n public static let name: String = \"prompts/get\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let name: String\n public let arguments: [String: Value]?\n\n public init(name: String, arguments: [String: Value]? = nil) {\n self.name = name\n self.arguments = arguments\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let description: String?\n public let messages: [Prompt.Message]\n\n public init(description: String?, messages: [Prompt.Message]) {\n self.description = description\n self.messages = messages\n }\n }\n}\n\n/// When the list of available prompts changes, servers that declared the listChanged capability SHOULD send a notification.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/#list-changed-notification\npublic struct PromptListChangedNotification: Notification {\n public static let name: String = \"notifications/prompts/list_changed\"\n}\n"], ["/swift-sdk/Sources/MCP/Server/Resources.swift", "import Foundation\n\n/// The Model Context Protocol (MCP) provides a standardized way\n/// for servers to expose resources to clients.\n/// Resources allow servers to share data that provides context to language models,\n/// such as files, database schemas, or application-specific information.\n/// Each resource is uniquely identified by a URI.\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/\npublic struct Resource: Hashable, Codable, Sendable {\n /// The resource name\n public var name: String\n /// The resource URI\n public var uri: String\n /// The resource description\n public var description: String?\n /// The resource MIME type\n public var mimeType: String?\n /// The resource metadata\n public var metadata: [String: String]?\n\n public init(\n name: String,\n uri: String,\n description: String? = nil,\n mimeType: String? = nil,\n metadata: [String: String]? = nil\n ) {\n self.name = name\n self.uri = uri\n self.description = description\n self.mimeType = mimeType\n self.metadata = metadata\n }\n\n /// Content of a resource.\n public struct Content: Hashable, Codable, Sendable {\n /// The resource URI\n public let uri: String\n /// The resource MIME type\n public let mimeType: String?\n /// The resource text content\n public let text: String?\n /// The resource binary content\n public let blob: String?\n\n public static func text(_ content: String, uri: String, mimeType: String? = nil) -> Self {\n .init(uri: uri, mimeType: mimeType, text: content)\n }\n\n public static func binary(_ data: Data, uri: String, mimeType: String? = nil) -> Self {\n .init(uri: uri, mimeType: mimeType, blob: data.base64EncodedString())\n }\n\n private init(uri: String, mimeType: String? = nil, text: String? = nil) {\n self.uri = uri\n self.mimeType = mimeType\n self.text = text\n self.blob = nil\n }\n\n private init(uri: String, mimeType: String? = nil, blob: String) {\n self.uri = uri\n self.mimeType = mimeType\n self.text = nil\n self.blob = blob\n }\n }\n\n /// A resource template.\n public struct Template: Hashable, Codable, Sendable {\n /// The URI template pattern\n public var uriTemplate: String\n /// The template name\n public var name: String\n /// The template description\n public var description: String?\n /// The resource MIME type\n public var mimeType: String?\n\n public init(\n uriTemplate: String,\n name: String,\n description: String? = nil,\n mimeType: String? = nil\n ) {\n self.uriTemplate = uriTemplate\n self.name = name\n self.description = description\n self.mimeType = mimeType\n }\n }\n}\n\n// MARK: -\n\n/// To discover available resources, clients send a `resources/list` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#listing-resources\npublic enum ListResources: Method {\n public static let name: String = \"resources/list\"\n\n public struct Parameters: NotRequired, Hashable, Codable, Sendable {\n public let cursor: String?\n\n public init() {\n self.cursor = nil\n }\n \n public init(cursor: String) {\n self.cursor = cursor\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let resources: [Resource]\n public let nextCursor: String?\n\n public init(resources: [Resource], nextCursor: String? = nil) {\n self.resources = resources\n self.nextCursor = nextCursor\n }\n }\n}\n\n/// To retrieve resource contents, clients send a `resources/read` request:\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#reading-resources\npublic enum ReadResource: Method {\n public static let name: String = \"resources/read\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let uri: String\n\n public init(uri: String) {\n self.uri = uri\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let contents: [Resource.Content]\n\n public init(contents: [Resource.Content]) {\n self.contents = contents\n }\n }\n}\n\n/// To discover available resource templates, clients send a `resources/templates/list` request.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#resource-templates\npublic enum ListResourceTemplates: Method {\n public static let name: String = \"resources/templates/list\"\n\n public struct Parameters: NotRequired, Hashable, Codable, Sendable {\n public let cursor: String?\n\n public init() {\n self.cursor = nil\n }\n \n public init(cursor: String) {\n self.cursor = cursor\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let templates: [Resource.Template]\n public let nextCursor: String?\n\n public init(templates: [Resource.Template], nextCursor: String? = nil) {\n self.templates = templates\n self.nextCursor = nextCursor\n }\n\n private enum CodingKeys: String, CodingKey {\n case templates = \"resourceTemplates\"\n case nextCursor\n }\n }\n}\n\n/// When the list of available resources changes, servers that declared the listChanged capability SHOULD send a notification.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#list-changed-notification\npublic struct ResourceListChangedNotification: Notification {\n public static let name: String = \"notifications/resources/list_changed\"\n\n public typealias Parameters = Empty\n}\n\n/// Clients can subscribe to specific resources and receive notifications when they change.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#subscriptions\npublic enum ResourceSubscribe: Method {\n public static let name: String = \"resources/subscribe\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let uri: String\n }\n\n public typealias Result = Empty\n}\n\n/// When a resource changes, servers that declared the updated capability SHOULD send a notification to subscribed clients.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#subscriptions\npublic struct ResourceUpdatedNotification: Notification {\n public static let name: String = \"notifications/resources/updated\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let uri: String\n\n public init(uri: String) {\n self.uri = uri\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Messages.swift", "import class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\nprivate let jsonrpc = \"2.0\"\n\npublic protocol NotRequired {\n init()\n}\n\npublic struct Empty: NotRequired, Hashable, Codable, Sendable {\n public init() {}\n}\n\nextension Value: NotRequired {\n public init() {\n self = .null\n }\n}\n\n// MARK: -\n\n/// A method that can be used to send requests and receive responses.\npublic protocol Method {\n /// The parameters of the method.\n associatedtype Parameters: Codable, Hashable, Sendable = Empty\n /// The result of the method.\n associatedtype Result: Codable, Hashable, Sendable = Empty\n /// The name of the method.\n static var name: String { get }\n}\n\n/// Type-erased method for request/response handling\nstruct AnyMethod: Method, Sendable {\n static var name: String { \"\" }\n typealias Parameters = Value\n typealias Result = Value\n}\n\nextension Method where Parameters == Empty {\n public static func request(id: ID = .random) -> Request {\n Request(id: id, method: name, params: Empty())\n }\n}\n\nextension Method where Result == Empty {\n public static func response(id: ID) -> Response {\n Response(id: id, result: Empty())\n }\n}\n\nextension Method {\n /// Create a request with the given parameters.\n public static func request(id: ID = .random, _ parameters: Self.Parameters) -> Request {\n Request(id: id, method: name, params: parameters)\n }\n\n /// Create a response with the given result.\n public static func response(id: ID, result: Self.Result) -> Response {\n Response(id: id, result: result)\n }\n\n /// Create a response with the given error.\n public static func response(id: ID, error: MCPError) -> Response {\n Response(id: id, error: error)\n }\n}\n\n// MARK: -\n\n/// A request message.\npublic struct Request: Hashable, Identifiable, Codable, Sendable {\n /// The request ID.\n public let id: ID\n /// The method name.\n public let method: String\n /// The request parameters.\n public let params: M.Parameters\n\n init(id: ID = .random, method: String, params: M.Parameters) {\n self.id = id\n self.method = method\n self.params = params\n }\n\n private enum CodingKeys: String, CodingKey {\n case jsonrpc, id, method, params\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(jsonrpc, forKey: .jsonrpc)\n try container.encode(id, forKey: .id)\n try container.encode(method, forKey: .method)\n try container.encode(params, forKey: .params)\n }\n}\n\nextension Request {\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let version = try container.decode(String.self, forKey: .jsonrpc)\n guard version == jsonrpc else {\n throw DecodingError.dataCorruptedError(\n forKey: .jsonrpc, in: container, debugDescription: \"Invalid JSON-RPC version\")\n }\n id = try container.decode(ID.self, forKey: .id)\n method = try container.decode(String.self, forKey: .method)\n\n if M.Parameters.self is NotRequired.Type {\n // For NotRequired parameters, use decodeIfPresent or init()\n params =\n (try container.decodeIfPresent(M.Parameters.self, forKey: .params)\n ?? (M.Parameters.self as! NotRequired.Type).init() as! M.Parameters)\n } else if let value = try? container.decode(M.Parameters.self, forKey: .params) {\n // If params exists and can be decoded, use it\n params = value\n } else if !container.contains(.params)\n || (try? container.decodeNil(forKey: .params)) == true\n {\n // If params is missing or explicitly null, use Empty for Empty parameters\n // or throw for non-Empty parameters\n if M.Parameters.self == Empty.self {\n params = Empty() as! M.Parameters\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Missing required params field\"))\n }\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Invalid params field\"))\n }\n }\n}\n\n/// A type-erased request for request/response handling\ntypealias AnyRequest = Request\n\nextension AnyRequest {\n init(_ request: Request) throws {\n let encoder = JSONEncoder()\n let decoder = JSONDecoder()\n\n let data = try encoder.encode(request)\n self = try decoder.decode(AnyRequest.self, from: data)\n }\n}\n\n/// A box for request handlers that can be type-erased\nclass RequestHandlerBox: @unchecked Sendable {\n func callAsFunction(_ request: AnyRequest) async throws -> AnyResponse {\n fatalError(\"Must override\")\n }\n}\n\n/// A typed request handler that can be used to handle requests of a specific type\nfinal class TypedRequestHandler: RequestHandlerBox, @unchecked Sendable {\n private let _handle: @Sendable (Request) async throws -> Response\n\n init(_ handler: @escaping @Sendable (Request) async throws -> Response) {\n self._handle = handler\n super.init()\n }\n\n override func callAsFunction(_ request: AnyRequest) async throws -> AnyResponse {\n let encoder = JSONEncoder()\n let decoder = JSONDecoder()\n\n // Create a concrete request from the type-erased one\n let data = try encoder.encode(request)\n let request = try decoder.decode(Request.self, from: data)\n\n // Handle with concrete type\n let response = try await _handle(request)\n\n // Convert result to AnyMethod response\n switch response.result {\n case .success(let result):\n let resultData = try encoder.encode(result)\n let resultValue = try decoder.decode(Value.self, from: resultData)\n return Response(id: response.id, result: resultValue)\n case .failure(let error):\n return Response(id: response.id, error: error)\n }\n }\n}\n\n// MARK: -\n\n/// A response message.\npublic struct Response: Hashable, Identifiable, Codable, Sendable {\n /// The response ID.\n public let id: ID\n /// The response result.\n public let result: Swift.Result\n\n public init(id: ID, result: M.Result) {\n self.id = id\n self.result = .success(result)\n }\n\n public init(id: ID, error: MCPError) {\n self.id = id\n self.result = .failure(error)\n }\n\n private enum CodingKeys: String, CodingKey {\n case jsonrpc, id, result, error\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(jsonrpc, forKey: .jsonrpc)\n try container.encode(id, forKey: .id)\n switch result {\n case .success(let result):\n try container.encode(result, forKey: .result)\n case .failure(let error):\n try container.encode(error, forKey: .error)\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let version = try container.decode(String.self, forKey: .jsonrpc)\n guard version == jsonrpc else {\n throw DecodingError.dataCorruptedError(\n forKey: .jsonrpc, in: container, debugDescription: \"Invalid JSON-RPC version\")\n }\n id = try container.decode(ID.self, forKey: .id)\n if let result = try? container.decode(M.Result.self, forKey: .result) {\n self.result = .success(result)\n } else if let error = try? container.decode(MCPError.self, forKey: .error) {\n self.result = .failure(error)\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Invalid response\"))\n }\n }\n}\n\n/// A type-erased response for request/response handling\ntypealias AnyResponse = Response\n\nextension AnyResponse {\n init(_ response: Response) throws {\n // Instead of re-encoding/decoding which might double-wrap the error,\n // directly transfer the properties\n self.id = response.id\n switch response.result {\n case .success(let result):\n // For success, we still need to convert the result to a Value\n let data = try JSONEncoder().encode(result)\n let resultValue = try JSONDecoder().decode(Value.self, from: data)\n self.result = .success(resultValue)\n case .failure(let error):\n // Keep the original error without re-encoding/decoding\n self.result = .failure(error)\n }\n }\n}\n\n// MARK: -\n\n/// A notification message.\npublic protocol Notification: Hashable, Codable, Sendable {\n /// The parameters of the notification.\n associatedtype Parameters: Hashable, Codable, Sendable = Empty\n /// The name of the notification.\n static var name: String { get }\n}\n\n/// A type-erased notification for message handling\nstruct AnyNotification: Notification, Sendable {\n static var name: String { \"\" }\n typealias Parameters = Value\n}\n\nextension AnyNotification {\n init(_ notification: some Notification) throws {\n let encoder = JSONEncoder()\n let decoder = JSONDecoder()\n\n let data = try encoder.encode(notification)\n self = try decoder.decode(AnyNotification.self, from: data)\n }\n}\n\n/// A message that can be used to send notifications.\npublic struct Message: Hashable, Codable, Sendable {\n /// The method name.\n public let method: String\n /// The notification parameters.\n public let params: N.Parameters\n\n public init(method: String, params: N.Parameters) {\n self.method = method\n self.params = params\n }\n\n private enum CodingKeys: String, CodingKey {\n case jsonrpc, method, params\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(jsonrpc, forKey: .jsonrpc)\n try container.encode(method, forKey: .method)\n if N.Parameters.self != Empty.self {\n try container.encode(params, forKey: .params)\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let version = try container.decode(String.self, forKey: .jsonrpc)\n guard version == jsonrpc else {\n throw DecodingError.dataCorruptedError(\n forKey: .jsonrpc, in: container, debugDescription: \"Invalid JSON-RPC version\")\n }\n method = try container.decode(String.self, forKey: .method)\n\n if N.Parameters.self is NotRequired.Type {\n // For NotRequired parameters, use decodeIfPresent or init()\n params =\n (try container.decodeIfPresent(N.Parameters.self, forKey: .params)\n ?? (N.Parameters.self as! NotRequired.Type).init() as! N.Parameters)\n } else if let value = try? container.decode(N.Parameters.self, forKey: .params) {\n // If params exists and can be decoded, use it\n params = value\n } else if !container.contains(.params)\n || (try? container.decodeNil(forKey: .params)) == true\n {\n // If params is missing or explicitly null, use Empty for Empty parameters\n // or throw for non-Empty parameters\n if N.Parameters.self == Empty.self {\n params = Empty() as! N.Parameters\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Missing required params field\"))\n }\n } else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: \"Invalid params field\"))\n }\n }\n}\n\n/// A type-erased message for message handling\ntypealias AnyMessage = Message\n\nextension Notification where Parameters == Empty {\n /// Create a message with empty parameters.\n public static func message() -> Message {\n Message(method: name, params: Empty())\n }\n}\n\nextension Notification {\n /// Create a message with the given parameters.\n public static func message(_ parameters: Parameters) -> Message {\n Message(method: name, params: parameters)\n }\n}\n\n/// A box for notification handlers that can be type-erased\nclass NotificationHandlerBox: @unchecked Sendable {\n func callAsFunction(_ notification: Message) async throws {}\n}\n\n/// A typed notification handler that can be used to handle notifications of a specific type\nfinal class TypedNotificationHandler: NotificationHandlerBox,\n @unchecked Sendable\n{\n private let _handle: @Sendable (Message) async throws -> Void\n\n init(_ handler: @escaping @Sendable (Message) async throws -> Void) {\n self._handle = handler\n super.init()\n }\n\n override func callAsFunction(_ notification: Message) async throws {\n // Create a concrete notification from the type-erased one\n let data = try JSONEncoder().encode(notification)\n let typedNotification = try JSONDecoder().decode(Message.self, from: data)\n\n try await _handle(typedNotification)\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/UnitInterval.swift", "/// A value constrained to the range 0.0 to 1.0, inclusive.\n///\n/// `UnitInterval` represents a normalized value that is guaranteed to be within\n/// the unit interval [0, 1]. This type is commonly used for representing\n/// priorities in sampling request model preferences.\n///\n/// The type provides safe initialization that returns `nil` for values outside\n/// the valid range, ensuring that all instances contain valid unit interval values.\n///\n/// - Example:\n/// ```swift\n/// let zero: UnitInterval = 0 // 0.0\n/// let half = UnitInterval(0.5)! // 0.5\n/// let one: UnitInterval = 1.0 // 1.0\n/// let invalid = UnitInterval(1.5) // nil\n/// ```\npublic struct UnitInterval: Hashable, Sendable {\n private let value: Double\n\n /// Creates a unit interval value from a `Double`.\n ///\n /// - Parameter value: A double value that must be in the range 0.0...1.0\n /// - Returns: A `UnitInterval` instance if the value is valid, `nil` otherwise\n ///\n /// - Example:\n /// ```swift\n /// let valid = UnitInterval(0.75) // Optional(0.75)\n /// let invalid = UnitInterval(-0.1) // nil\n /// let boundary = UnitInterval(1.0) // Optional(1.0)\n /// ```\n public init?(_ value: Double) {\n guard (0...1).contains(value) else { return nil }\n self.value = value\n }\n\n /// The underlying double value.\n ///\n /// This property provides access to the raw double value that is guaranteed\n /// to be within the range [0, 1].\n ///\n /// - Returns: The double value between 0.0 and 1.0, inclusive\n public var doubleValue: Double { value }\n}\n\n// MARK: - Comparable\n\nextension UnitInterval: Comparable {\n public static func < (lhs: UnitInterval, rhs: UnitInterval) -> Bool {\n lhs.value < rhs.value\n }\n}\n\n// MARK: - CustomStringConvertible\n\nextension UnitInterval: CustomStringConvertible {\n public var description: String { \"\\(value)\" }\n}\n\n// MARK: - Codable\n\nextension UnitInterval: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let doubleValue = try container.decode(Double.self)\n guard let interval = UnitInterval(doubleValue) else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: decoder.codingPath,\n debugDescription: \"Value \\(doubleValue) is not in range 0...1\")\n )\n }\n self = interval\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n try container.encode(value)\n }\n}\n\n// MARK: - ExpressibleByFloatLiteral\n\nextension UnitInterval: ExpressibleByFloatLiteral {\n /// Creates a unit interval from a floating-point literal.\n ///\n /// This initializer allows you to create `UnitInterval` instances using\n /// floating-point literals. The literal value must be in the range [0, 1]\n /// or a runtime error will occur.\n ///\n /// - Parameter value: A floating-point literal between 0.0 and 1.0\n ///\n /// - Warning: This initializer will crash if the literal is outside the valid range.\n /// Use the failable initializer `init(_:)` for runtime validation.\n ///\n /// - Example:\n /// ```swift\n /// let quarter: UnitInterval = 0.25\n /// let half: UnitInterval = 0.5\n /// ```\n public init(floatLiteral value: Double) {\n self.init(value)!\n }\n}\n\n// MARK: - ExpressibleByIntegerLiteral\n\nextension UnitInterval: ExpressibleByIntegerLiteral {\n /// Creates a unit interval from an integer literal.\n ///\n /// This initializer allows you to create `UnitInterval` instances using\n /// integer literals. Only the values 0 and 1 are valid.\n ///\n /// - Parameter value: An integer literal, either 0 or 1\n ///\n /// - Warning: This initializer will crash if the literal is outside the valid range.\n /// Use the failable initializer `init(_:)` for runtime validation.\n ///\n /// - Example:\n /// ```swift\n /// let zero: UnitInterval = 0\n /// let one: UnitInterval = 1\n /// ```\n public init(integerLiteral value: Int) {\n self.init(Double(value))!\n }\n}\n"], ["/swift-sdk/Sources/MCP/Client/Sampling.swift", "import Foundation\n\n/// The Model Context Protocol (MCP) allows servers to request LLM completions\n/// through the client, enabling sophisticated agentic behaviors while maintaining\n/// security and privacy.\n///\n/// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/sampling#how-sampling-works\npublic enum Sampling {\n /// A message in the conversation history.\n public struct Message: Hashable, Codable, Sendable {\n /// The message role\n public enum Role: String, Hashable, Codable, Sendable {\n /// A user message\n case user\n /// An assistant message\n case assistant\n }\n\n /// The message role\n public let role: Role\n /// The message content\n public let content: Content\n\n /// Creates a message with the specified role and content\n @available(\n *, deprecated, message: \"Use static factory methods .user(_:) or .assistant(_:) instead\"\n )\n public init(role: Role, content: Content) {\n self.role = role\n self.content = content\n }\n\n /// Private initializer for convenience methods to avoid deprecation warnings\n private init(_role role: Role, _content content: Content) {\n self.role = role\n self.content = content\n }\n\n /// Creates a user message with the specified content\n public static func user(_ content: Content) -> Message {\n return Message(_role: .user, _content: content)\n }\n\n /// Creates an assistant message with the specified content\n public static func assistant(_ content: Content) -> Message {\n return Message(_role: .assistant, _content: content)\n }\n\n /// Content types for sampling messages\n public enum Content: Hashable, Sendable {\n /// Text content\n case text(String)\n /// Image content\n case image(data: String, mimeType: String)\n }\n }\n\n /// Model preferences for sampling requests\n public struct ModelPreferences: Hashable, Codable, Sendable {\n /// Model hints for selection\n public struct Hint: Hashable, Codable, Sendable {\n /// Suggested model name/family\n public let name: String?\n\n public init(name: String? = nil) {\n self.name = name\n }\n }\n\n /// Array of model name suggestions that clients can use to select an appropriate model\n public let hints: [Hint]?\n /// Importance of minimizing costs (0-1 normalized)\n public let costPriority: UnitInterval?\n /// Importance of low latency response (0-1 normalized)\n public let speedPriority: UnitInterval?\n /// Importance of advanced model capabilities (0-1 normalized)\n public let intelligencePriority: UnitInterval?\n\n public init(\n hints: [Hint]? = nil,\n costPriority: UnitInterval? = nil,\n speedPriority: UnitInterval? = nil,\n intelligencePriority: UnitInterval? = nil\n ) {\n self.hints = hints\n self.costPriority = costPriority\n self.speedPriority = speedPriority\n self.intelligencePriority = intelligencePriority\n }\n }\n\n /// Context inclusion options for sampling requests\n public enum ContextInclusion: String, Hashable, Codable, Sendable {\n /// No additional context\n case none\n /// Include context from the requesting server\n case thisServer\n /// Include context from all connected MCP servers\n case allServers\n }\n\n /// Stop reason for sampling completion\n public enum StopReason: String, Hashable, Codable, Sendable {\n /// Natural end of turn\n case endTurn\n /// Hit a stop sequence\n case stopSequence\n /// Reached maximum tokens\n case maxTokens\n }\n}\n\n// MARK: - Codable\n\nextension Sampling.Message.Content: Codable {\n private enum CodingKeys: String, CodingKey {\n case type, text, data, mimeType\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let type = try container.decode(String.self, forKey: .type)\n\n switch type {\n case \"text\":\n let text = try container.decode(String.self, forKey: .text)\n self = .text(text)\n case \"image\":\n let data = try container.decode(String.self, forKey: .data)\n let mimeType = try container.decode(String.self, forKey: .mimeType)\n self = .image(data: data, mimeType: mimeType)\n default:\n throw DecodingError.dataCorruptedError(\n forKey: .type, in: container,\n debugDescription: \"Unknown sampling message content type\")\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n\n switch self {\n case .text(let text):\n try container.encode(\"text\", forKey: .type)\n try container.encode(text, forKey: .text)\n case .image(let data, let mimeType):\n try container.encode(\"image\", forKey: .type)\n try container.encode(data, forKey: .data)\n try container.encode(mimeType, forKey: .mimeType)\n }\n }\n}\n\n// MARK: - ExpressibleByStringLiteral\n\nextension Sampling.Message.Content: ExpressibleByStringLiteral {\n public init(stringLiteral value: String) {\n self = .text(value)\n }\n}\n\n// MARK: - ExpressibleByStringInterpolation\n\nextension Sampling.Message.Content: ExpressibleByStringInterpolation {\n public init(stringInterpolation: DefaultStringInterpolation) {\n self = .text(String(stringInterpolation: stringInterpolation))\n }\n}\n\n// MARK: -\n\n/// To request sampling from a client, servers send a `sampling/createMessage` request.\n/// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/sampling#how-sampling-works\npublic enum CreateSamplingMessage: Method {\n public static let name = \"sampling/createMessage\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n /// The conversation history to send to the LLM\n public let messages: [Sampling.Message]\n /// Model selection preferences\n public let modelPreferences: Sampling.ModelPreferences?\n /// Optional system prompt\n public let systemPrompt: String?\n /// What MCP context to include\n public let includeContext: Sampling.ContextInclusion?\n /// Controls randomness (0.0 to 1.0)\n public let temperature: Double?\n /// Maximum tokens to generate\n public let maxTokens: Int\n /// Array of sequences that stop generation\n public let stopSequences: [String]?\n /// Additional provider-specific parameters\n public let metadata: [String: Value]?\n\n public init(\n messages: [Sampling.Message],\n modelPreferences: Sampling.ModelPreferences? = nil,\n systemPrompt: String? = nil,\n includeContext: Sampling.ContextInclusion? = nil,\n temperature: Double? = nil,\n maxTokens: Int,\n stopSequences: [String]? = nil,\n metadata: [String: Value]? = nil\n ) {\n self.messages = messages\n self.modelPreferences = modelPreferences\n self.systemPrompt = systemPrompt\n self.includeContext = includeContext\n self.temperature = temperature\n self.maxTokens = maxTokens\n self.stopSequences = stopSequences\n self.metadata = metadata\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n /// Name of the model used\n public let model: String\n /// Why sampling stopped\n public let stopReason: Sampling.StopReason?\n /// The role of the completion\n public let role: Sampling.Message.Role\n /// The completion content\n public let content: Sampling.Message.Content\n\n public init(\n model: String,\n stopReason: Sampling.StopReason? = nil,\n role: Sampling.Message.Role,\n content: Sampling.Message.Content\n ) {\n self.model = model\n self.stopReason = stopReason\n self.role = role\n self.content = content\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Versioning.swift", "import Foundation\n\n/// The Model Context Protocol uses string-based version identifiers\n/// following the format YYYY-MM-DD, to indicate\n/// the last date backwards incompatible changes were made.\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2025-03-26/\npublic enum Version {\n /// All protocol versions supported by this implementation, ordered from newest to oldest.\n static let supported: Set = [\n \"2025-03-26\",\n \"2024-11-05\",\n ]\n\n /// The latest protocol version supported by this implementation.\n public static let latest = supported.max()!\n\n /// Negotiates the protocol version based on the client's request and server's capabilities.\n /// - Parameter clientRequestedVersion: The protocol version requested by the client.\n /// - Returns: The negotiated protocol version. If the client's requested version is supported,\n /// that version is returned. Otherwise, the server's latest supported version is returned.\n static func negotiate(clientRequestedVersion: String) -> String {\n if supported.contains(clientRequestedVersion) {\n return clientRequestedVersion\n }\n return latest\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/ID.swift", "import struct Foundation.UUID\n\n/// A unique identifier for a request.\npublic enum ID: Hashable, Sendable {\n /// A string ID.\n case string(String)\n\n /// A number ID.\n case number(Int)\n\n /// Generates a random string ID.\n public static var random: ID {\n return .string(UUID().uuidString)\n }\n}\n\n// MARK: - ExpressibleByStringLiteral\n\nextension ID: ExpressibleByStringLiteral {\n public init(stringLiteral value: String) {\n self = .string(value)\n }\n}\n\n// MARK: - ExpressibleByIntegerLiteral\n\nextension ID: ExpressibleByIntegerLiteral {\n public init(integerLiteral value: Int) {\n self = .number(value)\n }\n}\n\n// MARK: - CustomStringConvertible\n\nextension ID: CustomStringConvertible {\n public var description: String {\n switch self {\n case .string(let str): return str\n case .number(let num): return String(num)\n }\n }\n}\n\n// MARK: - Codable\n\nextension ID: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n if let string = try? container.decode(String.self) {\n self = .string(string)\n } else if let number = try? container.decode(Int.self) {\n self = .number(number)\n } else if container.decodeNil() {\n // Handle unspecified/null IDs as empty string\n self = .string(\"\")\n } else {\n throw DecodingError.dataCorruptedError(\n in: container, debugDescription: \"ID must be string or number\")\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n switch self {\n case .string(let str): try container.encode(str)\n case .number(let num): try container.encode(num)\n }\n }\n}\n"], ["/swift-sdk/Sources/MCP/Base/Lifecycle.swift", "/// The initialization phase MUST be the first interaction between client and server.\n/// During this phase, the client and server:\n/// - Establish protocol version compatibility\n/// - Exchange and negotiate capabilities\n/// - Share implementation details\n///\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle/#initialization\npublic enum Initialize: Method {\n public static let name: String = \"initialize\"\n\n public struct Parameters: Hashable, Codable, Sendable {\n public let protocolVersion: String\n public let capabilities: Client.Capabilities\n public let clientInfo: Client.Info\n\n public init(\n protocolVersion: String = Version.latest,\n capabilities: Client.Capabilities,\n clientInfo: Client.Info\n ) {\n self.protocolVersion = protocolVersion\n self.capabilities = capabilities\n self.clientInfo = clientInfo\n }\n\n private enum CodingKeys: String, CodingKey {\n case protocolVersion, capabilities, clientInfo\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n protocolVersion =\n try container.decodeIfPresent(String.self, forKey: .protocolVersion)\n ?? Version.latest\n capabilities =\n try container.decodeIfPresent(Client.Capabilities.self, forKey: .capabilities)\n ?? .init()\n clientInfo =\n try container.decodeIfPresent(Client.Info.self, forKey: .clientInfo)\n ?? .init(name: \"unknown\", version: \"0.0.0\")\n }\n }\n\n public struct Result: Hashable, Codable, Sendable {\n public let protocolVersion: String\n public let capabilities: Server.Capabilities\n public let serverInfo: Server.Info\n public let instructions: String?\n }\n}\n\n/// After successful initialization, the client MUST send an initialized notification to indicate it is ready to begin normal operations.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle/#initialization\npublic struct InitializedNotification: Notification {\n public static let name: String = \"notifications/initialized\"\n}\n"], ["/swift-sdk/Sources/MCP/Base/Transport.swift", "import Logging\n\nimport struct Foundation.Data\n\n/// Protocol defining the transport layer for MCP communication\npublic protocol Transport: Actor {\n var logger: Logger { get }\n\n /// Establishes connection with the transport\n func connect() async throws\n\n /// Disconnects from the transport\n func disconnect() async\n\n /// Sends data\n func send(_ data: Data) async throws\n\n /// Receives data in an async sequence\n func receive() -> AsyncThrowingStream\n}\n"], ["/swift-sdk/Sources/MCP/Base/Utilities/Ping.swift", "/// The Model Context Protocol includes an optional ping mechanism that allows either party to verify that their counterpart is still responsive and the connection is alive.\n/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/utilities/ping\npublic enum Ping: Method {\n public static let name: String = \"ping\"\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 03:25:14", "created_task_model": "DeepSeek-R1", "function_skeleton": "public static func parseDataURL ( _ string: String ) -> (mimeType: String, data: Data)? { }", "code_description": "This code segment functions to: Validate and process a structured URI format by extracting metadata components, determining the encoding scheme, decoding the payload using appropriate transformation methods, and returning processed content with combined type information."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```swift\n[TASK_BEGIN]\n public static func parseDataURL(_ string: String) -> (mimeType: String, data: Data)? {\n guard let match = string.wholeMatch(of: dataURLRegex) else { return nil }\n \n let mediaType = match.1.isEmpty ? \"text/plain\" : String(match.1)\n let dataString = String(match.3)\n \n let isBase64 = String(match.0).components(separatedBy: \",\")[0].contains(\";base64\")\n \n if isBase64 {\n guard let data = Data(base64Encoded: dataString) else { return nil }\n return (mediaType, data)\n } else {\n guard let decodedData = dataString.removingPercentEncoding?.data(using: .utf8) else { return nil }\n return (mediaType, decodedData)\n }\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 03-27-15"}, "editdistance_info": {"edit_distance": 45.9916, "calculate_time": "2025-08-21 03:27:15", "true_code_clean": "public static func parseDataURL(_ string: String) -> (mimeType: String, data: Data)? {\n guard let match = string.wholeMatch(of: dataURLRegex) else {\n return nil\n }\n let (_, mediatype, charset, encodedData) = match.output\n let isBase64 = string.contains(\";base64,\")\n var mimeType = mediatype.isEmpty ? \"text/plain\" : String(mediatype)\n if let charset = charset, !charset.isEmpty, mimeType.starts(with: \"text/\") {\n mimeType += \";charset=\\(charset)\"\n }\n let decodedData: Data\n if isBase64 {\n guard let base64Data = Data(base64Encoded: String(encodedData)) else { return nil }\n decodedData = base64Data\n } else {\n guard\n let percentDecodedData = String(encodedData).removingPercentEncoding?.data(\n using: .utf8)\n else { return nil }\n decodedData = percentDecodedData\n }\n return (mimeType: mimeType, data: decodedData)\n }", "predict_code_clean": "public static func parseDataURL(_ string: String) -> (mimeType: String, data: Data)? {\n guard let match = string.wholeMatch(of: dataURLRegex) else { return nil }\n let mediaType = match.1.isEmpty ? \"text/plain\" : String(match.1)\n let dataString = String(match.3)\n let isBase64 = String(match.0).components(separatedBy: \",\")[0].contains(\";base64\")\n if isBase64 {\n guard let data = Data(base64Encoded: dataString) else { return nil }\n return (mediaType, data)\n } else {\n guard let decodedData = dataString.removingPercentEncoding?.data(using: .utf8) else { return nil }\n return (mediaType, decodedData)\n }\n }"}}