diff --git a/Docs/architecture.md b/Docs/architecture.md index b8b55692..386e9f43 100644 --- a/Docs/architecture.md +++ b/Docs/architecture.md @@ -53,7 +53,7 @@ alter that request's response contract. Each Xcode installation has at most one owned headless host process, shared by every MCP session. A host connection owns its process: it starts it on first use, sends one -`initialize`, assigns upstream request IDs, returns progress to the requesting +`initialize`, assigns host request IDs, returns progress to the requesting session, and sends `notifications/cancelled` when a request is cancelled or times out. A timeout fails only that request. @@ -67,7 +67,7 @@ in the result's `_meta`. The broker records that report for the session and removes it from the client's result. When a process exits or violates the protocol, its in-flight requests fail with -`upstream unavailable`, handles created by that process expire, and the next +`host unavailable`, handles created by that process expire, and the next request starts a new process. Delivery-unknown mutations are not replayed. Closing an MCP session releases its handles. A headless host for a non-default installation stops after `NativeHostBroker.idleHostGracePeriod` @@ -94,12 +94,12 @@ startup; write failure unwinds acquired resources. ## Streamable HTTP contract -- Every request is checked by one Host and Origin policy before route resolution, session creation, debug reset, or upstream I/O. This includes `/health`, `/debug/*`, MCP routes, and unknown routes. +- Every request is checked by one Host and Origin policy before route resolution, session creation, debug reset, or host I/O. This includes `/health`, `/debug/*`, MCP routes, and unknown routes. - A `Host` header must name an IP address, `localhost`, or the configured listen host, with any port, since a port forward delivers the client's port; multiple or other values return `403`. A page that rebinds its own domain to the listener therefore cannot reach it. A missing `Host` is allowed. - A missing `Origin` header is allowed for non-browser clients. When `Origin` is present it must be one valid HTTP(S) origin whose host and port match the actual listener policy; empty, multiple, `null`, malformed, and cross-origin values return `403`. -- `/debug/upstreams` and `/debug/reset` return `404` unless the server enables debug endpoints (`--debug-endpoints`) and listens on loopback. +- `/debug/hosts` and `/debug/reset` return `404` unless the server enables debug endpoints (`--debug-endpoints`) and listens on loopback. - `POST /mcp` requires `Content-Type: application/json`. A client whose `Accept` omits `text/event-stream` gets every reply as JSON and no progress. -- A POST that carries a request is answered with one JSON-RPC response; a client notification or response gets `202`. When the request reports progress before its reply, or its reply takes longer than 15 seconds, the POST response becomes an event stream (`text/event-stream`) that carries the progress notifications and keepalive comments every 15 seconds, and ends with the response; otherwise the response is JSON. Clients give up on a response that does not start within a minute, and on a stream that stays silent for a few minutes. `initialize` is never streamed. When a host's response is not valid JSON-RPC for its request, the client receives error `-32603` (`invalid upstream response`) for that request. +- A POST that carries a request is answered with one JSON-RPC response; a client notification or response gets `202`. When the request reports progress before its reply, or its reply takes longer than 15 seconds, the POST response becomes an event stream (`text/event-stream`) that carries the progress notifications and keepalive comments every 15 seconds, and ends with the response; otherwise the response is JSON. Clients give up on a response that does not start within a minute, and on a stream that stays silent for a few minutes. `initialize` is never streamed. When a host's response is not valid JSON-RPC for its request, the client receives error `-32603` (`invalid host response`) for that request. - HTTP owns MCP sessions. It generates `MCP-Session-Id` on `initialize`, ignoring caller-provided ids, and ends the runtime's side of a session when the session is deleted, expires, or the server stops. An `initialize` that arrives while the server is stopping returns `503`. - After initialize, `POST`, `GET`, and `DELETE` require `MCP-Session-Id`. An explicit `MCP-Protocol-Version` must be valid, supported, and match the negotiated version. - When `MCP-Protocol-Version` is omitted, the server uses the session's negotiated version. If no negotiated version exists, it evaluates the protocol-defined fallback `2025-03-26` and returns `400` when that version is unsupported. @@ -109,7 +109,7 @@ startup; write failure unwinds acquired resources. - A GET stream carries a keepalive comment every 15 seconds. - A session with no in-flight HTTP request and no open SSE stream is retained for five minutes after its last client activity so that an interrupted SSE connection can reconnect. A one-minute sweep then terminates stale sessions and their buffered notifications; outbound server notifications do not extend this lifetime. - HTTP connection, SSE connection, request, and response access events are debug telemetry, including expected protocol-level `4xx` responses. The response remains the client-visible error contract. -- Empty, singleton, and mixed JSON-RPC arrays return `400`; the internal executor and response router operate on typed single messages. An array response from an upstream is a protocol violation. +- Empty, singleton, and mixed JSON-RPC arrays return `400`; the internal executor and response router operate on typed single messages. An array response from a host is a protocol violation. - Host `notifications/progress` is delivered only on the POST response stream of the request that carries that progress token, never to another session, another request, or a GET stream. It is dropped when the request has finished, and while a client that falls behind has not read the earlier ones. Other host notifications fan out to the GET streams of the sessions using that host. - HTTP owns each session's bounded SSE notification buffer. On overflow it drops the oldest notification and emits at most one warning per 30 seconds per session. `dropped_notifications` is cumulative for that session, while the warning also reports the dropped delta and sanitized methods of the notifications actually evicted; notification payloads are never logged. Unhandled server notifications remain debug-level events. diff --git a/Docs/configuration.md b/Docs/configuration.md index 86955164..8decf86b 100644 --- a/Docs/configuration.md +++ b/Docs/configuration.md @@ -56,7 +56,7 @@ Use `xcode-mcp-proxy-server --help` for CLI usage. | `--max-body-bytes bytes` | Maximum accepted HTTP request body size. | | `--share-compilation-cache` | Enable shared compilation caching and Swift/Clang prefix mapping in native hosts. Off by default; see [compilation caching](#compilation-caching). | | `--auto-approve` | Automatically allow MCP connection dialogs for agents connecting directly to GUI Xcode. Off by default; requires macOS Accessibility access. | -| `--debug-endpoints` | Serve `/debug/upstreams` and `/debug/reset` when the listener is loopback. Off by default. | +| `--debug-endpoints` | Serve `/debug/hosts` and `/debug/reset` when the listener is loopback. Off by default. | | `--force-restart` | Terminate an existing `xcode-mcp-proxy-server` on the listen port before starting. | | `--dry-run` | Print the resolved server command without starting it. | diff --git a/Docs/maintainer-architecture.md b/Docs/maintainer-architecture.md index 6e1377a3..64cc4462 100644 --- a/Docs/maintainer-architecture.md +++ b/Docs/maintainer-architecture.md @@ -125,7 +125,7 @@ three GUI tools, including `XcodeListWindows`, from installed Xcode schemas without executing their actions. Standalone native-host transports omit this flag and advertise only executable tools. The broker keeps their native tab selectors and results, and lazily starts Apple's `mcpbridge` -through the existing upstream connection transport. That connection shares +through the existing host connection transport. That connection shares request-ID/progress mapping, cancellation, restart, and shutdown handling with headless connections. Bridge failures never enter Organizer collection. Stopping the bridge terminates only the owned bridge process, leaving Xcode diff --git a/Docs/migrations/native-backend.md b/Docs/migrations/native-backend.md index 8934efa1..038e2d63 100644 --- a/Docs/migrations/native-backend.md +++ b/Docs/migrations/native-backend.md @@ -227,3 +227,8 @@ after initialize and send individual JSON-RPC messages instead of batch arrays. An explicit `MCP-Protocol-Version` must match negotiation. The SDK handles these details. See the [HTTP contract](../architecture.md#streamable-http-contract) for expiry, recovery, and header errors. + +The debug snapshot moved from `/debug/upstreams` to `/debug/hosts`. Host error +messages say `host` instead of `upstream`: `host unavailable`, `host overloaded`, +`host timeout`, and `invalid host response`. The JSON-RPC error codes are +unchanged. diff --git a/Sources/XcodeMCPCore/CoreRuntime/MCPBridgeRuntimeError.swift b/Sources/XcodeMCPCore/CoreRuntime/MCPRuntimeError.swift similarity index 80% rename from Sources/XcodeMCPCore/CoreRuntime/MCPBridgeRuntimeError.swift rename to Sources/XcodeMCPCore/CoreRuntime/MCPRuntimeError.swift index 8f7f16ec..ba468d4b 100644 --- a/Sources/XcodeMCPCore/CoreRuntime/MCPBridgeRuntimeError.swift +++ b/Sources/XcodeMCPCore/CoreRuntime/MCPRuntimeError.swift @@ -1,4 +1,4 @@ -package enum MCPBridgeRuntimeError: Error, Equatable, Sendable { +package enum MCPRuntimeError: Error, Equatable, Sendable { case closed case invalidRequest(String) case invalidResponse(String) diff --git a/Sources/XcodeMCPCore/ProcessRuntime/Process/MCPBridgeInvocation.swift b/Sources/XcodeMCPCore/ProcessRuntime/Process/MCPProcessInvocation.swift similarity index 52% rename from Sources/XcodeMCPCore/ProcessRuntime/Process/MCPBridgeInvocation.swift rename to Sources/XcodeMCPCore/ProcessRuntime/Process/MCPProcessInvocation.swift index 63a26f34..9251fce5 100644 --- a/Sources/XcodeMCPCore/ProcessRuntime/Process/MCPBridgeInvocation.swift +++ b/Sources/XcodeMCPCore/ProcessRuntime/Process/MCPProcessInvocation.swift @@ -1,12 +1,12 @@ /// Raw invocation of a configured MCP process. -package struct MCPBridgeInvocation: Equatable, Sendable { - /// Raw process command used to launch the bridge. +package struct MCPProcessInvocation: Equatable, Sendable { + /// Raw process command used to launch the process. package let command: String - /// Raw process arguments passed to the bridge command. + /// Raw process arguments passed to the command. package let arguments: [String] - /// Creates a raw bridge process invocation. + /// Creates a raw process invocation. package init(command: String, arguments: [String]) { self.command = command self.arguments = arguments diff --git a/Sources/XcodeMCPCore/ProcessRuntime/Process/NativeHostInvocation.swift b/Sources/XcodeMCPCore/ProcessRuntime/Process/NativeHostInvocation.swift index ebbfcc84..15dd15b7 100644 --- a/Sources/XcodeMCPCore/ProcessRuntime/Process/NativeHostInvocation.swift +++ b/Sources/XcodeMCPCore/ProcessRuntime/Process/NativeHostInvocation.swift @@ -11,7 +11,7 @@ package enum NativeHostInvocation { environment: [String: String] = ProcessInfo.processInfo.environment, executableURL: URL? = Bundle.main.executableURL, fileSystem: FileSystemClient = .liveValue - ) throws -> MCPBridgeInvocation { + ) throws -> MCPProcessInvocation { let executable: URL if let bundleURL { executable = try resolveExecutable(in: bundleURL, fileSystem: fileSystem) @@ -35,21 +35,21 @@ package enum NativeHostInvocation { guard let bundle = candidates.first(where: { fileSystem.isExecutableFile($0.appendingPathComponent("Contents/MacOS/\(executableName)").path) }) else { - throw MCPBridgeRuntimeError.transportUnavailable("Cannot find \(bundleName). Install XcodeMCPKit or supply nativeHostBundleURL / XCODE_MCP_NATIVE_HOST_BUNDLE.") + throw MCPRuntimeError.transportUnavailable("Cannot find \(bundleName). Install XcodeMCPKit or supply nativeHostBundleURL / XCODE_MCP_NATIVE_HOST_BUNDLE.") } executable = try resolveExecutable(in: bundle, fileSystem: fileSystem) } var arguments: [String] = [] if let developerDirectoryURL { arguments += ["--developer-dir", developerDirectoryURL.path] } if sharesCompilationCache { arguments.append("--share-compilation-cache") } - return MCPBridgeInvocation(command: executable.path, arguments: arguments) + return MCPProcessInvocation(command: executable.path, arguments: arguments) } private static func resolveExecutable(in bundleURL: URL, fileSystem: FileSystemClient) throws -> URL { let executable = bundleURL.standardizedFileURL.resolvingSymlinksInPath() .appendingPathComponent("Contents/MacOS/\(executableName)") guard fileSystem.isExecutableFile(executable.path) else { - throw MCPBridgeRuntimeError.transportUnavailable("Native helper executable is unavailable: \(executable.path)") + throw MCPRuntimeError.transportUnavailable("Native helper executable is unavailable: \(executable.path)") } return executable } diff --git a/Sources/XcodeMCPCore/ProcessRuntime/Bridge/UpstreamDiagnostics.swift b/Sources/XcodeMCPCore/ProcessRuntime/Session/MCPProcessDiagnostics.swift similarity index 98% rename from Sources/XcodeMCPCore/ProcessRuntime/Bridge/UpstreamDiagnostics.swift rename to Sources/XcodeMCPCore/ProcessRuntime/Session/MCPProcessDiagnostics.swift index 4acaaee7..b52c8537 100644 --- a/Sources/XcodeMCPCore/ProcessRuntime/Bridge/UpstreamDiagnostics.swift +++ b/Sources/XcodeMCPCore/ProcessRuntime/Session/MCPProcessDiagnostics.swift @@ -1,6 +1,6 @@ import os -extension Upstream { +extension MCPProcess { /// Where an owned process session reports conditions that it handles itself, such as a /// dropped stdout line or a failed signal. package struct Diagnostics: Sendable { diff --git a/Sources/XcodeMCPCore/ProcessRuntime/Bridge/UpstreamProcess.swift b/Sources/XcodeMCPCore/ProcessRuntime/Session/MCPProcessLauncher.swift similarity index 84% rename from Sources/XcodeMCPCore/ProcessRuntime/Bridge/UpstreamProcess.swift rename to Sources/XcodeMCPCore/ProcessRuntime/Session/MCPProcessLauncher.swift index 67c360a9..e3bb8d3e 100644 --- a/Sources/XcodeMCPCore/ProcessRuntime/Bridge/UpstreamProcess.swift +++ b/Sources/XcodeMCPCore/ProcessRuntime/Session/MCPProcessLauncher.swift @@ -25,7 +25,7 @@ private final class StdinWriter: @unchecked Sendable { self.onComplete = onComplete } - func send(_ payload: Data) -> Upstream.SendResult { + func send(_ payload: Data) -> MCPProcess.SendResult { state.lock() defer { state.unlock() } @@ -77,7 +77,7 @@ private final class StdinWriter: @unchecked Sendable { } } -package struct UpstreamProcessStartedIO: Sendable { +package struct MCPProcessStartedIO: Sendable { package let stdoutChunks: AsyncStream package let stderrChunks: AsyncStream @@ -90,15 +90,15 @@ package struct UpstreamProcessStartedIO: Sendable { } } -package protocol UpstreamProcessDriving: AnyObject, Sendable { +package protocol MCPProcessDriving: AnyObject, Sendable { func start( command: String, args: [String], environment: [String: String], maxQueuedWriteBytes: Int, onTermination: @escaping @Sendable (Int32) -> Void - ) throws -> UpstreamProcessStartedIO - func sendStdin(_ payload: Data) -> Upstream.SendResult + ) throws -> MCPProcessStartedIO + func sendStdin(_ payload: Data) -> MCPProcess.SendResult func closeStdin() func terminate() -> Bool func forceTerminate() -> Bool @@ -107,23 +107,23 @@ package protocol UpstreamProcessDriving: AnyObject, Sendable { func waitForOutputStopped() async } -package protocol UpstreamProcessDriverMaking: Sendable { - func makeDriver() -> any UpstreamProcessDriving +package protocol MCPProcessDriverMaking: Sendable { + func makeDriver() -> any MCPProcessDriving } -package struct LiveUpstreamProcessDriverFactory: UpstreamProcessDriverMaking { - private let diagnostics: Upstream.Diagnostics +package struct LiveMCPProcessDriverFactory: MCPProcessDriverMaking { + private let diagnostics: MCPProcess.Diagnostics - package init(diagnostics: Upstream.Diagnostics = .unifiedLog) { + package init(diagnostics: MCPProcess.Diagnostics = .unifiedLog) { self.diagnostics = diagnostics } - package func makeDriver() -> any UpstreamProcessDriving { - LiveUpstreamProcessDriver(diagnostics: diagnostics) + package func makeDriver() -> any MCPProcessDriving { + LiveMCPProcessDriver(diagnostics: diagnostics) } } -private final class LiveUpstreamProcessDriver: UpstreamProcessDriving, @unchecked Sendable { +private final class LiveMCPProcessDriver: MCPProcessDriving, @unchecked Sendable { private struct State { var process: Process? var stdinPipe: Pipe? @@ -134,11 +134,11 @@ private final class LiveUpstreamProcessDriver: UpstreamProcessDriving, @unchecke var stderrReader: OrderedPipeReader? } - private let diagnostics: Upstream.Diagnostics + private let diagnostics: MCPProcess.Diagnostics private let lock = NSLock() private var state = State() - init(diagnostics: Upstream.Diagnostics) { + init(diagnostics: MCPProcess.Diagnostics) { self.diagnostics = diagnostics } @@ -148,7 +148,7 @@ private final class LiveUpstreamProcessDriver: UpstreamProcessDriving, @unchecke environment: [String: String], maxQueuedWriteBytes: Int, onTermination: @escaping @Sendable (Int32) -> Void - ) throws -> UpstreamProcessStartedIO { + ) throws -> MCPProcessStartedIO { let stdinPipe = Pipe() let stdoutPipe = Pipe() let stderrPipe = Pipe() @@ -169,11 +169,11 @@ private final class LiveUpstreamProcessDriver: UpstreamProcessDriving, @unchecke let stdoutReader = OrderedPipeReader( fileHandle: stdoutPipe.fileHandleForReading, - label: "XcodeMCPProxy.UpstreamSession.stdout" + label: "XcodeMCPProxy.MCPProcessSession.stdout" ) let stderrReader = OrderedPipeReader( fileHandle: stderrPipe.fileHandleForReading, - label: "XcodeMCPProxy.UpstreamSession.stderr" + label: "XcodeMCPProxy.MCPProcessSession.stderr" ) do { @@ -190,7 +190,7 @@ private final class LiveUpstreamProcessDriver: UpstreamProcessDriving, @unchecke let stdinWriter = StdinWriter( fileHandle: stdinPipe.fileHandleForWriting, maxQueuedWriteBytes: maxQueuedWriteBytes, - label: "XcodeMCPProxy.UpstreamSession.stdin", + label: "XcodeMCPProxy.MCPProcessSession.stdin", onComplete: { [weak self] bytes, error in self?.completeStdinWrite(bytes: bytes, error: error) } @@ -211,13 +211,13 @@ private final class LiveUpstreamProcessDriver: UpstreamProcessDriving, @unchecke try? stdoutPipe.fileHandleForWriting.close() try? stderrPipe.fileHandleForWriting.close() - return UpstreamProcessStartedIO( + return MCPProcessStartedIO( stdoutChunks: stdoutReader.chunks, stderrChunks: stderrReader.chunks ) } - func sendStdin(_ payload: Data) -> Upstream.SendResult { + func sendStdin(_ payload: Data) -> MCPProcess.SendResult { guard let stdinWriter = lock.withLock({ state.stdinWriter }) else { return .unavailable(.notStarted) } @@ -250,7 +250,7 @@ private final class LiveUpstreamProcessDriver: UpstreamProcessDriving, @unchecke let result = kill(process.processIdentifier, SIGKILL) if result != 0, errno != ESRCH { diagnostics.error( - "Failed to force-terminate upstream process", + "Failed to force-terminate MCP process", metadata: [ "pid": "\(process.processIdentifier)", "errno": "\(errno)", @@ -290,7 +290,7 @@ private final class LiveUpstreamProcessDriver: UpstreamProcessDriving, @unchecke let stdinWriter = lock.withLock { state.stdinWriter } stdinWriter?.completeWrite(bytes: bytes) if let error { - diagnostics.warning("Upstream async write failed", metadata: ["error": "\(error)"]) + diagnostics.warning("MCP process async write failed", metadata: ["error": "\(error)"]) } } @@ -313,16 +313,16 @@ private final class LiveUpstreamProcessDriver: UpstreamProcessDriving, @unchecke let result = fcntl(fd, F_SETNOSIGPIPE, 1) if result == -1 { diagnostics.warning( - "Failed to disable SIGPIPE on upstream stdin pipe", + "Failed to disable SIGPIPE on MCP process stdin pipe", metadata: ["errno": "\(errno)"] ) } } } -private final class UpstreamProcessCancellation: @unchecked Sendable { +private final class MCPProcessCancellation: @unchecked Sendable { private struct State { - var driver: (any UpstreamProcessDriving)? + var driver: (any MCPProcessDriving)? var isCancelled = false var stdinClosed = false var outputStopped = false @@ -335,7 +335,7 @@ private final class UpstreamProcessCancellation: @unchecked Sendable { lock.withLock { state.isCancelled } } - func install(_ driver: any UpstreamProcessDriving) { + func install(_ driver: any MCPProcessDriving) { let shouldCancel = lock.withLock { () -> Bool in precondition(state.driver == nil) state.driver = driver @@ -348,7 +348,7 @@ private final class UpstreamProcessCancellation: @unchecked Sendable { } func closeStdin() { - let driver = lock.withLock { () -> (any UpstreamProcessDriving)? in + let driver = lock.withLock { () -> (any MCPProcessDriving)? in guard !state.stdinClosed, let driver = state.driver else { return nil } state.stdinClosed = true return driver @@ -357,7 +357,7 @@ private final class UpstreamProcessCancellation: @unchecked Sendable { } func stopOutput() { - let driver = lock.withLock { () -> (any UpstreamProcessDriving)? in + let driver = lock.withLock { () -> (any MCPProcessDriving)? in guard !state.outputStopped, let driver = state.driver else { return nil } state.outputStopped = true return driver @@ -370,7 +370,7 @@ private final class UpstreamProcessCancellation: @unchecked Sendable { } func cancel() { - let driver = lock.withLock { () -> (any UpstreamProcessDriving)? in + let driver = lock.withLock { () -> (any MCPProcessDriving)? in guard state.isCancelled == false else { return nil } state.isCancelled = true return state.driver @@ -380,13 +380,13 @@ private final class UpstreamProcessCancellation: @unchecked Sendable { cancelDriver(driver) } - private func cancelDriver(_ driver: any UpstreamProcessDriving) { + private func cancelDriver(_ driver: any MCPProcessDriving) { _ = driver.terminate() stopOutput() } } -package final class UpstreamTerminationDelay: Sendable { +package final class MCPProcessTerminationDelay: Sendable { private let cancelImpl: @Sendable () -> Void private let terminal: AsyncTerminalSignal @@ -407,20 +407,20 @@ package final class UpstreamTerminationDelay: Sendable { } } -package protocol UpstreamTerminationDelayScheduling: Sendable { +package protocol MCPProcessTerminationDelayScheduling: Sendable { func schedule( after delay: Duration, operation: @escaping @Sendable () -> Void - ) -> UpstreamTerminationDelay + ) -> MCPProcessTerminationDelay } -package struct LiveUpstreamTerminationDelayScheduler: UpstreamTerminationDelayScheduling { +package struct LiveMCPProcessTerminationDelayScheduler: MCPProcessTerminationDelayScheduling { package init() {} package func schedule( after delay: Duration, operation: @escaping @Sendable () -> Void - ) -> UpstreamTerminationDelay { + ) -> MCPProcessTerminationDelay { let terminal = AsyncTerminalSignal() let source = DispatchSource.makeTimerSource( queue: DispatchQueue.global(qos: .utility) @@ -429,7 +429,7 @@ package struct LiveUpstreamTerminationDelayScheduler: UpstreamTerminationDelaySc source.setCancelHandler(handler: terminal.signal) source.schedule(deadline: .now() + Self.dispatchInterval(delay)) source.resume() - return UpstreamTerminationDelay(terminal: terminal) { + return MCPProcessTerminationDelay(terminal: terminal) { source.cancel() } } @@ -450,7 +450,7 @@ package struct LiveUpstreamTerminationDelayScheduler: UpstreamTerminationDelaySc } } -private final class UpstreamTerminationRace: Sendable { +private final class MCPProcessTerminationRace: Sendable { private struct State { var result: Bool? var waiters: [CheckedContinuation] = [] @@ -481,7 +481,7 @@ private final class UpstreamTerminationRace: Sendable { } } -package struct UpstreamProcess: UpstreamSessionFactory { +package struct MCPProcessLauncher: MCPProcessSessionFactory { package struct Config: Sendable { package var command: String package var args: [String] @@ -489,10 +489,10 @@ package struct UpstreamProcess: UpstreamSessionFactory { package var maxQueuedWriteBytes: Int package var terminationDrainGrace: Duration package var terminationSignalGrace: Duration - package var terminationDelayScheduler: any UpstreamTerminationDelayScheduling + package var terminationDelayScheduler: any MCPProcessTerminationDelayScheduling package var clock: ClockClient - package var diagnostics: Upstream.Diagnostics - package var driverFactory: any UpstreamProcessDriverMaking + package var diagnostics: MCPProcess.Diagnostics + package var driverFactory: any MCPProcessDriverMaking package init( command: String, @@ -501,11 +501,11 @@ package struct UpstreamProcess: UpstreamSessionFactory { maxQueuedWriteBytes: Int, terminationDrainGrace: Duration = .milliseconds(250), terminationSignalGrace: Duration = .seconds(1), - terminationDelayScheduler: any UpstreamTerminationDelayScheduling = - LiveUpstreamTerminationDelayScheduler(), + terminationDelayScheduler: any MCPProcessTerminationDelayScheduling = + LiveMCPProcessTerminationDelayScheduler(), clock: ClockClient = .liveValue, - diagnostics: Upstream.Diagnostics = .unifiedLog, - driverFactory: (any UpstreamProcessDriverMaking)? = nil + diagnostics: MCPProcess.Diagnostics = .unifiedLog, + driverFactory: (any MCPProcessDriverMaking)? = nil ) { self.command = command self.args = args @@ -516,7 +516,7 @@ package struct UpstreamProcess: UpstreamSessionFactory { self.terminationDelayScheduler = terminationDelayScheduler self.clock = clock self.diagnostics = diagnostics - self.driverFactory = driverFactory ?? LiveUpstreamProcessDriverFactory(diagnostics: diagnostics) + self.driverFactory = driverFactory ?? LiveMCPProcessDriverFactory(diagnostics: diagnostics) } } @@ -526,21 +526,21 @@ package struct UpstreamProcess: UpstreamSessionFactory { self.config = configuration } - package func startSession() async throws -> any UpstreamSession { - try await ProcessBackedUpstreamSession.start(configuration: config) + package func startSession() async throws -> any MCPProcessSession { + try await LiveMCPProcessSession.start(configuration: config) } } -package actor ProcessBackedUpstreamSession: UpstreamSession { - package nonisolated let events: AsyncStream - private let continuation: AsyncStream.Continuation +package actor LiveMCPProcessSession: MCPProcessSession { + package nonisolated let events: AsyncStream + private let continuation: AsyncStream.Continuation - private let config: UpstreamProcess.Config - private var diagnostics: Upstream.Diagnostics { config.diagnostics } + private let config: MCPProcessLauncher.Config + private var diagnostics: MCPProcess.Diagnostics { config.diagnostics } private let maxBufferedStderrBytes = 16 * 1024 - private nonisolated let cancellation = UpstreamProcessCancellation() + private nonisolated let cancellation = MCPProcessCancellation() - private var driver: (any UpstreamProcessDriving)? + private var driver: (any MCPProcessDriving)? private var stdoutTask: Task? private var stderrTask: Task? private var framer = StdioFramer() @@ -552,24 +552,24 @@ package actor ProcessBackedUpstreamSession: UpstreamSession { private var suppressExitEvent = false private var pendingExitStatus: Int32? private var terminationDrainTimeoutTask: Task? - private var terminationRaces: [UUID: UpstreamTerminationRace] = [:] + private var terminationRaces: [UUID: MCPProcessTerminationRace] = [:] private var didFinishEvents = false private var isStopping = false private var stopCompleted = false private var stopTask: Task? package static func start( - configuration: UpstreamProcess.Config - ) async throws -> ProcessBackedUpstreamSession { - let session = ProcessBackedUpstreamSession(configuration: configuration) + configuration: MCPProcessLauncher.Config + ) async throws -> LiveMCPProcessSession { + let session = LiveMCPProcessSession(configuration: configuration) try await session.runProcess() return session } - private init(configuration: UpstreamProcess.Config) { + private init(configuration: MCPProcessLauncher.Config) { self.config = configuration - var streamContinuation: AsyncStream.Continuation! + var streamContinuation: AsyncStream.Continuation! self.events = AsyncStream { continuation in streamContinuation = continuation } @@ -580,17 +580,17 @@ package actor ProcessBackedUpstreamSession: UpstreamSession { cancellation.cancel() } - package func send(_ data: Data) async -> Upstream.SendResult { + package func send(_ data: Data) async -> MCPProcess.SendResult { if didFinishEvents || terminationObserved { - diagnostics.warning("Upstream send skipped because session has terminated") + diagnostics.warning("MCP process send skipped because session has terminated") return .unavailable(.terminated) } if isStopping { - diagnostics.warning("Upstream send skipped because session is stopping") + diagnostics.warning("MCP process send skipped because session is stopping") return .unavailable(.shuttingDown) } guard let driver else { - diagnostics.warning("Upstream send skipped because session never started") + diagnostics.warning("MCP process send skipped because session never started") return .unavailable(.notStarted) } @@ -602,7 +602,7 @@ package actor ProcessBackedUpstreamSession: UpstreamSession { let result = driver.sendStdin(payload) if result == .backpressure { diagnostics.warning( - "Upstream write queue overloaded", + "MCP process write queue overloaded", metadata: [ "payload_bytes": "\(payload.count)", "limit_bytes": "\(config.maxQueuedWriteBytes)", @@ -628,7 +628,7 @@ package actor ProcessBackedUpstreamSession: UpstreamSession { } } -private extension ProcessBackedUpstreamSession { +private extension LiveMCPProcessSession { func runProcess() async throws { framer = StdioFramer() stderrBuffer = "" @@ -650,7 +650,7 @@ private extension ProcessBackedUpstreamSession { let driver = config.driverFactory.makeDriver() self.driver = driver cancellation.install(driver) - let io: UpstreamProcessStartedIO + let io: MCPProcessStartedIO do { io = try driver.start( command: config.command, @@ -695,10 +695,10 @@ private extension ProcessBackedUpstreamSession { let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) if !trimmed.isEmpty { let preview = String(trimmed.prefix(200)) - diagnostics.warning("Dropping non-JSON upstream stdout", metadata: ["preview": "\(preview)"]) + diagnostics.warning("Dropping non-JSON MCP process stdout", metadata: ["preview": "\(preview)"]) } } else { - diagnostics.warning("Dropping non-UTF8 upstream stdout", metadata: ["bytes": "\(message.count)"]) + diagnostics.warning("Dropping non-UTF8 MCP process stdout", metadata: ["bytes": "\(message.count)"]) } continue } @@ -715,7 +715,7 @@ private extension ProcessBackedUpstreamSession { } diagnostics.error( - "Fatal upstream stdout protocol violation", + "Fatal MCP process stdout protocol violation", metadata: [ "reason": protocolViolation.reason.rawValue, "buffered_bytes": "\(protocolViolation.bufferedByteCount)", @@ -757,7 +757,7 @@ private extension ProcessBackedUpstreamSession { } flushBufferedStderrChunkIfNeeded() } else { - diagnostics.error("Upstream stderr (binary)", metadata: ["bytes": "\(data.count)"]) + diagnostics.error("MCP process stderr (binary)", metadata: ["bytes": "\(data.count)"]) } } @@ -840,7 +840,7 @@ private extension ProcessBackedUpstreamSession { let grace = config.terminationSignalGrace guard grace > .zero else { return false } let id = UUID() - let race = UpstreamTerminationRace() + let race = MCPProcessTerminationRace() terminationRaces[id] = race if terminationObserved { race.complete(true) } let delay = config.terminationDelayScheduler.schedule(after: grace) { @@ -856,7 +856,7 @@ private extension ProcessBackedUpstreamSession { func waitUntilTerminationObserved() async { if terminationObserved { return } let id = UUID() - let race = UpstreamTerminationRace() + let race = MCPProcessTerminationRace() terminationRaces[id] = race if terminationObserved { race.complete(true) } _ = await race.value() diff --git a/Sources/XcodeMCPCore/ProcessRuntime/Bridge/UpstreamClient.swift b/Sources/XcodeMCPCore/ProcessRuntime/Session/MCPProcessSession.swift similarity index 63% rename from Sources/XcodeMCPCore/ProcessRuntime/Bridge/UpstreamClient.swift rename to Sources/XcodeMCPCore/ProcessRuntime/Session/MCPProcessSession.swift index 94f9b6f2..7df26111 100644 --- a/Sources/XcodeMCPCore/ProcessRuntime/Bridge/UpstreamClient.swift +++ b/Sources/XcodeMCPCore/ProcessRuntime/Session/MCPProcessSession.swift @@ -1,9 +1,9 @@ import Foundation import XcodeMCPWire -package enum Upstream {} +package enum MCPProcess {} -extension Upstream { +extension MCPProcess { package enum Event: Sendable { case message(Data) case stderr(String) @@ -20,27 +20,27 @@ extension Upstream { case shuttingDown } - /// Why a send did not reach the upstream. Backpressure is the only case - /// that should count against the upstream's health; an unavailable slot is + /// Why a send did not reach the process. Backpressure is the only case + /// that should count against the process's health; an unavailable slot is /// already handled by the exit/quarantine machinery. package enum SendResult: Sendable, Equatable { case accepted case backpressure - case unavailable(Upstream.UnavailableReason) + case unavailable(MCPProcess.UnavailableReason) } } -package protocol UpstreamSession: AnyObject, Sendable { - var events: AsyncStream { get } +package protocol MCPProcessSession: AnyObject, Sendable { + var events: AsyncStream { get } /// Sends a synchronous best-effort stop signal to the owned process I/O. /// Completion remains the responsibility of ``stop()``. nonisolated func cancel() - func send(_ data: Data) async -> Upstream.SendResult + func send(_ data: Data) async -> MCPProcess.SendResult /// Closes MCP input and waits for process exit and output drain. Unresponsive /// processes are terminated after the configured shutdown grace. func stop() async } -package protocol UpstreamSessionFactory: Sendable { - func startSession() async throws -> any UpstreamSession +package protocol MCPProcessSessionFactory: Sendable { + func startSession() async throws -> any MCPProcessSession } diff --git a/Sources/XcodeMCPKit/Internal/ClientRuntime/InitializedMCPClientSession.swift b/Sources/XcodeMCPKit/Internal/ClientRuntime/InitializedMCPClientSession.swift index 9b00ce8c..edf1beae 100644 --- a/Sources/XcodeMCPKit/Internal/ClientRuntime/InitializedMCPClientSession.swift +++ b/Sources/XcodeMCPKit/Internal/ClientRuntime/InitializedMCPClientSession.swift @@ -324,7 +324,7 @@ package actor InitializedMCPClientSession { onProgress: ProgressHandler? = nil ) async throws -> JSONValue { guard method.isEmpty == false else { - throw MCPBridgeRuntimeError.invalidRequest("method must not be empty") + throw MCPRuntimeError.invalidRequest("method must not be empty") } try ensureOpen() @@ -360,7 +360,7 @@ package actor InitializedMCPClientSession { let payload = try makeJSONRPCPayload(id: id, method: method, params: requestParams) let requestDeadline = deadline if requestDeadline?.hasExpired == true { - throw MCPBridgeRuntimeError.requestTimedOut(method: method) + throw MCPRuntimeError.requestTimedOut(method: method) } let operation = MCPClientOperation( envelope: try MCPClientEnvelope(data: payload), @@ -404,7 +404,7 @@ package actor InitializedMCPClientSession { var iterator = resultStream.makeAsyncIterator() guard let result = try await iterator.next() else { try Task.checkCancellation() - throw MCPBridgeRuntimeError.closed + throw MCPRuntimeError.closed } return result } onCancel: { @@ -474,10 +474,10 @@ package actor InitializedMCPClientSession { return loaded } guard case .string(let nextCursor) = rawCursor else { - throw MCPBridgeRuntimeError.invalidResponse("\(method) returned an invalid cursor") + throw MCPRuntimeError.invalidResponse("\(method) returned an invalid cursor") } guard seenCursors.insert(nextCursor).inserted else { - throw MCPBridgeRuntimeError.invalidResponse("\(method) returned a cursor cycle") + throw MCPRuntimeError.invalidResponse("\(method) returned a cursor cycle") } cursor = nextCursor } @@ -510,7 +510,7 @@ package actor InitializedMCPClientSession { let lanes = Array(progressLanes.values) progressHandlers.removeAll() progressLanes.removeAll() - pendingRequests.failAll(error: MCPBridgeRuntimeError.closed) + pendingRequests.failAll(error: MCPRuntimeError.closed) await pendingRequests.drainAllSendTasks() var deferredProgressTasks: [Task] = [] for lane in lanes { @@ -545,7 +545,7 @@ package actor InitializedMCPClientSession { isolated deinit { eventTask?.cancel() for lane in progressLanes.values { lane.cancel() } - pendingRequests.failAll(error: MCPBridgeRuntimeError.closed) + pendingRequests.failAll(error: MCPRuntimeError.closed) closeCompletionTask?.cancel() for task in deferredProgressTasks { task.cancel() } for waiter in closeWaiters { waiter.resume() } @@ -554,20 +554,20 @@ package actor InitializedMCPClientSession { private extension InitializedMCPClientSession { static func runtimeError(from error: any Error) -> any Error { - if let error = error as? MCPBridgeRuntimeError { return error } + if let error = error as? MCPRuntimeError { return error } if let error = error as? MCPClientSessionFailure { return error } if let failure = error as? MCPTransportFailure { switch failure { case .sessionExpired(let sessionID, _): - return MCPBridgeRuntimeError.transportUnavailable( + return MCPRuntimeError.transportUnavailable( "Streamable HTTP session expired: \(sessionID)" ) case .deliveryUnknown(let reason), .unavailable(let reason): - return MCPBridgeRuntimeError.transportUnavailable(reason) + return MCPRuntimeError.transportUnavailable(reason) } } if error is CancellationError { return error } - return MCPBridgeRuntimeError.transportUnavailable(errorDescription(error)) + return MCPRuntimeError.transportUnavailable(errorDescription(error)) } static func errorDescription(_ error: any Error) -> String { @@ -579,7 +579,7 @@ private extension InitializedMCPClientSession { static func requiresCancellationNotification(_ error: any Error) -> Bool { if error is CancellationError { return true } - guard let runtimeError = error as? MCPBridgeRuntimeError else { return false } + guard let runtimeError = error as? MCPRuntimeError else { return false } if case .requestTimedOut = runtimeError { return true } return false } @@ -591,7 +591,7 @@ private extension InitializedMCPClientSession { ) async throws -> T { guard let deadline else { return try await operation() } guard deadline.hasExpired == false else { - throw MCPBridgeRuntimeError.requestTimedOut(method: method) + throw MCPRuntimeError.requestTimedOut(method: method) } let clock = configuration.clock return try await withThrowingTaskGroup(of: T.self) { group in @@ -599,7 +599,7 @@ private extension InitializedMCPClientSession { group.addTask { await clock.sleep(deadline.remainingDuration()) try Task.checkCancellation() - throw MCPBridgeRuntimeError.requestTimedOut(method: method) + throw MCPRuntimeError.requestTimedOut(method: method) } let result = try await group.next()! group.cancelAll() @@ -608,7 +608,7 @@ private extension InitializedMCPClientSession { } func ensureOpen() throws { - if isClosed { throw MCPBridgeRuntimeError.closed } + if isClosed { throw MCPRuntimeError.closed } } func handle(_ event: MCPClientSessionEvent) async { @@ -617,7 +617,7 @@ private extension InitializedMCPClientSession { await handleMessage(envelope) case .connectionState(let snapshot): if case .closed = snapshot.phase { - pendingRequests.failAll(error: MCPBridgeRuntimeError.closed) + pendingRequests.failAll(error: MCPRuntimeError.closed) } else if case .unavailable(let error) = snapshot.phase { pendingRequests.failAll(error: error.sessionError) } @@ -686,7 +686,7 @@ private extension InitializedMCPClientSession { return .object(["_meta": .object(["progressToken": .string(token)])]) } guard case .object(var object) = params else { - throw MCPBridgeRuntimeError.invalidRequest("progress requests require object params") + throw MCPRuntimeError.invalidRequest("progress requests require object params") } var meta: [String: JSONValue] if case .object(let existingMeta) = object["_meta"] { meta = existingMeta } else { meta = [:] } @@ -698,7 +698,7 @@ private extension InitializedMCPClientSession { func parseJSONObject(_ data: Data) throws -> [String: JSONValue] { let raw = try JSONRPC.Wire.object(fromData: data) guard let value = JSONValue(any: raw), case .object(let object) = value else { - throw MCPBridgeRuntimeError.invalidResponse("JSON-RPC message is not an object") + throw MCPRuntimeError.invalidResponse("JSON-RPC message is not an object") } return object } @@ -710,7 +710,7 @@ private extension InitializedMCPClientSession { } } - func parseServerError(_ value: JSONValue) -> MCPBridgeRuntimeError { + func parseServerError(_ value: JSONValue) -> MCPRuntimeError { guard case .object(let object) = value else { return .invalidResponse("JSON-RPC error is not an object") } diff --git a/Sources/XcodeMCPKit/Internal/ClientRuntime/MCPClientSessionAuthority.swift b/Sources/XcodeMCPKit/Internal/ClientRuntime/MCPClientSessionAuthority.swift index 61d03728..fc474856 100644 --- a/Sources/XcodeMCPKit/Internal/ClientRuntime/MCPClientSessionAuthority.swift +++ b/Sources/XcodeMCPKit/Internal/ClientRuntime/MCPClientSessionAuthority.swift @@ -26,10 +26,10 @@ package struct MCPClientEnvelope: Sendable { do { raw = try JSONSerialization.jsonObject(with: data) } catch { - throw MCPBridgeRuntimeError.invalidRequest("invalid JSON-RPC message: \(error.localizedDescription)") + throw MCPRuntimeError.invalidRequest("invalid JSON-RPC message: \(error.localizedDescription)") } guard let object = raw as? [String: Any] else { - throw MCPBridgeRuntimeError.invalidRequest("JSON-RPC message must be one object") + throw MCPRuntimeError.invalidRequest("JSON-RPC message must be one object") } let method = object["method"] as? String let id = object["id"].flatMap(JSONRPC.ID.init(any:)) @@ -40,7 +40,7 @@ package struct MCPClientEnvelope: Sendable { } else if let id { kind = .response(id: id) } else { - throw MCPBridgeRuntimeError.invalidRequest("JSON-RPC message has neither method nor id") + throw MCPRuntimeError.invalidRequest("JSON-RPC message has neither method nor id") } self.data = data } @@ -232,7 +232,7 @@ private final class MCPConnectionCommandIngress: Sendable { func admit() throws -> (id: UUID, admission: MCPConnectionOperationAdmission) { try state.withLock { state in - guard state.isAccepting else { throw MCPBridgeRuntimeError.closed } + guard state.isAccepting else { throw MCPRuntimeError.closed } let id = UUID() let admission = MCPConnectionOperationAdmission() state.operations[id] = admission @@ -460,7 +460,7 @@ package actor MCPClientSessionAuthority { throw failure } try await joinRecovery(failedConnection: connection.id, deadline: operation.deadline) - guard let replacement = current else { throw MCPBridgeRuntimeError.closed } + guard let replacement = current else { throw MCPRuntimeError.closed } do { try await sendOnce(operation.envelope, on: replacement, deadline: operation.deadline) } catch let secondFailure as MCPTransportFailure { @@ -475,7 +475,7 @@ package actor MCPClientSessionAuthority { } package func reconnect(deadline: Deadline?) async throws { - if isClosed { throw MCPBridgeRuntimeError.closed } + if isClosed { throw MCPRuntimeError.closed } try await joinRecovery(failedConnection: current?.id, deadline: deadline, force: true) } @@ -526,7 +526,7 @@ package actor MCPClientSessionAuthority { interruptedRecovery?.attempt.cancel() interruptedRecovery?.deadline.cancel() for waiter in interruptedRecovery?.waiters.values.map({ $0 }) ?? [] { - waiter.finish(throwing: MCPBridgeRuntimeError.closed) + waiter.finish(throwing: MCPRuntimeError.closed) } let cleanups = Array(recoveryCleanups.values) recoveryCleanups.removeAll() @@ -535,7 +535,7 @@ package actor MCPClientSessionAuthority { current = nil currentHeaders = MCPConnectionHeaders() for continuation in hiddenResponses.values { - continuation.finish(throwing: MCPBridgeRuntimeError.closed) + continuation.finish(throwing: MCPRuntimeError.closed) } hiddenResponses.removeAll() let cancellationTasks = Array(cancellationNotificationTasks.values) @@ -562,7 +562,7 @@ package actor MCPClientSessionAuthority { current?.cancel() for task in cancellationNotificationTasks.values { task.cancel() } for continuation in hiddenResponses.values { - continuation.finish(throwing: MCPBridgeRuntimeError.closed) + continuation.finish(throwing: MCPRuntimeError.closed) } subscribers.finish() eventContinuation.finish() @@ -630,7 +630,7 @@ private extension MCPClientSessionAuthority { try await joinRecovery(failedConnection: nil, deadline: deadline) } guard let current else { - throw MCPBridgeRuntimeError.transportUnavailable("MCP connection is unavailable") + throw MCPRuntimeError.transportUnavailable("MCP connection is unavailable") } return current } @@ -677,7 +677,7 @@ private extension MCPClientSessionAuthority { try await Self.awaitConnectionCommand(sendTask) } catch let failure as MCPTransportFailure { throw failure - } catch let error as MCPBridgeRuntimeError { + } catch let error as MCPRuntimeError { throw error } catch is CancellationError { throw CancellationError() @@ -751,7 +751,7 @@ private extension MCPClientSessionAuthority { return .response(response) } try Task.checkCancellation() - throw MCPBridgeRuntimeError.transportUnavailable( + throw MCPRuntimeError.transportUnavailable( "connection closed during initialize" ) } @@ -764,7 +764,7 @@ private extension MCPClientSessionAuthority { return response } } - throw MCPBridgeRuntimeError.transportUnavailable( + throw MCPRuntimeError.transportUnavailable( "connection closed during initialize" ) } @@ -804,7 +804,7 @@ private extension MCPClientSessionAuthority { // Another caller already replaced the connection that failed. return } - if isClosed { throw MCPBridgeRuntimeError.closed } + if isClosed { throw MCPRuntimeError.closed } try checkDeadline(deadline, method: "session recovery") let recoveryID = recovery?.id ?? startRecovery() let waiterID = UUID() @@ -815,9 +815,9 @@ private extension MCPClientSessionAuthority { try await raceDeadline(deadline, method: "session recovery") { for try await _ in pair.stream { return } try Task.checkCancellation() - throw MCPBridgeRuntimeError.transportUnavailable("session recovery ended without a result") + throw MCPRuntimeError.transportUnavailable("session recovery ended without a result") } - } catch let error as MCPBridgeRuntimeError { + } catch let error as MCPRuntimeError { if case .requestTimedOut = error { throw error } throw MCPClientSessionFailure.sessionRecoveryFailed(error.localizedDescription) } catch let failure as MCPClientSessionFailure { @@ -998,25 +998,25 @@ private extension MCPClientSessionAuthority { if let error = object["error"] as? [String: Any] { let code = (error["code"] as? NSNumber)?.intValue ?? 0 let message = error["message"] as? String ?? "MCP server error" - throw MCPBridgeRuntimeError.serverError( + throw MCPRuntimeError.serverError( code: code, message: message, data: error["data"].flatMap(JSONValue.init(any:)) ) } else if object["error"] != nil { - throw MCPBridgeRuntimeError.invalidResponse("initialize error is not an object") + throw MCPRuntimeError.invalidResponse("initialize error is not an object") } guard let result = object["result"] as? [String: Any] else { - throw MCPBridgeRuntimeError.invalidResponse("initialize result is not an object") + throw MCPRuntimeError.invalidResponse("initialize result is not an object") } guard let protocolVersion = result["protocolVersion"] as? String, protocolVersion.isEmpty == false else { - throw MCPBridgeRuntimeError.invalidResponse( + throw MCPRuntimeError.invalidResponse( "initialize result is missing protocolVersion" ) } guard MCPProtocolVersion.isSupported(protocolVersion) else { - throw MCPBridgeRuntimeError.invalidResponse( + throw MCPRuntimeError.invalidResponse( "initialize result has unsupported protocolVersion \(protocolVersion)" ) } @@ -1032,7 +1032,7 @@ private extension MCPClientSessionAuthority { } func ensureOpen() throws { - if isClosed { throw MCPBridgeRuntimeError.closed } + if isClosed { throw MCPRuntimeError.closed } if case .unavailable(let error) = snapshot.phase { throw error.sessionError } @@ -1040,7 +1040,7 @@ private extension MCPClientSessionAuthority { func checkDeadline(_ deadline: Deadline?, method: String) throws { if deadline?.hasExpired == true { - throw MCPBridgeRuntimeError.requestTimedOut(method: method) + throw MCPRuntimeError.requestTimedOut(method: method) } } @@ -1057,7 +1057,7 @@ private extension MCPClientSessionAuthority { group.addTask { await clock.sleep(deadline.remainingDuration()) try Task.checkCancellation() - throw MCPBridgeRuntimeError.requestTimedOut(method: method) + throw MCPRuntimeError.requestTimedOut(method: method) } let result = try await group.next()! group.cancelAll() @@ -1083,9 +1083,9 @@ extension XcodeMCPError { case .sessionRecoveryFailed(let reason): MCPClientSessionFailure.sessionRecoveryFailed(reason) case .transportUnavailable(let reason): - MCPBridgeRuntimeError.transportUnavailable(reason) + MCPRuntimeError.transportUnavailable(reason) case .invalidResponse(let reason): - MCPBridgeRuntimeError.invalidResponse(reason) + MCPRuntimeError.invalidResponse(reason) case .closed, .invalidRequest, .requestTimedOut, .serverError: self } diff --git a/Sources/XcodeMCPKit/Internal/ClientRuntime/StreamableHTTPMCPClient.swift b/Sources/XcodeMCPKit/Internal/ClientRuntime/StreamableHTTPMCPClient.swift index c9d88e8c..26dc188e 100644 --- a/Sources/XcodeMCPKit/Internal/ClientRuntime/StreamableHTTPMCPClient.swift +++ b/Sources/XcodeMCPKit/Internal/ClientRuntime/StreamableHTTPMCPClient.swift @@ -81,7 +81,7 @@ package final class StreamableHTTPMCPClient: Sendable { package static func validateEndpoint(_ endpoint: URL) throws { guard let scheme = endpoint.scheme?.lowercased(), scheme == "http" || scheme == "https" else { - throw MCPBridgeRuntimeError.invalidRequest( + throw MCPRuntimeError.invalidRequest( "Streamable HTTP endpoint must use http or https: \(endpoint.absoluteString)" ) } @@ -105,7 +105,7 @@ package final class StreamableHTTPMCPClient: Sendable { ) let (responseBytes, response) = try await urlSession.bytes(for: request) guard let httpResponse = response as? HTTPURLResponse else { - throw MCPBridgeRuntimeError.transportUnavailable("Streamable HTTP response was not HTTP") + throw MCPRuntimeError.transportUnavailable("Streamable HTTP response was not HTTP") } guard (200..<300).contains(httpResponse.statusCode) else { if httpResponse.statusCode == 404, let sessionID = headers.sessionID { @@ -161,7 +161,7 @@ package final class StreamableHTTPMCPClient: Sendable { ) let (bytes, response) = try await urlSession.bytes(for: request) guard let httpResponse = response as? HTTPURLResponse else { - throw MCPBridgeRuntimeError.transportUnavailable( + throw MCPRuntimeError.transportUnavailable( "Streamable HTTP event stream response was not HTTP" ) } @@ -172,7 +172,7 @@ package final class StreamableHTTPMCPClient: Sendable { } if Self.isTerminalEventStreamStatus(httpResponse.statusCode) { return } _ = try? await Self.collect(bytes) - throw MCPBridgeRuntimeError.transportUnavailable( + throw MCPRuntimeError.transportUnavailable( "Streamable HTTP event stream failed with status \(httpResponse.statusCode)" ) } @@ -473,7 +473,7 @@ package actor StreamableHTTPMCPConnectionState { private var closeWaiters: [CheckedContinuation?, Never>] = [] package func ensureOpen() throws { - if closed { throw MCPBridgeRuntimeError.closed } + if closed { throw MCPRuntimeError.closed } } package func reserveEventStreamStart() -> Bool { diff --git a/Sources/XcodeMCPKit/Internal/ClientRuntime/StreamableHTTPXcodeMCPTransport.swift b/Sources/XcodeMCPKit/Internal/ClientRuntime/StreamableHTTPXcodeMCPTransport.swift index 0371278a..f4c100ad 100644 --- a/Sources/XcodeMCPKit/Internal/ClientRuntime/StreamableHTTPXcodeMCPTransport.swift +++ b/Sources/XcodeMCPKit/Internal/ClientRuntime/StreamableHTTPXcodeMCPTransport.swift @@ -56,7 +56,7 @@ package final class StreamableHTTPXcodeMCPTransport: XcodeMCPTransport { discoveryResolver: StreamableHTTPDiscoveryResolver = .liveValue ) async throws -> StreamableHTTPXcodeMCPTransport { guard let endpoint = discoveryResolver.endpoint(from: discoveryFile) else { - throw MCPBridgeRuntimeError.transportUnavailable( + throw MCPRuntimeError.transportUnavailable( "Streamable HTTP discovery file is missing, stale, or invalid: \(discoveryFile.path)" ) } @@ -165,7 +165,7 @@ package final class StreamableHTTPXcodeMCPTransport: XcodeMCPTransport { streamContinuation.finish() } - private static func runtimeError(from error: StreamableHTTPMCPClientError) -> MCPBridgeRuntimeError { + private static func runtimeError(from error: StreamableHTTPMCPClientError) -> MCPRuntimeError { switch error { case .httpStatus(let statusCode, let body, _): return .httpStatus(code: statusCode, body: body) diff --git a/Sources/XcodeMCPKit/Internal/ClientRuntime/XcodeMCPTransport.swift b/Sources/XcodeMCPKit/Internal/ClientRuntime/XcodeMCPTransport.swift index 10ef2695..51c0e8b9 100644 --- a/Sources/XcodeMCPKit/Internal/ClientRuntime/XcodeMCPTransport.swift +++ b/Sources/XcodeMCPKit/Internal/ClientRuntime/XcodeMCPTransport.swift @@ -32,15 +32,15 @@ package protocol XcodeMCPTransport: Sendable { func close(headers: MCPConnectionHeaders) async } -package final class UpstreamProcessXcodeMCPTransport: XcodeMCPTransport { +package final class ProcessXcodeMCPTransport: XcodeMCPTransport { package nonisolated let events: AsyncStream - private let session: any UpstreamSession + private let session: any MCPProcessSession private let bridgeTask: Task - package static func start(config: UpstreamProcess.Config) async throws -> UpstreamProcessXcodeMCPTransport { - let session = try await UpstreamProcess(configuration: config).startSession() - return UpstreamProcessXcodeMCPTransport(session: session) + package static func start(config: MCPProcessLauncher.Config) async throws -> ProcessXcodeMCPTransport { + let session = try await MCPProcessLauncher(configuration: config).startSession() + return ProcessXcodeMCPTransport(session: session) } package static func start( @@ -48,9 +48,9 @@ package final class UpstreamProcessXcodeMCPTransport: XcodeMCPTransport { arguments: [String], environment: [String: String], maxQueuedWriteBytes: Int = 4 * 1024 * 1024 - ) async throws -> UpstreamProcessXcodeMCPTransport { + ) async throws -> ProcessXcodeMCPTransport { try await start( - config: UpstreamProcess.Config( + config: MCPProcessLauncher.Config( command: command, args: arguments, environment: environment, @@ -59,7 +59,7 @@ package final class UpstreamProcessXcodeMCPTransport: XcodeMCPTransport { ) } - private init(session: any UpstreamSession) { + private init(session: any MCPProcessSession) { self.session = session let sessionEvents = session.events let stream = AsyncStream.makeStream() @@ -100,7 +100,7 @@ package final class UpstreamProcessXcodeMCPTransport: XcodeMCPTransport { headers: MCPConnectionHeaders, deadline: Deadline? ) async throws { - // A local stdio bridge has no HTTP session headers. The typed boundary + // A local stdio process has no HTTP session headers. The typed boundary // remains explicit so adding another transport input cannot silently // fall back to a legacy send path. _ = headers @@ -109,9 +109,9 @@ package final class UpstreamProcessXcodeMCPTransport: XcodeMCPTransport { case .accepted: return case .backpressure: - throw MCPBridgeRuntimeError.transportUnavailable("MCP process write queue is full") + throw MCPRuntimeError.transportUnavailable("MCP process write queue is full") case .unavailable(let reason): - throw MCPBridgeRuntimeError.transportUnavailable("MCP process is unavailable: \(reason)") + throw MCPRuntimeError.transportUnavailable("MCP process is unavailable: \(reason)") } } diff --git a/Sources/XcodeMCPKit/XcodeMCP.swift b/Sources/XcodeMCPKit/XcodeMCP.swift index dc36838f..15d2f004 100644 --- a/Sources/XcodeMCPKit/XcodeMCP.swift +++ b/Sources/XcodeMCPKit/XcodeMCP.swift @@ -195,7 +195,7 @@ public actor XcodeMCP { bundleURL: bundleURL, developerDirectoryURL: developerDirectoryURL ) - return try await UpstreamProcessXcodeMCPTransport.start( + return try await ProcessXcodeMCPTransport.start( command: invocation.command, arguments: invocation.arguments, environment: ProcessInfo.processInfo.environment @@ -203,7 +203,7 @@ public actor XcodeMCP { } case .process(let command, let arguments, let environment): recipe = MCPTransportRecipe { - try await UpstreamProcessXcodeMCPTransport.start( + try await ProcessXcodeMCPTransport.start( command: command, arguments: arguments, environment: environment @@ -469,7 +469,7 @@ private extension XcodeMCP { if error is CancellationError { return error } - guard let runtimeError = error as? MCPBridgeRuntimeError else { + guard let runtimeError = error as? MCPRuntimeError else { if let failure = error as? MCPTransportFailure { switch failure { case .sessionExpired(let sessionID, _): diff --git a/Sources/XcodeMCPKit/XcodeMCPError.swift b/Sources/XcodeMCPKit/XcodeMCPError.swift index 9fa70ef7..0c56a623 100644 --- a/Sources/XcodeMCPKit/XcodeMCPError.swift +++ b/Sources/XcodeMCPKit/XcodeMCPError.swift @@ -29,7 +29,7 @@ public enum XcodeMCPError: Error, Equatable, Sendable { /// includes one. case serverError(code: Int, message: String, data: MCPJSONValue?) - /// The underlying bridge process or transport was unavailable. + /// The underlying MCP process or transport was unavailable. /// /// The associated string describes the transport failure. case transportUnavailable(String) diff --git a/Sources/XcodeMCPProxyHTTP/HTTP/HTTPRoute.swift b/Sources/XcodeMCPProxyHTTP/HTTP/HTTPRoute.swift index 6b67ac02..9e2b9e4c 100644 --- a/Sources/XcodeMCPProxyHTTP/HTTP/HTTPRoute.swift +++ b/Sources/XcodeMCPProxyHTTP/HTTP/HTTPRoute.swift @@ -13,7 +13,7 @@ enum HTTPRoute { switch (method, path) { case (.GET, "/health"): .health - case (.GET, "/debug/upstreams"): + case (.GET, "/debug/hosts"): .debugSnapshot case (.POST, "/debug/reset"): .debugReset diff --git a/Sources/XcodeMCPProxyHTTP/HTTP/ProxyHTTPConfiguration.swift b/Sources/XcodeMCPProxyHTTP/HTTP/ProxyHTTPConfiguration.swift index 7ead4cc9..def57572 100644 --- a/Sources/XcodeMCPProxyHTTP/HTTP/ProxyHTTPConfiguration.swift +++ b/Sources/XcodeMCPProxyHTTP/HTTP/ProxyHTTPConfiguration.swift @@ -2,7 +2,7 @@ package struct ProxyHTTPConfiguration: Sendable { package let listenHost: String package let listenPort: Int package let maxBodyBytes: Int - /// Serves `/debug/upstreams` and `/debug/reset` on a loopback listener. + /// Serves `/debug/hosts` and `/debug/reset` on a loopback listener. package let enablesDebugEndpoints: Bool package init(listenHost: String, listenPort: Int, maxBodyBytes: Int, enablesDebugEndpoints: Bool = false) { diff --git a/Sources/XcodeMCPProxyKit/Internal/CLI/Server/ProxyServerCommand.swift b/Sources/XcodeMCPProxyKit/Internal/CLI/Server/ProxyServerCommand.swift index 8cef195b..8bc7a391 100644 --- a/Sources/XcodeMCPProxyKit/Internal/CLI/Server/ProxyServerCommand.swift +++ b/Sources/XcodeMCPProxyKit/Internal/CLI/Server/ProxyServerCommand.swift @@ -46,7 +46,7 @@ package struct ProxyServerCommand: ParsableCommand { @Flag(help: "Automatically allow Xcode MCP connections for all agents, including external clients. Requires Accessibility permission.") var autoApprove = false - @Flag(help: "Serve /debug/upstreams and /debug/reset on a loopback listener.") + @Flag(help: "Serve /debug/hosts and /debug/reset on a loopback listener.") var debugEndpoints = false @Flag(help: "Terminate an existing proxy server on the listen port before starting.") diff --git a/Sources/XcodeMCPProxyKit/XcodeMCPProxyServer.swift b/Sources/XcodeMCPProxyKit/XcodeMCPProxyServer.swift index 1ef0dfc0..7930d0d7 100644 --- a/Sources/XcodeMCPProxyKit/XcodeMCPProxyServer.swift +++ b/Sources/XcodeMCPProxyKit/XcodeMCPProxyServer.swift @@ -86,7 +86,7 @@ public struct XcodeMCPProxyServerConfiguration: Equatable, Sendable { /// Whether to fetch native tool catalogs during startup. public var prewarmToolsList: Bool - /// Whether to serve `/debug/upstreams` and `/debug/reset`. They are served only on a loopback + /// Whether to serve `/debug/hosts` and `/debug/reset`. They are served only on a loopback /// listener. Defaults to `false`. public var enablesDebugEndpoints: Bool diff --git a/Sources/XcodeMCPProxyRuntime/Broker/NativeHostBroker.swift b/Sources/XcodeMCPProxyRuntime/Broker/NativeHostBroker.swift index 25d3157c..7738df35 100644 --- a/Sources/XcodeMCPProxyRuntime/Broker/NativeHostBroker.swift +++ b/Sources/XcodeMCPProxyRuntime/Broker/NativeHostBroker.swift @@ -6,7 +6,7 @@ import XcodeMCPProxyRuntimeContract import XcodeMCPWire package final class NativeHostBroker: ProxyRuntimeServing, Sendable { - typealias SessionFactory = @Sendable (NativeHostRuntime.Configuration) -> any UpstreamSessionFactory + typealias SessionFactory = @Sendable (NativeHostRuntime.Configuration) -> any MCPProcessSessionFactory private struct State: Sendable { var hosts: [String: NativeBrokerHost] = [:] @@ -29,7 +29,7 @@ package final class NativeHostBroker: ProxyRuntimeServing, Sendable { private let configuration: ProxyRuntimeConfiguration private let inventory: XcodeHostInventory private let sessionFactory: SessionFactory - private let guiSessionFactory: any UpstreamSessionFactory + private let guiSessionFactory: any MCPProcessSessionFactory private let clock: ClockClient private let logger: Logger static let defaultHostIdentifier = "host-default" @@ -76,7 +76,7 @@ package final class NativeHostBroker: ProxyRuntimeServing, Sendable { init(configuration: ProxyRuntimeConfiguration, inventory: XcodeHostInventory, clock: ClockClient = .liveValue, logger: Logger = ProxyLogging.make("broker"), - guiSessionFactory: (any UpstreamSessionFactory)? = nil, + guiSessionFactory: (any MCPProcessSessionFactory)? = nil, sessionFactory: @escaping SessionFactory) throws { self.configuration = configuration self.inventory = inventory @@ -260,7 +260,7 @@ package final class NativeHostBroker: ProxyRuntimeServing, Sendable { guard let admission else { return AnsweredCall(reply: cancelled) } let key = UUID() let admittedMessage = message - let timeoutReply = NativeBrokerReply.error(id: requestID, code: -32000, message: "upstream timeout").clientReply + let timeoutReply = NativeBrokerReply.error(id: requestID, code: -32000, message: "host timeout").clientReply let operation = NativeHostBrokerOperation(cancelledReply: cancelled, requestIDKey: requestID?.key, deadline: deadline, clock: clock, timeoutReply: timeoutReply) { [self] in let reply = await process(admittedMessage, in: session, admission: admission) @@ -353,7 +353,7 @@ package final class NativeHostBroker: ProxyRuntimeServing, Sendable { return try Self.externalReply(error.reply, requestID: id) } catch { logger.notice("A host's error response is invalid", metadata: ["error": "\(error)"]) - return .invalidUpstreamResponse(id: id) + return .invalidHostResponse(id: id) } } catch is CancellationError { return .error(id: id, code: -32800, message: "request cancelled") @@ -396,11 +396,11 @@ package final class NativeHostBroker: ProxyRuntimeServing, Sendable { catch let error as NativeHostConnectionError { switch error { case .expired: throw Self.expiredReference() - case .unavailable: throw Self.replyError(error, code: -32001, message: "upstream unavailable") - case .overloaded: throw Self.replyError(error, code: -32002, message: "upstream overloaded") - case .timedOut: throw Self.replyError(error, code: -32000, message: "upstream timeout") + case .unavailable: throw Self.replyError(error, code: -32001, message: "host unavailable") + case .overloaded: throw Self.replyError(error, code: -32002, message: "host overloaded") + case .timedOut: throw Self.replyError(error, code: -32000, message: "host timeout") case .invalidResponse: - throw NativeHostBrokerReplyError(description: error.description, reply: .invalidUpstreamResponse()) + throw NativeHostBrokerReplyError(description: error.description, reply: .invalidHostResponse()) case .rejected(let response): throw NativeHostBrokerReplyError(description: error.description, reply: .response(response)) } @@ -1048,7 +1048,7 @@ private extension NativeHostBroker { } } catch is NativeBrokerTurns.Full { // The host's queue would refuse these requests too. - throw Self.replyError(.overloaded, code: -32002, message: "upstream overloaded") + throw Self.replyError(.overloaded, code: -32002, message: "host overloaded") } } else { sent = try Self.takingSelection(from: await send(forwarded, to: host, session: session, generation: generation)) diff --git a/Sources/XcodeMCPProxyRuntime/Broker/NativeHostBrokerTools.swift b/Sources/XcodeMCPProxyRuntime/Broker/NativeHostBrokerTools.swift index 2de7a478..da403f9a 100644 --- a/Sources/XcodeMCPProxyRuntime/Broker/NativeHostBrokerTools.swift +++ b/Sources/XcodeMCPProxyRuntime/Broker/NativeHostBrokerTools.swift @@ -13,8 +13,8 @@ enum NativeBrokerReply: Sendable { case accepted /// The error for a host response that is not valid JSON-RPC for its request. - static func invalidUpstreamResponse(id: JSONRPC.ID? = nil) -> Self { - .error(id: id, code: -32603, message: "invalid upstream response") + static func invalidHostResponse(id: JSONRPC.ID? = nil) -> Self { + .error(id: id, code: -32603, message: "invalid host response") } /// The message HTTP sends to the client. diff --git a/Sources/XcodeMCPProxyRuntime/Host/UpstreamStderrLogFilter.swift b/Sources/XcodeMCPProxyRuntime/Host/HostStderrLogFilter.swift similarity index 89% rename from Sources/XcodeMCPProxyRuntime/Host/UpstreamStderrLogFilter.swift rename to Sources/XcodeMCPProxyRuntime/Host/HostStderrLogFilter.swift index 681f97fa..bd37199c 100644 --- a/Sources/XcodeMCPProxyRuntime/Host/UpstreamStderrLogFilter.swift +++ b/Sources/XcodeMCPProxyRuntime/Host/HostStderrLogFilter.swift @@ -3,7 +3,7 @@ import Foundation import Logging import NIOConcurrencyHelpers -enum UpstreamStderrLogFilter { +enum HostStderrLogFilter { static func level(for message: String) -> Logger.Level { let defaultLevel: Logger.Level = NativeHostRuntime.diagnostic(in: message) == nil ? .debug : .error guard message.hasPrefix("["), @@ -17,12 +17,12 @@ enum UpstreamStderrLogFilter { } } -struct UpstreamStderrLogDecision: Sendable { +struct HostStderrLogDecision: Sendable { let shouldLog: Bool let suppressedDuplicateCount: Int } -final class UpstreamStderrLogLimiter: Sendable { +final class HostStderrLogLimiter: Sendable { private struct Record: Sendable { var lastLoggedUptimeNs: UInt64 var suppressedDuplicateCount: Int @@ -43,7 +43,7 @@ final class UpstreamStderrLogLimiter: Sendable { upstreamIndex: Int, message: String, nowUptimeNs: UInt64 - ) -> UpstreamStderrLogDecision { + ) -> HostStderrLogDecision { let key = "\(upstreamIndex)|\(message)" return state.withLockedValue { state in guard var record = state.recordsByKey[key] else { @@ -51,7 +51,7 @@ final class UpstreamStderrLogLimiter: Sendable { lastLoggedUptimeNs: nowUptimeNs, suppressedDuplicateCount: 0 ) - return UpstreamStderrLogDecision( + return HostStderrLogDecision( shouldLog: true, suppressedDuplicateCount: 0 ) @@ -60,7 +60,7 @@ final class UpstreamStderrLogLimiter: Sendable { guard nowUptimeNs &- record.lastLoggedUptimeNs >= duplicateLogIntervalNanoseconds else { record.suppressedDuplicateCount += 1 state.recordsByKey[key] = record - return UpstreamStderrLogDecision( + return HostStderrLogDecision( shouldLog: false, suppressedDuplicateCount: record.suppressedDuplicateCount ) @@ -70,7 +70,7 @@ final class UpstreamStderrLogLimiter: Sendable { record.lastLoggedUptimeNs = nowUptimeNs record.suppressedDuplicateCount = 0 state.recordsByKey[key] = record - return UpstreamStderrLogDecision( + return HostStderrLogDecision( shouldLog: true, suppressedDuplicateCount: suppressedCount ) diff --git a/Sources/XcodeMCPProxyRuntime/Host/NativeHostConnection.swift b/Sources/XcodeMCPProxyRuntime/Host/NativeHostConnection.swift index ccb4c39a..85445698 100644 --- a/Sources/XcodeMCPProxyRuntime/Host/NativeHostConnection.swift +++ b/Sources/XcodeMCPProxyRuntime/Host/NativeHostConnection.swift @@ -21,11 +21,11 @@ enum NativeHostConnectionError: Error, CustomStringConvertible { var description: String { switch self { - case .unavailable(let reason): "upstream unavailable: \(reason)" - case .overloaded: "upstream overloaded" + case .unavailable(let reason): "host unavailable: \(reason)" + case .overloaded: "host overloaded" case .expired: "This reference belongs to an earlier Xcode connection. Open or list workspaces again, or start a new session." - case .timedOut: "upstream timeout" - case .invalidResponse: "invalid upstream response" + case .timedOut: "host timeout" + case .invalidResponse: "invalid host response" case .rejected(let response): "Native request failed: \(String(decoding: response, as: UTF8.self))" } } @@ -52,10 +52,10 @@ actor NativeHostConnection { private final class Process: Sendable { let generation: UInt64 - let session: any UpstreamSession + let session: any MCPProcessSession let reader = NIOLockedValueBox?>(nil) - init(generation: UInt64, session: any UpstreamSession) { + init(generation: UInt64, session: any MCPProcessSession) { self.generation = generation self.session = session } @@ -63,7 +63,7 @@ actor NativeHostConnection { private struct ProgressTokenMapping { let clientToken: JSONValue - let upstreamToken: String + let hostToken: String } private struct Pending { @@ -81,18 +81,18 @@ actor NativeHostConnection { let task: Task } - private let factory: any UpstreamSessionFactory + private let factory: any MCPProcessSessionFactory private let handshake: JSONValue private let handshakeTimeout: Duration? private let catalogTimeout: Duration? private let prewarmsCatalog: Bool private let clock: ClockClient private let logger: Logger - private let stderrLimiter = UpstreamStderrLogLimiter() + private let stderrLimiter = HostStderrLogLimiter() private let onEvent: @Sendable (Event) -> Void nonisolated let status = NIOLockedValueBox(Status()) /// The process session that deinitialization cancels, and whether it already did. - private nonisolated let live = NIOLockedValueBox<(session: (any UpstreamSession)?, cancelled: Bool)>((nil, false)) + private nonisolated let live = NIOLockedValueBox<(session: (any MCPProcessSession)?, cancelled: Bool)>((nil, false)) /// A requested stop that has not finished; requests wait for it and then start a new process. private nonisolated let retirement = NIOLockedValueBox?>(nil) @@ -109,7 +109,7 @@ actor NativeHostConnection { private var catalogEpoch: UInt64 = 0 private var endings: [UInt64: Task] = [:] - init(factory: any UpstreamSessionFactory, handshake: JSONValue, handshakeTimeout: Duration?, + init(factory: any MCPProcessSessionFactory, handshake: JSONValue, handshakeTimeout: Duration?, catalogTimeout: Duration?, prewarmsCatalog: Bool, clock: ClockClient, logger: Logger, onEvent: @escaping @Sendable (Event) -> Void) { self.factory = factory @@ -230,7 +230,7 @@ actor NativeHostConnection { private func launch(generation: UInt64) async throws -> Process { defer { if starting?.generation == generation { starting = nil } } - let session: any UpstreamSession + let session: any MCPProcessSession do { session = try await factory.startSession() } catch { updateStatus { if $0.phase == .starting { $0.phase = .idle } } @@ -329,9 +329,9 @@ actor NativeHostConnection { var progress: ProgressTokenMapping? if case .object(var parameters)? = object["params"], case .object(var meta)? = parameters["_meta"], let token = meta["progressToken"] { - let upstream = "progress-\(process.generation)-\(id)" - progress = ProgressTokenMapping(clientToken: token, upstreamToken: upstream) - meta["progressToken"] = .string(upstream) + let hostToken = "progress-\(process.generation)-\(id)" + progress = ProgressTokenMapping(clientToken: token, hostToken: hostToken) + meta["progressToken"] = .string(hostToken) parameters["_meta"] = .object(meta) object["params"] = .object(parameters) } @@ -465,7 +465,7 @@ actor NativeHostConnection { // MARK: - Host messages - private func receive(_ event: Upstream.Event, from process: Process) async { + private func receive(_ event: MCPProcess.Event, from process: Process) async { guard self.process === process else { return } switch event { case .message(let data): @@ -507,7 +507,7 @@ actor NativeHostConnection { case .notification("notifications/progress"): guard let parameters = object["params"] as? [String: Any], let token = parameters["progressToken"] as? String, - let entry = pending.values.first(where: { $0.progress?.upstreamToken == token }), + let entry = pending.values.first(where: { $0.progress?.hostToken == token }), let progress = entry.progress else { return } var rewritten = object var fields = parameters @@ -535,7 +535,7 @@ actor NativeHostConnection { } private func log(stderr line: String) { - let level = UpstreamStderrLogFilter.level(for: line) + let level = HostStderrLogFilter.level(for: line) guard level >= logger.logLevel else { return } let decision = stderrLimiter.decision(upstreamIndex: 0, message: line, nowUptimeNs: clock.uptimeNanoseconds()) guard decision.shouldLog else { return } diff --git a/Sources/XcodeMCPProxyRuntime/Host/NativeHostRuntime.swift b/Sources/XcodeMCPProxyRuntime/Host/NativeHostRuntime.swift index 5c0dfcab..af905916 100644 --- a/Sources/XcodeMCPProxyRuntime/Host/NativeHostRuntime.swift +++ b/Sources/XcodeMCPProxyRuntime/Host/NativeHostRuntime.swift @@ -41,10 +41,10 @@ enum NativeHostRuntime { } } - static func makeDefaultUpstreamConfig( + static func makeDefaultProcessConfig( config: Configuration, baseEnvironment: [String: String] = ProcessInfo.processInfo.environment - ) throws -> UpstreamProcess.Config { + ) throws -> MCPProcessLauncher.Config { var environment = baseEnvironment environment.removeValue(forKey: "XCODE_PID") environment.removeValue(forKey: "MCP_XCODE_PID") @@ -57,7 +57,7 @@ enum NativeHostRuntime { environment: environment) if let developerDirectoryURL { environment["DEVELOPER_DIR"] = developerDirectoryURL.path } let messageLimit = maxQueuedWriteBytes(for: config) - return UpstreamProcess.Config( + return MCPProcessLauncher.Config( command: invocation.command, args: invocation.arguments + ["--gui-tool-schemas", "--max-message-bytes", String(messageLimit)], environment: environment, @@ -118,13 +118,13 @@ enum NativeHostRuntime { } /// Launches Apple's bridge lazily; ending it leaves the user's Xcode running. -struct GUIXcodeSessionFactory: UpstreamSessionFactory { +struct GUIXcodeSessionFactory: MCPProcessSessionFactory { let configuration: NativeHostRuntime.Configuration let environment: [String: String] - func startSession() async throws -> any UpstreamSession { + func startSession() async throws -> any MCPProcessSession { guard let developerDirectory = configuration.developerDirectoryURL else { - throw MCPBridgeRuntimeError.transportUnavailable("The GUI bridge requires an Xcode installation") + throw MCPRuntimeError.transportUnavailable("The GUI bridge requires an Xcode installation") } var environment = environment environment["DEVELOPER_DIR"] = developerDirectory.path @@ -138,12 +138,12 @@ struct GUIXcodeSessionFactory: UpstreamSessionFactory { }?.processIdentifier } guard let processID else { - throw MCPBridgeRuntimeError.transportUnavailable("Open \(applicationURL.path) before using the standard crash tools") + throw MCPRuntimeError.transportUnavailable("Open \(applicationURL.path) before using the standard crash tools") } // The native helper also advertises MCP. Never let Apple's bridge auto-select it. environment["MCP_XCODE_PID"] = String(processID) } - return try await UpstreamProcess(configuration: .init( + return try await MCPProcessLauncher(configuration: .init( command: developerDirectory.appendingPathComponent("usr/bin/mcpbridge").path, args: [], environment: environment, maxQueuedWriteBytes: NativeHostRuntime.maxQueuedWriteBytes(for: configuration), @@ -151,17 +151,17 @@ struct GUIXcodeSessionFactory: UpstreamSessionFactory { } } -struct NativeHostSessionFactory: UpstreamSessionFactory { +struct NativeHostSessionFactory: MCPProcessSessionFactory { let configuration: NativeHostRuntime.Configuration let environment: [String: String] - func processConfiguration(environment: [String: String]) throws -> UpstreamProcess.Config { - try NativeHostRuntime.makeDefaultUpstreamConfig( + func processConfiguration(environment: [String: String]) throws -> MCPProcessLauncher.Config { + try NativeHostRuntime.makeDefaultProcessConfig( config: configuration, baseEnvironment: environment) } - func startSession() async throws -> any UpstreamSession { + func startSession() async throws -> any MCPProcessSession { let environment = try await NativeHostRuntime.buildServiceEnvironment(baseEnvironment: environment) - return try await UpstreamProcess(configuration: processConfiguration(environment: environment)).startSession() + return try await MCPProcessLauncher(configuration: processConfiguration(environment: environment)).startSession() } } diff --git a/Sources/XcodeMCPProxyRuntime/Support/ProxyLogging.swift b/Sources/XcodeMCPProxyRuntime/Support/ProxyLogging.swift index 10f552a8..c6da808b 100644 --- a/Sources/XcodeMCPProxyRuntime/Support/ProxyLogging.swift +++ b/Sources/XcodeMCPProxyRuntime/Support/ProxyLogging.swift @@ -71,10 +71,10 @@ enum LogLevelParser { } } -extension Upstream.Diagnostics { +extension MCPProcess.Diagnostics { /// Forwards a host process session's diagnostics to the server log. static var serverLog: Self { - let logger = Logger(label: "XcodeMCPRuntime.upstream") + let logger = Logger(label: "XcodeMCPRuntime.host") return Self { severity, message, metadata in let metadata = metadata.mapValues { Logger.MetadataValue.string($0) } switch severity { diff --git a/Tests/ProxyCLITests/ServerRunnerTests.swift b/Tests/ProxyCLITests/ServerRunnerTests.swift index 1ad9b54f..1176a194 100644 --- a/Tests/ProxyCLITests/ServerRunnerTests.swift +++ b/Tests/ProxyCLITests/ServerRunnerTests.swift @@ -64,7 +64,7 @@ struct ServerRunnerTests { #expect(exitCode == 0) let configuration = try #require(fakeServer.recordedConfig()) let runtimeConfiguration = try configuration.runtimeConfiguration() - let child = try NativeHostRuntime.makeDefaultUpstreamConfig( + let child = try NativeHostRuntime.makeDefaultProcessConfig( config: NativeHostRuntime.Configuration( nativeHostBundleURL: runtimeConfiguration.nativeHostBundleURL, developerDirectoryURL: runtimeConfiguration.developerDirectoryURL, diff --git a/Tests/ProxyIntegrationTests/HTTPConcurrencyTests.swift b/Tests/ProxyIntegrationTests/HTTPConcurrencyTests.swift index 3f1127cd..d83e0b56 100644 --- a/Tests/ProxyIntegrationTests/HTTPConcurrencyTests.swift +++ b/Tests/ProxyIntegrationTests/HTTPConcurrencyTests.swift @@ -172,13 +172,13 @@ struct HTTPConcurrencyTests { let calls = host.requests("tools/call") let reportingCall = try #require(calls.first) guard case .object(let params)? = reportingCall["params"], case .object(let meta)? = params["_meta"], - let upstreamToken = meta["progressToken"] else { + let hostToken = meta["progressToken"] else { Issue.record("the host request has no progress token") return } host.emit(.object(["jsonrpc": .string("2.0"), "method": .string("notifications/progress"), - "params": .object(["progressToken": upstreamToken, "progress": .number(.int(1)), + "params": .object(["progressToken": hostToken, "progress": .number(.int(1)), "message": .string("halfway")])])) let result = JSONValue.object(["content": .array([])]) for call in calls { @@ -428,7 +428,7 @@ struct HTTPConcurrencyTests { let (firstResponse, firstObject) = try await first #expect(firstResponse.statusCode == 200) #expect((firstObject["id"] as? NSNumber)?.intValue == 700) - #expect((firstObject["error"] as? [String: Any])?["message"] as? String == "upstream timeout") + #expect((firstObject["error"] as? [String: Any])?["message"] as? String == "host timeout") let host = try #require(runtime.host) let hostRequestIDs = host.requests("tools/call").compactMap { $0["id"] } diff --git a/Tests/ProxyIntegrationTests/HTTPHandlerTests.swift b/Tests/ProxyIntegrationTests/HTTPHandlerTests.swift index d1235f8e..f67a996d 100644 --- a/Tests/ProxyIntegrationTests/HTTPHandlerTests.swift +++ b/Tests/ProxyIntegrationTests/HTTPHandlerTests.swift @@ -29,14 +29,14 @@ struct HTTPHandlerTests { #expect(response.body == "ok") } - @Test func httpDebugUpstreamsReturnsSnapshot() async throws { + @Test func httpDebugHostsReturnsSnapshot() async throws { var config = makeHTTPConfig() config.enablesDebugEndpoints = true let channel = makeHTTPTestChannel() let runtime = try HTTPTestRuntime(config: config) try await addHTTPHandler(to: channel, config: config, runtime: runtime) - let head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/debug/upstreams") + let head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/debug/hosts") try await channel.writeInbound(HTTPServerRequestPart.head(head)) try await channel.writeInbound(HTTPServerRequestPart.end(nil)) @@ -55,7 +55,7 @@ struct HTTPHandlerTests { #expect((hosts.first?["inFlightRequests"] as? NSNumber)?.intValue == 0) } - @Test func httpDebugUpstreamsReturnsNotFoundWhenListenerIsNotLoopback() async throws { + @Test func httpDebugHostsReturnsNotFoundWhenListenerIsNotLoopback() async throws { var config = makeHTTPConfig() config.listenHost = "0.0.0.0" config.enablesDebugEndpoints = true @@ -64,7 +64,7 @@ struct HTTPHandlerTests { let runtime = try HTTPTestRuntime(config: config) try await addHTTPHandler(to: channel, config: config, runtime: runtime) - let head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/debug/upstreams") + let head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/debug/hosts") try await channel.writeInbound(HTTPServerRequestPart.head(head)) try await channel.writeInbound(HTTPServerRequestPart.end(nil)) @@ -136,7 +136,7 @@ struct HTTPHandlerTests { #expect(response.body == "not found") } - @Test(arguments: [(HTTPMethod.GET, "/debug/upstreams?includeSensitive=1"), (.POST, "/debug/reset")]) + @Test(arguments: [(HTTPMethod.GET, "/debug/hosts?includeSensitive=1"), (.POST, "/debug/reset")]) func httpDebugEndpointsRequireTheOptIn(method: HTTPMethod, uri: String) async throws { let config = makeHTTPConfig() let channel = makeHTTPTestChannel() @@ -1110,7 +1110,7 @@ struct HTTPHandlerTests { ) let error = try #require(errorObject["error"] as? [String: Any]) #expect((error["code"] as? NSNumber)?.intValue == -32001) - #expect(error["message"] as? String == "upstream unavailable") + #expect(error["message"] as? String == "host unavailable") #expect( runtime.controlService.sessions.phase(of: ProxySessionID(rawValue: sessionID)) == .initialized(protocolVersion: MCP.ProtocolVersion.current) @@ -1301,7 +1301,7 @@ struct HTTPHandlerTests { } } - @Test func httpJSONArrayBodyIsRejectedBeforeUpstreamRouting() async throws { + @Test func httpJSONArrayBodyIsRejectedBeforeHostRouting() async throws { let config = makeHTTPConfig() let channel = makeHTTPTestChannel() let runtime = try HTTPTestRuntime(config: config) @@ -1342,7 +1342,7 @@ struct HTTPHandlerTests { #expect((object?["id"] as? NSNumber)?.intValue == 2001) let error = object?["error"] as? [String: Any] #expect((error?["code"] as? NSNumber)?.intValue == -32000) - #expect((error?["message"] as? String) == "upstream timeout") + #expect((error?["message"] as? String) == "host timeout") let heldID = try #require(host.requests("tools/call").first?["id"]) let cancellations = try await runtime.waitForHostMessages("notifications/cancelled") @@ -1353,7 +1353,7 @@ struct HTTPHandlerTests { #expect(params["requestId"] == heldID) } - @Test func httpMalformedJSONReturnsParseErrorBeforeUpstreamUnavailable() async throws { + @Test func httpMalformedJSONReturnsParseErrorBeforeHostUnavailable() async throws { let config = makeHTTPConfig() let channel = makeHTTPTestChannel() let runtime = try HTTPTestRuntime(config: config) @@ -1387,7 +1387,7 @@ struct HTTPHandlerTests { let channel = makeHTTPTestChannel() let runtime = try HTTPTestRuntime(config: config) { method, _ in #expect(method == "tools/call") - return .error(code: -32002, message: "upstream overloaded") + return .error(code: -32002, message: "host overloaded") } try await addHTTPHandler(to: channel, config: config, runtime: runtime) let sessionID = try await initializeHTTPChannel(channel) @@ -1406,7 +1406,7 @@ struct HTTPHandlerTests { #expect((object?["id"] as? NSNumber)?.intValue == 3101) let error = object?["error"] as? [String: Any] #expect((error?["code"] as? NSNumber)?.intValue == -32002) - #expect((error?["message"] as? String) == "upstream overloaded") + #expect((error?["message"] as? String) == "host overloaded") } @Test func httpInitializeIgnoresCallerProvidedSessionHeader() async throws { @@ -1878,7 +1878,7 @@ struct HTTPHandlerTests { case .health: return "/health" case .debugSnapshot: - return "/debug/upstreams?includeSensitive=1" + return "/debug/hosts?includeSensitive=1" case .debugReset: return "/debug/reset" case .sse, .deleteSession, .post: @@ -2000,11 +2000,11 @@ enum HostFailureCase: CaseIterable, Sendable { var message: String { switch self { - case .timeout: "upstream timeout" - case .processExit: "upstream unavailable" - case .backpressure: "upstream overloaded" + case .timeout: "host timeout" + case .processExit: "host unavailable" + case .backpressure: "host overloaded" case .rpcError: "Invalid params" - case .invalidResponse: "invalid upstream response" + case .invalidResponse: "invalid host response" } } } diff --git a/Tests/ProxyIntegrationTests/XcodeMCPProxyServerTests.swift b/Tests/ProxyIntegrationTests/XcodeMCPProxyServerTests.swift index ba87b76c..30f27fc8 100644 --- a/Tests/ProxyIntegrationTests/XcodeMCPProxyServerTests.swift +++ b/Tests/ProxyIntegrationTests/XcodeMCPProxyServerTests.swift @@ -178,7 +178,7 @@ struct XcodeMCPProxyServerTests { let server = XcodeMCPProxyServer(configuration: .init( bindAddress: .localhost(port: 0), nativeHostBundleURL: missingBundle, discovery: .disabled )) - await #expect(throws: MCPBridgeRuntimeError.self) { _ = try await server.start() } + await #expect(throws: MCPRuntimeError.self) { _ = try await server.start() } let snapshot = await server.snapshot() #expect(snapshot.phase == .stopped) #expect(snapshot.endpoint == nil) diff --git a/Tests/ProxyStressTests/DocumentationSearchStressTests.swift b/Tests/ProxyStressTests/DocumentationSearchStressTests.swift index 4af0c99e..cba2a9e5 100644 --- a/Tests/ProxyStressTests/DocumentationSearchStressTests.swift +++ b/Tests/ProxyStressTests/DocumentationSearchStressTests.swift @@ -13,8 +13,8 @@ struct DocumentationSearchStressTests { @Test func documentationSearchHandlesFourSessionsWithOneThousandParallelRequestsEach() async throws { let sessionCount = 4 let requestsPerSession = 1_000 - let upstream = DocumentationSearchStressUpstreamClient(sessionCount: sessionCount) - let server = try StressHTTPServer.start(upstream: upstream) + let host = DocumentationSearchStressHostSession(sessionCount: sessionCount) + let server = try StressHTTPServer.start(host: host) let urlSession = makeStressURLSession() defer { urlSession.invalidateAndCancel() @@ -35,7 +35,7 @@ struct DocumentationSearchStressTests { urlSession: urlSession ) - let counts = await upstream.documentationSearchCountsBySessionIndex() + let counts = await host.documentationSearchCountsBySessionIndex() #expect(counts == Array(repeating: requestsPerSession, count: sessionCount)) } catch { try? await server.shutdown() @@ -142,7 +142,7 @@ private struct StressHTTPServer { let broker: NativeHostBroker let childChannelTracker: HTTPTestServerChannelTracker - static func start(upstream: DocumentationSearchStressUpstreamClient) throws -> StressHTTPServer { + static func start(host: DocumentationSearchStressHostSession) throws -> StressHTTPServer { ProxyLogging.bootstrap(environment: ["MCP_LOG_LEVEL": "critical"]) let group = MultiThreadedEventLoopGroup(numberOfThreads: 4) let childChannelTracker = HTTPTestServerChannelTracker() @@ -158,7 +158,7 @@ private struct StressHTTPServer { let broker = try NativeHostBroker( configuration: config, inventory: XcodeHostInventory(defaultInstallation: installation) { [installation] }, - sessionFactory: { _ in SingleProcessFactory(session: upstream) }) + sessionFactory: { _ in SingleProcessFactory(session: host) }) let controlService = HTTPControlService(runtime: broker) let bootstrap = ServerBootstrap(group: group) @@ -207,18 +207,18 @@ private struct StressHTTPServer { } } -private struct SingleProcessFactory: UpstreamSessionFactory { - let session: DocumentationSearchStressUpstreamClient - func startSession() async throws -> any UpstreamSession { session } +private struct SingleProcessFactory: MCPProcessSessionFactory { + let session: DocumentationSearchStressHostSession + func startSession() async throws -> any MCPProcessSession { session } } -private actor DocumentationSearchStressUpstreamClient: UpstreamSession { - nonisolated let events: AsyncStream - private let continuation: AsyncStream.Continuation +private actor DocumentationSearchStressHostSession: MCPProcessSession { + nonisolated let events: AsyncStream + private let continuation: AsyncStream.Continuation private var countsBySessionIndex: [Int] init(sessionCount: Int) { - var streamContinuation: AsyncStream.Continuation! + var streamContinuation: AsyncStream.Continuation! self.events = AsyncStream { continuation in streamContinuation = continuation } @@ -234,7 +234,7 @@ private actor DocumentationSearchStressUpstreamClient: UpstreamSession { continuation.finish() } - func send(_ data: Data) async -> Upstream.SendResult { + func send(_ data: Data) async -> MCPProcess.SendResult { guard let json = try? JSONSerialization.jsonObject(with: data, options: []) else { return .accepted } diff --git a/Tests/PublicProductContractTests/PublicProductContractTests.swift b/Tests/PublicProductContractTests/PublicProductContractTests.swift index ce1469d6..4d951ead 100644 --- a/Tests/PublicProductContractTests/PublicProductContractTests.swift +++ b/Tests/PublicProductContractTests/PublicProductContractTests.swift @@ -930,7 +930,7 @@ func compileOnlyClientDomainSurface() throws { .invalidRequest("missing tool name"), .invalidResponse("missing result"), .requestTimedOut(method: "tools/list"), - .serverError(code: -32000, message: "upstream unavailable", data: ["reason": "disabled"]), + .serverError(code: -32000, message: "host unavailable", data: ["reason": "disabled"]), .transportUnavailable("mcpbridge closed"), .sessionRecoveryFailed("replacement initialize failed"), ] diff --git a/Tests/XcodeMCPCoreTestSupport/UpstreamProcessFixture.swift b/Tests/XcodeMCPCoreTestSupport/MCPProcessFixture.swift similarity index 93% rename from Tests/XcodeMCPCoreTestSupport/UpstreamProcessFixture.swift rename to Tests/XcodeMCPCoreTestSupport/MCPProcessFixture.swift index fac728a3..575bdfbf 100644 --- a/Tests/XcodeMCPCoreTestSupport/UpstreamProcessFixture.swift +++ b/Tests/XcodeMCPCoreTestSupport/MCPProcessFixture.swift @@ -2,14 +2,14 @@ import Foundation import Testing @testable import XcodeMCPCore -struct StaticUpstreamProcessDriverFactory: UpstreamProcessDriverMaking { - private let driver: FakeUpstreamProcessDriver +struct StaticMCPProcessDriverFactory: MCPProcessDriverMaking { + private let driver: FakeMCPProcessDriver - init(_ driver: FakeUpstreamProcessDriver) { + init(_ driver: FakeMCPProcessDriver) { self.driver = driver } - func makeDriver() -> any UpstreamProcessDriving { + func makeDriver() -> any MCPProcessDriving { driver } } @@ -28,8 +28,8 @@ final class ControlledTerminationDelay: @unchecked Sendable { self.operation = operation } - func makeDelay() -> UpstreamTerminationDelay { - UpstreamTerminationDelay(terminal: terminal) { [weak self] in + func makeDelay() -> MCPProcessTerminationDelay { + MCPProcessTerminationDelay(terminal: terminal) { [weak self] in self?.cancel() } } @@ -58,7 +58,7 @@ final class ControlledTerminationDelay: @unchecked Sendable { } final class ControlledTerminationDelayScheduler: - UpstreamTerminationDelayScheduling, + MCPProcessTerminationDelayScheduling, @unchecked Sendable { private let scheduled = DeterministicRecorder() @@ -66,7 +66,7 @@ final class ControlledTerminationDelayScheduler: func schedule( after delay: Duration, operation: @escaping @Sendable () -> Void - ) -> UpstreamTerminationDelay { + ) -> MCPProcessTerminationDelay { _ = delay let controlled = ControlledTerminationDelay(operation: operation) scheduled.record(controlled) @@ -78,7 +78,7 @@ final class ControlledTerminationDelayScheduler: } } -final class FakeUpstreamProcessDriver: UpstreamProcessDriving, @unchecked Sendable { +final class FakeMCPProcessDriver: MCPProcessDriving, @unchecked Sendable { struct Snapshot: Sendable { let closeStdinCount: Int let terminateCount: Int @@ -146,7 +146,7 @@ final class FakeUpstreamProcessDriver: UpstreamProcessDriving, @unchecked Sendab environment: [String: String], maxQueuedWriteBytes: Int, onTermination: @escaping @Sendable (Int32) -> Void - ) throws -> UpstreamProcessStartedIO { + ) throws -> MCPProcessStartedIO { _ = command _ = args _ = environment @@ -155,14 +155,14 @@ final class FakeUpstreamProcessDriver: UpstreamProcessDriving, @unchecked Sendab state.maxQueuedWriteBytes = maxQueuedWriteBytes state.onTermination = onTermination } - return UpstreamProcessStartedIO( + return MCPProcessStartedIO( stdoutChunks: stdoutChunks, stderrChunks: stderrChunks ) } - func sendStdin(_ payload: Data) -> Upstream.SendResult { - let result: Upstream.SendResult = lock.withLock { + func sendStdin(_ payload: Data) -> MCPProcess.SendResult { + let result: MCPProcess.SendResult = lock.withLock { guard state.isRunning else { return .unavailable(.terminated) } diff --git a/Tests/XcodeMCPCoreTests/JSONRPCWireContractTests.swift b/Tests/XcodeMCPCoreTests/JSONRPCWireContractTests.swift index 940d1b24..33fde7ff 100644 --- a/Tests/XcodeMCPCoreTests/JSONRPCWireContractTests.swift +++ b/Tests/XcodeMCPCoreTests/JSONRPCWireContractTests.swift @@ -71,7 +71,7 @@ struct JSONRPCWireContractTests { let errorData = try JSONRPC.Wire.errorResponseData( id: numberID, code: -32002, - message: "upstream overloaded" + message: "host overloaded" ) let response = try #require( JSONSerialization.jsonObject(with: errorData) as? [String: Any] @@ -81,12 +81,12 @@ struct JSONRPCWireContractTests { #expect(response["jsonrpc"] as? String == "2.0") #expect((response["id"] as? NSNumber)?.intValue == 7) #expect((error["code"] as? NSNumber)?.intValue == -32002) - #expect(error["message"] as? String == "upstream overloaded") + #expect(error["message"] as? String == "host overloaded") let parsedError = try #require(JSONRPC.Wire.errorPayload(inResponseObject: response)) #expect(parsedError.code == -32002) - #expect(parsedError.message == "upstream overloaded") + #expect(parsedError.message == "host overloaded") let invalidRequestData = try JSONRPC.Wire.errorResponseData( id: nil, diff --git a/Tests/XcodeMCPCoreTests/NativeHostInvocationTests.swift b/Tests/XcodeMCPCoreTests/NativeHostInvocationTests.swift index f45b10df..763670a1 100644 --- a/Tests/XcodeMCPCoreTests/NativeHostInvocationTests.swift +++ b/Tests/XcodeMCPCoreTests/NativeHostInvocationTests.swift @@ -41,7 +41,7 @@ struct NativeHostInvocationTests { @Test func explicitMissingBundleDoesNotSelectAnotherInstalledHelper() { var fileSystem = FileSystemClient.testValue fileSystem.isExecutableFile = { $0 == "/installed/XcodeMCPNativeHost.app/Contents/MacOS/xcode-mcp-native-host" } - #expect(throws: MCPBridgeRuntimeError.self) { + #expect(throws: MCPRuntimeError.self) { try NativeHostInvocation.resolve(bundleURL: URL(fileURLWithPath: "/missing.app"), environment: ["PATH": "/installed"], executableURL: nil, fileSystem: fileSystem) } diff --git a/Tests/XcodeMCPKitTests/ProcessTransportIntegrationTests.swift b/Tests/XcodeMCPKitTests/ProcessTransportIntegrationTests.swift index f245c75b..e60f6ae6 100644 --- a/Tests/XcodeMCPKitTests/ProcessTransportIntegrationTests.swift +++ b/Tests/XcodeMCPKitTests/ProcessTransportIntegrationTests.swift @@ -7,16 +7,16 @@ import Testing @Suite(.serialized) struct ProcessTransportIntegrationTests { @Test func stdoutEOFFailsUnboundedRequestsAfterDeliveringTheFinalResponse() async throws { - let fakeDriver = FakeUpstreamProcessDriver(terminatesOnTerminate: false) + let fakeDriver = FakeMCPProcessDriver(terminatesOnTerminate: false) let scheduler = ControlledTerminationDelayScheduler() - let transport = try await UpstreamProcessXcodeMCPTransport.start(config: .init( - command: "/fake/upstream", + let transport = try await ProcessXcodeMCPTransport.start(config: .init( + command: "/fake/mcp-process", args: [], environment: [:], maxQueuedWriteBytes: 64 * 1024, terminationSignalGrace: .seconds(30), terminationDelayScheduler: scheduler, - driverFactory: StaticUpstreamProcessDriverFactory(fakeDriver) + driverFactory: StaticMCPProcessDriverFactory(fakeDriver) )) defer { fakeDriver.emitTermination(status: 0) @@ -70,9 +70,9 @@ struct ProcessTransportIntegrationTests { switch await pendingRequest.result { case .success: Issue.record("unanswered request succeeded after stdout EOF") - return nil as MCPBridgeRuntimeError? + return nil as MCPRuntimeError? case .failure(let error): - return error as? MCPBridgeRuntimeError + return error as? MCPRuntimeError } } guard case .transportUnavailable = error else { @@ -85,7 +85,7 @@ struct ProcessTransportIntegrationTests { } Issue.record("request after EOF succeeded") } catch { - guard case .transportUnavailable = error as? MCPBridgeRuntimeError else { + guard case .transportUnavailable = error as? MCPRuntimeError else { Issue.record("expected unavailable transport after EOF, got \(error)") return } @@ -108,15 +108,15 @@ struct ProcessTransportIntegrationTests { } @Test func processTransportDeinitSynchronouslySignalsOwnedProcess() async throws { - let fakeDriver = FakeUpstreamProcessDriver() - let config = UpstreamProcess.Config( - command: "/fake/upstream", + let fakeDriver = FakeMCPProcessDriver() + let config = MCPProcessLauncher.Config( + command: "/fake/mcp-process", args: [], environment: [:], maxQueuedWriteBytes: 1024, - driverFactory: StaticUpstreamProcessDriverFactory(fakeDriver) + driverFactory: StaticMCPProcessDriverFactory(fakeDriver) ) - var transport: UpstreamProcessXcodeMCPTransport? = try await .start(config: config) + var transport: ProcessXcodeMCPTransport? = try await .start(config: config) weak let weakTransport = transport transport = nil diff --git a/Tests/XcodeMCPKitTests/XcodeMCPTests.swift b/Tests/XcodeMCPKitTests/XcodeMCPTests.swift index e685c03c..72dd1c0d 100644 --- a/Tests/XcodeMCPKitTests/XcodeMCPTests.swift +++ b/Tests/XcodeMCPKitTests/XcodeMCPTests.swift @@ -137,7 +137,7 @@ struct XcodeMCPTests { await closeGate.open() #expect(try await transport.nextCloseTerminal() == 1) - await #expect(throws: MCPBridgeRuntimeError.invalidResponse( + await #expect(throws: MCPRuntimeError.invalidResponse( "initialize result has unsupported protocolVersion 2099-01-01" )) { try await initialize.value @@ -147,7 +147,7 @@ struct XcodeMCPTests { @Test func asyncInitializerMapsRuntimeTransportErrorsToPublicError() async throws { let transport = RuntimeFailingXcodeMCPTransport( - error: MCPBridgeRuntimeError.transportUnavailable("mcpbridge write queue is full") + error: MCPRuntimeError.transportUnavailable("mcpbridge write queue is full") ) await #expect(throws: XcodeMCPError.transportUnavailable( @@ -427,7 +427,7 @@ struct XcodeMCPTests { weakProbe = probe let capturedProbe = probe - await #expect(throws: MCPBridgeRuntimeError.invalidRequest( + await #expect(throws: MCPRuntimeError.invalidRequest( "progress requests require object params" )) { _ = try await session.request( @@ -523,7 +523,7 @@ struct XcodeMCPTests { ) let sendsBeforeRequest = await transport.sentMessages().count - await #expect(throws: MCPBridgeRuntimeError.requestTimedOut(method: "tools/list")) { + await #expect(throws: MCPRuntimeError.requestTimedOut(method: "tools/list")) { _ = try await session.request( "tools/list", deadline: Deadline(uptimeNanoseconds: 0) @@ -576,7 +576,7 @@ struct XcodeMCPTests { #expect(requestedTimeout == .seconds(2)) await timeoutClock.resumeSleep(at: sleepBaseline) - await #expect(throws: MCPBridgeRuntimeError.requestTimedOut(method: "tools/list")) { + await #expect(throws: MCPRuntimeError.requestTimedOut(method: "tools/list")) { _ = try await requestTask.value } _ = try await transport.nextCancelled(method: "tools/list") @@ -1381,7 +1381,7 @@ struct XcodeMCPTests { ] for array in arrays { - #expect(throws: MCPBridgeRuntimeError.invalidRequest( + #expect(throws: MCPRuntimeError.invalidRequest( "JSON-RPC message must be one object" )) { _ = try MCPClientEnvelope(data: Data(array.utf8)) @@ -1964,9 +1964,9 @@ private func waitUntilAuthorityCloseStarts( throw XcodeMCPError.invalidResponse( "expired close probe unexpectedly reached the transport" ) - } catch MCPBridgeRuntimeError.closed { + } catch MCPRuntimeError.closed { return - } catch MCPBridgeRuntimeError.requestTimedOut { + } catch MCPRuntimeError.requestTimedOut { await Task.yield() } catch MCPClientSessionFailure.sessionRecoveryFailed { await Task.yield() @@ -2023,7 +2023,7 @@ private actor LifecycleTransportFactory { func make() throws -> any XcodeMCPTransport { guard index < transports.count else { - throw MCPBridgeRuntimeError.transportUnavailable("test factory exhausted") + throw MCPRuntimeError.transportUnavailable("test factory exhausted") } defer { index += 1 } return transports[index] @@ -2128,7 +2128,7 @@ private actor StalledRecoveryTransportFactory { case 3: return fresh default: - throw MCPBridgeRuntimeError.transportUnavailable("test factory exhausted") + throw MCPRuntimeError.transportUnavailable("test factory exhausted") } } @@ -2159,7 +2159,7 @@ private actor MixedRecoveryTransportFactory { func make() throws -> any XcodeMCPTransport { guard transports.indices.contains(count) else { - throw MCPBridgeRuntimeError.transportUnavailable("test factory exhausted") + throw MCPRuntimeError.transportUnavailable("test factory exhausted") } defer { count += 1 } return transports[count] @@ -2218,7 +2218,7 @@ private actor LifecycleContractTransport: XcodeMCPTransport { ) async throws { _ = headers _ = deadline - guard closed == false else { throw MCPBridgeRuntimeError.closed } + guard closed == false else { throw MCPRuntimeError.closed } let object = try lifecycleObject(data) let message = SentMessage( id: object["id"], @@ -2327,7 +2327,7 @@ private actor LifecycleContractTransport: XcodeMCPTransport { let raw = try JSONSerialization.jsonObject(with: data) guard let value = MCPJSONValue(foundationObject: raw), let object = value.objectValue else { - throw MCPBridgeRuntimeError.invalidRequest("test message is not an object") + throw MCPRuntimeError.invalidRequest("test message is not an object") } return object } @@ -2593,10 +2593,10 @@ private actor UnsupportedResponseFailingXcodeMCPTransport: XcodeMCPTransport { private let continuation: AsyncStream.Continuation private let sentMessageValues = RecordedValues() - private let error: MCPBridgeRuntimeError + private let error: MCPRuntimeError private var closed = false - init(error: MCPBridgeRuntimeError) { + init(error: MCPRuntimeError) { let stream = AsyncStream.makeStream() self.events = stream.stream self.continuation = stream.continuation @@ -2611,7 +2611,7 @@ private actor UnsupportedResponseFailingXcodeMCPTransport: XcodeMCPTransport { _ = headers _ = deadline guard closed == false else { - throw MCPBridgeRuntimeError.closed + throw MCPRuntimeError.closed } let object = try parse(data) let sent = SentMessage( diff --git a/Tests/XcodeMCPProcessRuntimeTests/UpstreamProcessTests.swift b/Tests/XcodeMCPProcessRuntimeTests/MCPProcessLauncherTests.swift similarity index 83% rename from Tests/XcodeMCPProcessRuntimeTests/UpstreamProcessTests.swift rename to Tests/XcodeMCPProcessRuntimeTests/MCPProcessLauncherTests.swift index f2cd57cc..ec5980f6 100644 --- a/Tests/XcodeMCPProcessRuntimeTests/UpstreamProcessTests.swift +++ b/Tests/XcodeMCPProcessRuntimeTests/MCPProcessLauncherTests.swift @@ -4,11 +4,11 @@ import Testing @testable import XcodeMCPCoreTestSupport @Suite -struct UpstreamProcessTests { +struct MCPProcessLauncherTests { @Test func upstreamSessionReassemblesStdoutMessagesAndPreservesOrder() async throws { - let fakeDriver = FakeUpstreamProcessDriver() - let session = try await makeFakeUpstreamSession(fakeDriver) - let events = UpstreamEventRecorder(session.events) + let fakeDriver = FakeMCPProcessDriver() + let session = try await makeFakeProcessSession(fakeDriver) + let events = MCPProcessEventRecorder(session.events) defer { events.cancel() Task { @@ -49,9 +49,9 @@ struct UpstreamProcessTests { } @Test func upstreamSessionFlushesStderrLinesAndLargeChunksDeterministically() async throws { - let fakeDriver = FakeUpstreamProcessDriver() - let session = try await makeFakeUpstreamSession(fakeDriver) - let events = UpstreamEventRecorder(session.events) + let fakeDriver = FakeMCPProcessDriver() + let session = try await makeFakeProcessSession(fakeDriver) + let events = MCPProcessEventRecorder(session.events) defer { events.cancel() Task { @@ -80,8 +80,8 @@ struct UpstreamProcessTests { } @Test func upstreamSessionWritesStdinInOrderAndReportsBackpressure() async throws { - let fakeDriver = FakeUpstreamProcessDriver() - let session = try await makeFakeUpstreamSession(fakeDriver, maxQueuedWriteBytes: 12) + let fakeDriver = FakeMCPProcessDriver() + let session = try await makeFakeProcessSession(fakeDriver, maxQueuedWriteBytes: 12) defer { Task { await session.stop() @@ -99,9 +99,9 @@ struct UpstreamProcessTests { } @Test func upstreamSessionDrainsLateStdoutBeforeExitAfterTermination() async throws { - let fakeDriver = FakeUpstreamProcessDriver() - let session = try await makeFakeUpstreamSession(fakeDriver) - let events = UpstreamEventRecorder(session.events) + let fakeDriver = FakeMCPProcessDriver() + let session = try await makeFakeProcessSession(fakeDriver) + let events = MCPProcessEventRecorder(session.events) defer { events.cancel() Task { @@ -135,13 +135,13 @@ struct UpstreamProcessTests { @Test func upstreamSessionForcesExitAfterDeterministicDrainGrace() async throws { let drainClock = TestClock() - let fakeDriver = FakeUpstreamProcessDriver() - let session = try await makeFakeUpstreamSession( + let fakeDriver = FakeMCPProcessDriver() + let session = try await makeFakeProcessSession( fakeDriver, terminationDrainGrace: .seconds(10), clock: makeTestClockClient(drainClock) ) - let events = UpstreamEventRecorder(session.events) + let events = MCPProcessEventRecorder(session.events) defer { events.cancel() Task { @@ -165,9 +165,9 @@ struct UpstreamProcessTests { } @Test func upstreamSessionTreatsInvalidStdoutAsFatalProtocolViolation() async throws { - let fakeDriver = FakeUpstreamProcessDriver() - let session = try await makeFakeUpstreamSession(fakeDriver) - let events = UpstreamEventRecorder(session.events) + let fakeDriver = FakeMCPProcessDriver() + let session = try await makeFakeProcessSession(fakeDriver) + let events = MCPProcessEventRecorder(session.events) defer { events.cancel() Task { @@ -194,12 +194,12 @@ struct UpstreamProcessTests { @Test func stdoutEOFStartsBoundedCleanupAndRejectsFurtherSends() async throws { let scheduler = ControlledTerminationDelayScheduler() - let fakeDriver = FakeUpstreamProcessDriver(terminatesOnTerminate: false) - let session = try await makeFakeUpstreamSession( + let fakeDriver = FakeMCPProcessDriver(terminatesOnTerminate: false) + let session = try await makeFakeProcessSession( fakeDriver, terminationSignalGrace: .seconds(30), terminationDelayScheduler: scheduler ) - let events = UpstreamEventRecorder(session.events) + let events = MCPProcessEventRecorder(session.events) defer { events.cancel() fakeDriver.emitTermination(status: 0) @@ -226,9 +226,9 @@ struct UpstreamProcessTests { } @Test func upstreamSessionStopIsIdempotentAndSuppressesExit() async throws { - let fakeDriver = FakeUpstreamProcessDriver() - let session = try await makeFakeUpstreamSession(fakeDriver) - let events = UpstreamEventRecorder(session.events) + let fakeDriver = FakeMCPProcessDriver() + let session = try await makeFakeProcessSession(fakeDriver) + let events = MCPProcessEventRecorder(session.events) defer { events.cancel() } @@ -247,13 +247,13 @@ struct UpstreamProcessTests { @Test func stdoutEOFDrainsStderrBeforeTerminationNotification() async throws { let scheduler = ControlledTerminationDelayScheduler() let drainClock = TestClock() - let fakeDriver = FakeUpstreamProcessDriver(terminatesOnTerminate: false) - let session = try await makeFakeUpstreamSession( + let fakeDriver = FakeMCPProcessDriver(terminatesOnTerminate: false) + let session = try await makeFakeProcessSession( fakeDriver, terminationDelayScheduler: scheduler, clock: makeTestClockClient(drainClock) ) - let events = UpstreamEventRecorder(session.events) + let events = MCPProcessEventRecorder(session.events) defer { events.cancel() Task { await session.stop() } @@ -288,8 +288,8 @@ struct UpstreamProcessTests { } @Test func concurrentStopsShareOutputDrainCompletion() async throws { - let fakeDriver = FakeUpstreamProcessDriver(finishesOutputOnStop: false) - let session = try await makeFakeUpstreamSession(fakeDriver) + let fakeDriver = FakeMCPProcessDriver(finishesOutputOnStop: false) + let session = try await makeFakeProcessSession(fakeDriver) let completedStops = RecordedValues() let first = Task { @@ -314,8 +314,8 @@ struct UpstreamProcessTests { @Test func stopCancelsEscalationDelayAfterDelayedTerminationAcknowledgement() async throws { let scheduler = ControlledTerminationDelayScheduler() - let fakeDriver = FakeUpstreamProcessDriver(terminatesOnTerminate: false) - let session = try await makeFakeUpstreamSession( + let fakeDriver = FakeMCPProcessDriver(terminatesOnTerminate: false) + let session = try await makeFakeProcessSession( fakeDriver, terminationSignalGrace: .seconds(30), terminationDelayScheduler: scheduler @@ -348,8 +348,8 @@ struct UpstreamProcessTests { @Test func stopEscalatesIgnoredTerminationAndDrainsQueuedStdinCallbacks() async throws { let scheduler = ControlledTerminationDelayScheduler() - let fakeDriver = FakeUpstreamProcessDriver(terminatesOnTerminate: false) - let session = try await makeFakeUpstreamSession( + let fakeDriver = FakeMCPProcessDriver(terminatesOnTerminate: false) + let session = try await makeFakeProcessSession( fakeDriver, terminationSignalGrace: .seconds(30), terminationDelayScheduler: scheduler @@ -389,9 +389,9 @@ struct UpstreamProcessTests { @Test func normalStopPreservesFinalOutputWithoutSendingTerminationSignals() async throws { let scheduler = ControlledTerminationDelayScheduler() - let fakeDriver = FakeUpstreamProcessDriver() - let session = try await makeFakeUpstreamSession(fakeDriver, terminationDelayScheduler: scheduler) - let events = UpstreamEventRecorder(session.events) + let fakeDriver = FakeMCPProcessDriver() + let session = try await makeFakeProcessSession(fakeDriver, terminationDelayScheduler: scheduler) + let events = MCPProcessEventRecorder(session.events) let stopped = RecordedValues() let stop = Task { await session.stop() @@ -428,8 +428,8 @@ struct UpstreamProcessTests { @Test func normalStopBoundsOutputDrainAfterNaturalExit() async throws { let clock = TestClock() - let fakeDriver = FakeUpstreamProcessDriver() - let session = try await makeFakeUpstreamSession( + let fakeDriver = FakeMCPProcessDriver() + let session = try await makeFakeProcessSession( fakeDriver, terminationDrainGrace: .seconds(10), clock: makeTestClockClient(clock) ) let stop = Task { await session.stop() } @@ -445,8 +445,8 @@ struct UpstreamProcessTests { } @Test func synchronousCancelKeepsImmediateSignalCleanup() async throws { - let fakeDriver = FakeUpstreamProcessDriver() - let session = try await makeFakeUpstreamSession(fakeDriver) + let fakeDriver = FakeMCPProcessDriver() + let session = try await makeFakeProcessSession(fakeDriver) session.cancel() #expect(fakeDriver.snapshot().terminateCount == 1) #expect(fakeDriver.snapshot().stopOutputCount == 1) @@ -459,7 +459,7 @@ struct UpstreamProcessTests { } @Suite(.serialized, .enabled(if: ProcessTestEnvironment.isEnabled)) -struct LiveUpstreamProcessSmokeTests { +struct LiveMCPProcessSmokeTests { @Test(arguments: [true, false]) func stopLetsEOFChildCompleteOrEscalatesAnUnresponsiveChild(respondsToEOF: Bool) async throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) @@ -486,7 +486,7 @@ struct LiveUpstreamProcessSmokeTests { fi while :; do :; done """ - let config = UpstreamProcess.Config( + let config = MCPProcessLauncher.Config( command: "/bin/sh", args: ["-c", script, "eof-child", respondsToEOF ? "natural" : "unresponsive", marker.path, pidFile.path], environment: ProcessInfo.processInfo.environment, @@ -494,8 +494,8 @@ struct LiveUpstreamProcessSmokeTests { terminationSignalGrace: respondsToEOF ? .seconds(1) : .milliseconds(75), driverFactory: TerminationRecordingDriverFactory(statuses: statuses) ) - try await withLiveUpstreamSession(config: config) { session in - let events = UpstreamEventRecorder(session.events) + try await withLiveProcessSession(config: config) { session in + let events = MCPProcessEventRecorder(session.events) _ = try await events.nextMessage() try await waitWithTimeout("EOF child stop", timeout: .seconds(5)) { await session.stop() @@ -516,16 +516,16 @@ struct LiveUpstreamProcessSmokeTests { } @Test func upstreamProcessLiveSmokeStopsChildAfterStdoutEOF() async throws { - let config = UpstreamProcess.Config( + let config = MCPProcessLauncher.Config( command: "/bin/sh", args: ["-c", "trap '' TERM; printf '{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{}}'; exec 1>&-; while :; do sleep 1; done"], environment: ProcessInfo.processInfo.environment, maxQueuedWriteBytes: 1024, terminationSignalGrace: .milliseconds(50) ) - try await withLiveUpstreamSession(config: config) { session in + try await withLiveProcessSession(config: config) { session in let events = try await waitWithTimeout("live stdout EOF cleanup", timeout: .seconds(5)) { - var observed: [Upstream.Event] = [] + var observed: [MCPProcess.Event] = [] for await event in session.events { observed.append(event) } return observed } @@ -543,7 +543,7 @@ struct LiveUpstreamProcessSmokeTests { } @Test func upstreamProcessLiveSmokeDrainsMessageStderrAndExit() async throws { - let config = UpstreamProcess.Config( + let config = MCPProcessLauncher.Config( command: "/bin/sh", args: [ "-c", @@ -553,12 +553,12 @@ struct LiveUpstreamProcessSmokeTests { maxQueuedWriteBytes: 1024 ) - try await withLiveUpstreamSession(config: config) { session in + try await withLiveProcessSession(config: config) { session in let events = try await waitWithTimeout( - "live UpstreamProcess smoke should finish", + "live MCPProcessLauncher smoke should finish", timeout: .seconds(5) ) { - var observed: [Upstream.Event] = [] + var observed: [MCPProcess.Event] = [] for await event in session.events { observed.append(event) if isExitEvent(event) { @@ -590,25 +590,25 @@ struct LiveUpstreamProcessSmokeTests { } } -private struct TerminationRecordingDriverFactory: UpstreamProcessDriverMaking { +private struct TerminationRecordingDriverFactory: MCPProcessDriverMaking { let statuses: DeterministicRecorder - func makeDriver() -> any UpstreamProcessDriving { - TerminationRecordingDriver(driver: LiveUpstreamProcessDriverFactory().makeDriver(), statuses: statuses) + func makeDriver() -> any MCPProcessDriving { + TerminationRecordingDriver(driver: LiveMCPProcessDriverFactory().makeDriver(), statuses: statuses) } } -private final class TerminationRecordingDriver: UpstreamProcessDriving { - let driver: any UpstreamProcessDriving +private final class TerminationRecordingDriver: MCPProcessDriving { + let driver: any MCPProcessDriving let statuses: DeterministicRecorder - init(driver: any UpstreamProcessDriving, statuses: DeterministicRecorder) { + init(driver: any MCPProcessDriving, statuses: DeterministicRecorder) { self.driver = driver self.statuses = statuses } func start(command: String, args: [String], environment: [String: String], maxQueuedWriteBytes: Int, - onTermination: @escaping @Sendable (Int32) -> Void) throws -> UpstreamProcessStartedIO { + onTermination: @escaping @Sendable (Int32) -> Void) throws -> MCPProcessStartedIO { let statuses = statuses return try driver.start(command: command, args: args, environment: environment, maxQueuedWriteBytes: maxQueuedWriteBytes) { status in @@ -617,7 +617,7 @@ private final class TerminationRecordingDriver: UpstreamProcessDriving { } } - func sendStdin(_ payload: Data) -> Upstream.SendResult { driver.sendStdin(payload) } + func sendStdin(_ payload: Data) -> MCPProcess.SendResult { driver.sendStdin(payload) } func closeStdin() { driver.closeStdin() } func terminate() -> Bool { driver.terminate() } func forceTerminate() -> Bool { driver.forceTerminate() } @@ -626,17 +626,17 @@ private final class TerminationRecordingDriver: UpstreamProcessDriving { func waitForOutputStopped() async { await driver.waitForOutputStopped() } } -private func makeFakeUpstreamSession( - _ fakeDriver: FakeUpstreamProcessDriver, +private func makeFakeProcessSession( + _ fakeDriver: FakeMCPProcessDriver, maxQueuedWriteBytes: Int = 1024, terminationDrainGrace: Duration = .milliseconds(250), terminationSignalGrace: Duration = .seconds(1), - terminationDelayScheduler: any UpstreamTerminationDelayScheduling = - LiveUpstreamTerminationDelayScheduler(), + terminationDelayScheduler: any MCPProcessTerminationDelayScheduling = + LiveMCPProcessTerminationDelayScheduler(), clock: ClockClient = .liveValue -) async throws -> any UpstreamSession { - let config = UpstreamProcess.Config( - command: "/fake/upstream", +) async throws -> any MCPProcessSession { + let config = MCPProcessLauncher.Config( + command: "/fake/mcp-process", args: [], environment: [:], maxQueuedWriteBytes: maxQueuedWriteBytes, @@ -644,16 +644,16 @@ private func makeFakeUpstreamSession( terminationSignalGrace: terminationSignalGrace, terminationDelayScheduler: terminationDelayScheduler, clock: clock, - driverFactory: StaticUpstreamProcessDriverFactory(fakeDriver) + driverFactory: StaticMCPProcessDriverFactory(fakeDriver) ) - return try await UpstreamProcess(configuration: config).startSession() + return try await MCPProcessLauncher(configuration: config).startSession() } -private func withLiveUpstreamSession( - config: UpstreamProcess.Config, - _ body: @escaping @Sendable (any UpstreamSession) async throws -> T +private func withLiveProcessSession( + config: MCPProcessLauncher.Config, + _ body: @escaping @Sendable (any MCPProcessSession) async throws -> T ) async throws -> T { - let session = try await UpstreamProcess(configuration: config).startSession() + let session = try await MCPProcessLauncher(configuration: config).startSession() do { let result = try await body(session) await session.stop() @@ -664,14 +664,14 @@ private func withLiveUpstreamSession( } } -private final class UpstreamEventRecorder: @unchecked Sendable { - private let recorder = DeterministicRecorder() - private let task: Task<[Upstream.Event], Never> +private final class MCPProcessEventRecorder: @unchecked Sendable { + private let recorder = DeterministicRecorder() + private let task: Task<[MCPProcess.Event], Never> - init(_ events: AsyncStream) { + init(_ events: AsyncStream) { let recorder = recorder self.task = Task { - var allEvents: [Upstream.Event] = [] + var allEvents: [MCPProcess.Event] = [] for await event in events { allEvents.append(event) recorder.record(event) @@ -681,8 +681,8 @@ private final class UpstreamEventRecorder: @unchecked Sendable { } func nextEvent( - matching predicate: @escaping @Sendable (Upstream.Event) -> Bool - ) async throws -> Upstream.Event { + matching predicate: @escaping @Sendable (MCPProcess.Event) -> Bool + ) async throws -> MCPProcess.Event { try await recorder.nextValue(matching: predicate) } @@ -712,11 +712,11 @@ private final class UpstreamEventRecorder: @unchecked Sendable { return value } - func snapshot() -> [Upstream.Event] { + func snapshot() -> [MCPProcess.Event] { recorder.snapshot() } - func finishedEvents() async -> [Upstream.Event] { + func finishedEvents() async -> [MCPProcess.Event] { await task.value } @@ -725,7 +725,7 @@ private final class UpstreamEventRecorder: @unchecked Sendable { } } -private func isExitEvent(_ event: Upstream.Event) -> Bool { +private func isExitEvent(_ event: MCPProcess.Event) -> Bool { if case .exit = event { return true } diff --git a/Tests/XcodeMCPProxyRuntimeTestSupport/FakeHostSession.swift b/Tests/XcodeMCPProxyRuntimeTestSupport/FakeHostSession.swift index c4dbb01e..88050fe7 100644 --- a/Tests/XcodeMCPProxyRuntimeTestSupport/FakeHostSession.swift +++ b/Tests/XcodeMCPProxyRuntimeTestSupport/FakeHostSession.swift @@ -7,7 +7,7 @@ import XcodeMCPProxyTestSupport /// A scripted host process. It answers `initialize` and, unless `handlesCatalog` is set, /// `tools/list` itself, and asks `handle` for every other request. -final class FakeHostSession: UpstreamSession, Sendable { +final class FakeHostSession: MCPProcessSession, Sendable { enum Reply: Sendable { case result(JSONValue) case error(code: Int, message: String) @@ -17,8 +17,8 @@ final class FakeHostSession: UpstreamSession, Sendable { case backpressure } - let events: AsyncStream - private let continuation: AsyncStream.Continuation + let events: AsyncStream + private let continuation: AsyncStream.Continuation private let handle: @Sendable (_ method: String, _ params: [String: JSONValue]) -> Reply private let tools: NIOLockedValueBox private let initializeReply: Reply? @@ -43,14 +43,14 @@ final class FakeHostSession: UpstreamSession, Sendable { handle: @escaping @Sendable (_ method: String, _ params: [String: JSONValue]) -> Reply = { _, _ in .result(.object([:])) }) { - (events, continuation) = AsyncStream.makeStream() + (events, continuation) = AsyncStream.makeStream() self.tools = NIOLockedValueBox(tools) self.initializeReply = initializeReply self.handlesCatalog = handlesCatalog self.handle = handle } - func send(_ data: Data) async -> Upstream.SendResult { + func send(_ data: Data) async -> MCPProcess.SendResult { guard let value = (try? JSONSerialization.jsonObject(with: data)).flatMap(JSONValue.init(any:)), case .object(let object) = value else { Issue.record("The host received a message that is not a JSON object") @@ -144,7 +144,7 @@ final class FakeHostSession: UpstreamSession, Sendable { } /// Starts a new `FakeHostSession` for every process start. -final class FakeHostSessionFactory: UpstreamSessionFactory, Sendable { +final class FakeHostSessionFactory: MCPProcessSessionFactory, Sendable { let sessions = NIOLockedValueBox<[FakeHostSession]>([]) let started = LockedRecordedValues() private let make: @Sendable (_ start: Int) throws -> FakeHostSession @@ -153,7 +153,7 @@ final class FakeHostSessionFactory: UpstreamSessionFactory, Sendable { self.make = make } - func startSession() async throws -> any UpstreamSession { + func startSession() async throws -> any MCPProcessSession { let session = try make(sessions.withLockedValue { $0.count }) sessions.withLockedValue { $0.append(session) } started.append(session) diff --git a/Tests/XcodeMCPProxyRuntimeTestSupport/HostProcessConfigurationMirror.swift b/Tests/XcodeMCPProxyRuntimeTestSupport/HostProcessConfigurationMirror.swift index ac522a22..504cf7a4 100644 --- a/Tests/XcodeMCPProxyRuntimeTestSupport/HostProcessConfigurationMirror.swift +++ b/Tests/XcodeMCPProxyRuntimeTestSupport/HostProcessConfigurationMirror.swift @@ -3,7 +3,7 @@ import Testing import XcodeMCPCore @testable import XcodeMCPProxyRuntime -func upstreamEnvironment(from factory: any UpstreamSessionFactory) throws -> [String: String] { +func upstreamEnvironment(from factory: any MCPProcessSessionFactory) throws -> [String: String] { let configMirror = try upstreamConfigMirror(from: factory) return try upstreamEnvironment(fromConfigMirror: configMirror) } @@ -12,20 +12,20 @@ private func upstreamEnvironment(fromConfigMirror configMirror: Mirror) throws - return try #require( configMirror.children.first(where: { $0.label == "environment" })?.value as? [String: String], - "UpstreamProcess.Config should include environment for tests" + "MCPProcessLauncher.Config should include environment for tests" ) } -func upstreamMaxQueuedWriteBytes(from factory: any UpstreamSessionFactory) throws -> Int { +func upstreamMaxQueuedWriteBytes(from factory: any MCPProcessSessionFactory) throws -> Int { let configMirror = try upstreamConfigMirror(from: factory) return try #require( configMirror.children.first(where: { $0.label == "maxQueuedWriteBytes" })?.value as? Int, - "UpstreamProcess.Config should include maxQueuedWriteBytes for tests" + "MCPProcessLauncher.Config should include maxQueuedWriteBytes for tests" ) } -func upstreamCommand(from factory: any UpstreamSessionFactory) throws -> String { +func upstreamCommand(from factory: any MCPProcessSessionFactory) throws -> String { let configMirror = try upstreamConfigMirror(from: factory) return try upstreamCommand(fromConfigMirror: configMirror) } @@ -33,12 +33,12 @@ func upstreamCommand(from factory: any UpstreamSessionFactory) throws -> String private func upstreamCommand(fromConfigMirror configMirror: Mirror) throws -> String { return try #require( configMirror.children.first(where: { $0.label == "command" })?.value as? String, - "UpstreamProcess.Config should include command for tests" + "MCPProcessLauncher.Config should include command for tests" ) } -func upstreamArgs(from factory: any UpstreamSessionFactory) throws -> [String] { +func upstreamArgs(from factory: any MCPProcessSessionFactory) throws -> [String] { let configMirror = try upstreamConfigMirror(from: factory) return try upstreamArgs(fromConfigMirror: configMirror) } @@ -46,19 +46,19 @@ func upstreamArgs(from factory: any UpstreamSessionFactory) throws -> [String] { private func upstreamArgs(fromConfigMirror configMirror: Mirror) throws -> [String] { return try #require( configMirror.children.first(where: { $0.label == "args" })?.value as? [String], - "UpstreamProcess.Config should include args for tests" + "MCPProcessLauncher.Config should include args for tests" ) } -private func upstreamConfigMirror(from factory: any UpstreamSessionFactory) throws -> Mirror { +private func upstreamConfigMirror(from factory: any MCPProcessSessionFactory) throws -> Mirror { if let factory = factory as? NativeHostSessionFactory { return Mirror(reflecting: try factory.processConfiguration(environment: factory.environment)) } let factoryMirror = Mirror(reflecting: factory) let config = try #require( factoryMirror.children.first(where: { $0.label == "config" })?.value, - "UpstreamProcess factory should expose a stored config for tests" + "MCPProcessLauncher factory should expose a stored config for tests" ) return Mirror(reflecting: config) } diff --git a/Tests/XcodeMCPProxyRuntimeTests/NativeHostBrokerTests.swift b/Tests/XcodeMCPProxyRuntimeTests/NativeHostBrokerTests.swift index 6165c0ef..3f147f6b 100644 --- a/Tests/XcodeMCPProxyRuntimeTests/NativeHostBrokerTests.swift +++ b/Tests/XcodeMCPProxyRuntimeTests/NativeHostBrokerTests.swift @@ -536,7 +536,7 @@ struct NativeHostBrokerTests { "name": .string(NativeHostBroker.openWorkspaceTool), "arguments": .object(["path": .string("/Fixture/App.xcodeproj"), "hostIdentifier": other]), ])) - guard let error = failed.jsonRPCError, error.code == -32001, error.message == "upstream unavailable" else { + guard let error = failed.jsonRPCError, error.code == -32001, error.message == "host unavailable" else { Issue.record("A host that cannot start did not report itself unavailable: \(failed)"); return } #expect(try await fixture.workspaces(session).isEmpty) @@ -562,7 +562,7 @@ struct NativeHostBrokerTests { guard let error = reply.jsonRPCError, error.code == -32603 else { Issue.record("runtime transport failure became a tool result"); return } - #expect(error.message == "invalid upstream response") + #expect(error.message == "invalid host response") } @Test func nativeProtocolErrorsKeepTheirPayloadAndClientCorrelation() async throws { @@ -867,9 +867,9 @@ struct NativeHostBrokerTests { } } -private final class BrokerTransport: UpstreamSession, Sendable { - let events: AsyncStream - private let continuation: AsyncStream.Continuation +private final class BrokerTransport: MCPProcessSession, Sendable { + let events: AsyncStream + private let continuation: AsyncStream.Continuation let waiting = TestSignal() let stopped = TestSignal() let holdsStop = NIOLockedValueBox(false) @@ -917,7 +917,7 @@ private final class BrokerTransport: UpstreamSession, Sendable { self.processID = processID ?? 1000 + index self.manifestOpensDirectory = manifestOpensDirectory initialization.withLockedValue { $0.held = holdsInitialization } - let pair = AsyncStream.makeStream() + let pair = AsyncStream.makeStream() events = pair.stream continuation = pair.continuation } @@ -932,7 +932,7 @@ private final class BrokerTransport: UpstreamSession, Sendable { continuation.finish() } - func send(_ data: Data) async -> Upstream.SendResult { + func send(_ data: Data) async -> MCPProcess.SendResult { do { let object = try JSONRPC.Wire.object(fromData: data) if case .response(let id) = JSONRPC.Message.Inspector.kind(of: object) { @@ -1122,7 +1122,7 @@ private final class BrokerRuntimeFactory: Sendable { let invalidResponses = NIOLockedValueBox>([]) let created = TestSignal() - func make(_ configuration: NativeHostRuntime.Configuration) -> any UpstreamSessionFactory { + func make(_ configuration: NativeHostRuntime.Configuration) -> any MCPProcessSessionFactory { BrokerHostProcesses(owner: self) } @@ -1150,7 +1150,7 @@ private final class BrokerRuntimeFactory: Sendable { } /// The processes of one host; each start is a new transport that keeps the host's index. -private final class BrokerHostProcesses: UpstreamSessionFactory, Sendable { +private final class BrokerHostProcesses: MCPProcessSessionFactory, Sendable { let owner: BrokerRuntimeFactory let index = NIOLockedValueBox(nil) @@ -1158,7 +1158,7 @@ private final class BrokerHostProcesses: UpstreamSessionFactory, Sendable { self.owner = owner } - func startSession() async throws -> any UpstreamSession { try owner.start(self) } + func startSession() async throws -> any MCPProcessSession { try owner.start(self) } } private final class BrokerFixture: Sendable { diff --git a/Tests/XcodeMCPProxyRuntimeTests/NativeHostConnectionTests.swift b/Tests/XcodeMCPProxyRuntimeTests/NativeHostConnectionTests.swift index c5c85a99..c40a4acf 100644 --- a/Tests/XcodeMCPProxyRuntimeTests/NativeHostConnectionTests.swift +++ b/Tests/XcodeMCPProxyRuntimeTests/NativeHostConnectionTests.swift @@ -59,12 +59,12 @@ struct NativeHostConnectionTests { let upstreamIDs = host.requests("tools/call").compactMap { $0["id"] } #expect(Set(upstreamIDs.map { "\($0)" }).count == 2) guard case .object(let params)? = host.requests("tools/call").first?["params"], - case .object(let meta)? = params["_meta"], let upstreamToken = meta["progressToken"] else { + case .object(let meta)? = params["_meta"], let hostToken = meta["progressToken"] else { Issue.record("The progress token did not reach the host"); return } - #expect(upstreamToken != .string("token")) + #expect(hostToken != .string("token")) host.emit(.object(["jsonrpc": .string("2.0"), "method": .string("notifications/progress"), - "params": .object(["progressToken": upstreamToken, "progress": .number(.int(1))])])) + "params": .object(["progressToken": hostToken, "progress": .number(.int(1))])])) host.release("tools/call", with: .result(.object(["content": .array([])]))) #expect(try await first.value["id"] == .number(.int(1))) #expect(try await second.value["id"] == .number(.int(1))) @@ -412,7 +412,7 @@ struct NativeHostConnectionTests { } /// Returns its session only after `gate` is signaled. -private final class GatedSessionFactory: UpstreamSessionFactory, Sendable { +private final class GatedSessionFactory: MCPProcessSessionFactory, Sendable { let session: FakeHostSession let gate: TestSignal let entered = TestSignal() @@ -422,7 +422,7 @@ private final class GatedSessionFactory: UpstreamSessionFactory, Sendable { self.gate = gate } - func startSession() async throws -> any UpstreamSession { + func startSession() async throws -> any MCPProcessSession { entered.signal() try await gate.wait(description: "process start released") return session diff --git a/Tests/XcodeMCPProxyRuntimeTests/NativeHostRuntimeTests.swift b/Tests/XcodeMCPProxyRuntimeTests/NativeHostRuntimeTests.swift index 4fe74e0a..b2a79772 100644 --- a/Tests/XcodeMCPProxyRuntimeTests/NativeHostRuntimeTests.swift +++ b/Tests/XcodeMCPProxyRuntimeTests/NativeHostRuntimeTests.swift @@ -34,7 +34,7 @@ struct NativeHostRuntimeTests { } @Test func nativeHostIgnoresInheritedGUIRoutingConfiguration() throws { - let configuration = try NativeHostRuntime.makeDefaultUpstreamConfig( + let configuration = try NativeHostRuntime.makeDefaultProcessConfig( config: makeBridgeRuntimeConfig(makeConfig(requestTimeout: .seconds(5))), baseEnvironment: ["MCP_XCODE_PID": "9876", "MCP_XCODE_SESSION_ID": "parent-session", "XCODE_PID": "legacy", "DEVELOPER_DIR": "/Parent/Developer", "PATH": "/usr/bin"]) @@ -52,7 +52,7 @@ struct NativeHostRuntimeTests { func compilationCacheSharingReachesTheOwnedHost(sharesCompilationCache: Bool) throws { var config = makeConfig(requestTimeout: .seconds(5)) config.sharesCompilationCache = sharesCompilationCache - let configuration = try NativeHostRuntime.makeDefaultUpstreamConfig( + let configuration = try NativeHostRuntime.makeDefaultProcessConfig( config: makeBridgeRuntimeConfig(config), baseEnvironment: [:]) #expect(configuration.args.contains("--share-compilation-cache") == sharesCompilationCache) @@ -69,7 +69,7 @@ struct NativeHostRuntimeTests { let environment = try await NativeHostRuntime.buildServiceEnvironment( baseEnvironment: ["PATH": "/usr/bin", "MCP_XCODE_PID": "9876"], processRunner: runner) - let configuration = try NativeHostRuntime.makeDefaultUpstreamConfig( + let configuration = try NativeHostRuntime.makeDefaultProcessConfig( config: makeBridgeRuntimeConfig(makeConfig(requestTimeout: .seconds(5))), baseEnvironment: environment) @@ -187,8 +187,8 @@ struct NativeHostRuntimeTests { @Test func upstreamStderrLogLimiterSuppressesRepeatedMessages() { - let limiter = UpstreamStderrLogLimiter(duplicateLogIntervalNanoseconds: 1_000_000_000) - let message = "some upstream stderr" + let limiter = HostStderrLogLimiter(duplicateLogIntervalNanoseconds: 1_000_000_000) + let message = "some host stderr" let first = limiter.decision( upstreamIndex: 0, message: message, diff --git a/Tests/XcodeMCPProxyRuntimeTests/ProxyLoggingTests.swift b/Tests/XcodeMCPProxyRuntimeTests/ProxyLoggingTests.swift index ad75b9eb..0e08c97b 100644 --- a/Tests/XcodeMCPProxyRuntimeTests/ProxyLoggingTests.swift +++ b/Tests/XcodeMCPProxyRuntimeTests/ProxyLoggingTests.swift @@ -50,7 +50,7 @@ struct ProxyLoggingTests { func upstreamStderrUsesTheDeclaredDiagnosticLevel( input: (message: String, level: Logger.Level) ) async throws { - #expect(UpstreamStderrLogFilter.level(for: input.message) == input.level) + #expect(HostStderrLogFilter.level(for: input.message) == input.level) } @Test(arguments: [ @@ -63,11 +63,11 @@ struct ProxyLoggingTests { "[NativeDiagnostic:42] errorHandler: DEBUG appears in the message", ]) func upstreamConsoleOutputWithoutARecognizedDiagnosticLevelUsesDebug(message: String) async throws { - #expect(UpstreamStderrLogFilter.level(for: message) == .debug) + #expect(HostStderrLogFilter.level(for: message) == .debug) } @Test func nativeHostNSLogWithoutADeclaredLevelRemainsAnError() { let message = "2026-10-05 23:53:55.622 xcode-mcp-native-host[43311:36380528] CoreSimulatorService connection interrupted. DEBUG logging is enabled." - #expect(UpstreamStderrLogFilter.level(for: message) == .error) + #expect(HostStderrLogFilter.level(for: message) == .error) } } diff --git a/scripts/verify-proxy-target-boundaries.sh b/scripts/verify-proxy-target-boundaries.sh index 46ef40f3..1af6dedd 100755 --- a/scripts/verify-proxy-target-boundaries.sh +++ b/scripts/verify-proxy-target-boundaries.sh @@ -52,7 +52,7 @@ reject_matches \ reject_matches \ "XcodeMCPProxyHTTP references a host process type" \ - '(^|[^[:alnum:]_])Upstream[A-Za-z0-9_]*([^[:alnum:]_]|$)' \ + '(^|[^[:alnum:]_])(Upstream|MCPProcess)[A-Za-z0-9_]*([^[:alnum:]_]|$)' \ Sources/XcodeMCPProxyHTTP reject_matches \