Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 3 additions & 10 deletions Sources/XcodeMCPProxyKit/XcodeMCPProxyServer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -478,22 +478,15 @@ extension XcodeMCPProxyServerConfiguration {
guard maxBodyBytes > 0 else {
throw XcodeMCPProxyServer.LifecycleError.invalidConfiguration("maxBodyBytes must be greater than zero")
}
let timeout: TimeInterval
if let requestTimeout {
let components = requestTimeout.components
timeout = Double(components.seconds) + Double(components.attoseconds) / 1_000_000_000_000_000_000
guard timeout > 0 else {
throw XcodeMCPProxyServer.LifecycleError.invalidConfiguration("requestTimeout must be positive; use nil to disable it")
}
} else {
timeout = 0
if let requestTimeout, requestTimeout <= .zero {
throw XcodeMCPProxyServer.LifecycleError.invalidConfiguration("requestTimeout must be positive; use nil to disable it")
}
let configuration = ProxyRuntimeConfiguration(
nativeHostBundleURL: nativeHostBundleURL,
developerDirectoryURL: developerDirectoryURL,
sharesCompilationCache: sharesCompilationCache,
maxMessageBytes: maxBodyBytes,
requestTimeout: timeout,
requestTimeout: requestTimeout,
prewarmToolsList: prewarmToolsList,
initializeParamsOverride: initializeHandshake.map { handshake in
.init(
Expand Down
36 changes: 19 additions & 17 deletions Sources/XcodeMCPProxyRuntime/Broker/NativeHostBroker.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import Foundation
import Logging
import NIOCore
import NIOConcurrencyHelpers
import XcodeMCPCore
import XcodeMCPProxyRuntimeContract
Expand Down Expand Up @@ -44,7 +43,11 @@ package final class NativeHostBroker: ProxyRuntimeServing, Sendable {
private static let guiHostIdentifier = "gui-xcode"
/// Bounds a cleanup close while client requests have no timeout, so a host that never answers
/// does not keep the model from being bound again.
static let cleanupFallbackTimeout: TimeInterval = 60
static let cleanupFallbackTimeout: Duration = .seconds(60)
/// Bounds a host's initialize handshake even when client requests have no timeout.
private static let handshakeTimeoutLimit: Duration = .seconds(60)
/// Bounds an internal catalog load even when client requests have no timeout.
private static let catalogTimeoutLimit: Duration = .seconds(10)

private struct Admission: Sendable {
let hostIdentifier: String
Expand Down Expand Up @@ -91,14 +94,11 @@ package final class NativeHostBroker: ProxyRuntimeServing, Sendable {
developerDirectoryURL: installation.developerDirectory,
sharesCompilationCache: configuration.sharesCompilationCache,
maxBodyBytes: configuration.maxMessageBytes)
let timeout = configuration.requestTimeout
let connection = NativeHostConnection(
factory: sessionFactory(processConfiguration),
handshake: .object(InitializeHandshakeJSON.resolved(
initializeParamsOverride: configuration.initializeParamsOverride)),
handshakeTimeout: MCP.MethodDispatcher.timeoutForInitialize(defaultSeconds: timeout).map(Self.duration),
// An internal catalog load stays bounded even when client request timeouts are disabled.
catalogTimeout: MCP.MethodDispatcher.timeoutForControlPlane(defaultSeconds: timeout).map(Self.duration),
handshakeTimeout: handshakeTimeout, catalogTimeout: catalogTimeout,
prewarmsCatalog: configuration.prewarmToolsList, clock: clock,
logger: ProxyLogging.make("native-host"),
onEvent: { [weak self] event in self?.receive(event, from: id) })
Expand All @@ -110,18 +110,22 @@ package final class NativeHostBroker: ProxyRuntimeServing, Sendable {
}
}

private static func duration(_ amount: TimeAmount) -> Duration { .nanoseconds(amount.nanoseconds) }
private var handshakeTimeout: Duration {
min(configuration.requestTimeout ?? Self.handshakeTimeoutLimit, Self.handshakeTimeoutLimit)
}

private var catalogTimeout: Duration {
min(configuration.requestTimeout ?? Self.catalogTimeoutLimit, Self.catalogTimeoutLimit)
}

private func guiConnection() throws -> NativeHostConnection {
try state.withLockedValue { storage in
guard !storage.stopped, storage.resetsInProgress == 0 else { throw CancellationError() }
if let connection = storage.guiConnection { return connection }
let timeout = configuration.requestTimeout
let connection = NativeHostConnection(factory: guiSessionFactory,
handshake: .object(InitializeHandshakeJSON.resolved(
initializeParamsOverride: configuration.initializeParamsOverride)),
handshakeTimeout: MCP.MethodDispatcher.timeoutForInitialize(defaultSeconds: timeout).map(Self.duration),
catalogTimeout: MCP.MethodDispatcher.timeoutForControlPlane(defaultSeconds: timeout).map(Self.duration),
handshakeTimeout: handshakeTimeout, catalogTimeout: catalogTimeout,
prewarmsCatalog: false, clock: clock, logger: ProxyLogging.make("mcpbridge"),
onEvent: { [weak self] event in self?.receive(event, from: Self.guiHostIdentifier) })
storage.guiConnection = connection
Expand Down Expand Up @@ -182,8 +186,8 @@ package final class NativeHostBroker: ProxyRuntimeServing, Sendable {
let cancelled = NativeBrokerReply.error(id: requestID, code: -32800, message: "request cancelled").clientReply
var deadline: Date?
if let object, case .request = JSONRPC.Message.Inspector.kind(of: object),
let timeout = makeRequestTimeout(configuration.requestTimeout) {
deadline = clock.now().addingTimeInterval(Double(timeout.nanoseconds) / 1_000_000_000)
let timeout = configuration.requestTimeout {
deadline = clock.now().addingTimeInterval(timeout / .seconds(1))
}
// Admission pins the host under the broker lock, which the unused-host scan also holds,
// so a host is kept for this request before idle retirement can stop its process.
Expand Down Expand Up @@ -565,8 +569,7 @@ package final class NativeHostBroker: ProxyRuntimeServing, Sendable {
"workspaceIdentifier": .string(workspace.nativeIdentifier),
])]),
])
let timeout = makeRequestTimeout(
configuration.requestTimeout > 0 ? configuration.requestTimeout : Self.cleanupFallbackTimeout)
let timeout = configuration.requestTimeout ?? Self.cleanupFallbackTimeout
do {
let reply = try await withDeadline(timeout) {
try await host.connection.sendToRunningProcess(request, generation: workspace.generation)
Expand All @@ -587,14 +590,13 @@ package final class NativeHostBroker: ProxyRuntimeServing, Sendable {
}

/// Runs `operation`, failing it with `CancellationError` once `timeout` elapses.
private func withDeadline<T: Sendable>(_ timeout: TimeAmount?,
private func withDeadline<T: Sendable>(_ timeout: Duration,
_ operation: @escaping @Sendable () async throws -> T) async throws -> T {
guard let timeout else { return try await operation() }
let clock = clock
return try await withThrowingTaskGroup(of: T.self) { group in
group.addTask { try await operation() }
group.addTask {
await clock.sleep(.nanoseconds(timeout.nanoseconds))
await clock.sleep(timeout)
throw CancellationError()
}
defer { group.cancelAll() }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ package struct ProxyRuntimeConfiguration: Sendable {
package var developerDirectoryURL: URL?
package var sharesCompilationCache: Bool
package var maxMessageBytes: Int
package var requestTimeout: TimeInterval
/// The limit for one client request, or `nil` for none.
package var requestTimeout: Duration?
package var prewarmToolsList: Bool
package var initializeParamsOverride: InitializeHandshakeOverride?

Expand All @@ -68,7 +69,7 @@ package struct ProxyRuntimeConfiguration: Sendable {
developerDirectoryURL: URL? = nil,
sharesCompilationCache: Bool = false,
maxMessageBytes: Int,
requestTimeout: TimeInterval,
requestTimeout: Duration?,
prewarmToolsList: Bool = true,
initializeParamsOverride: InitializeHandshakeOverride? = nil
) {
Expand Down
35 changes: 0 additions & 35 deletions Sources/XcodeMCPProxyRuntime/Support/MCPMethodDispatcher.swift

This file was deleted.

10 changes: 0 additions & 10 deletions Sources/XcodeMCPProxyRuntime/Support/TimeoutSupport.swift

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import XcodeMCPProxyTestSupport

extension HTTPHandlerTests {
@Test func httpDocumentationSearchIsForwardedToNativeHost() async throws {
let config = makeHTTPConfig(requestTimeout: 2)
let config = makeHTTPConfig(requestTimeout: .seconds(2))
let runtime = try HTTPTestRuntime(config: config) { method, params in
#expect(method == "tools/call")
#expect(params["name"] == .string("DocumentationSearch"))
Expand Down Expand Up @@ -53,7 +53,7 @@ extension HTTPHandlerTests {
}

@Test func httpBatchDocumentationSearchIsForwardedToNativeHost() async throws {
let config = makeHTTPConfig(requestTimeout: 2)
let config = makeHTTPConfig(requestTimeout: .seconds(2))
let runtime = try HTTPTestRuntime(config: config)
let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime)

Expand Down Expand Up @@ -87,7 +87,7 @@ extension HTTPHandlerTests {
}

@Test func httpBatchToolsListUsesLocalToolSurfaceAndForwardsOtherCalls() async throws {
let config = makeHTTPConfig(requestTimeout: 2)
let config = makeHTTPConfig(requestTimeout: .seconds(2))
let runtime = try HTTPTestRuntime(config: config)
let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime)

Expand Down
26 changes: 13 additions & 13 deletions Tests/ProxyIntegrationTests/HTTPConcurrencyTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import XcodeMCPProxyTestSupport
struct HTTPConcurrencyTests {
@Test(arguments: ["BuildProject", "FutureNativeTool"])
func nativeToolCallsResolveWorkspacePathsAndPreserveProviderErrors(toolName: String) async throws {
let config = makeHTTPConfig(requestTimeout: 5)
let config = makeHTTPConfig(requestTimeout: .seconds(5))
let tools = JSONValue.object(["tools": .array([.object([
"name": .string("BuildProject"),
"inputSchema": .object([
Expand Down Expand Up @@ -74,7 +74,7 @@ struct HTTPConcurrencyTests {
}

@Test func httpAndSwiftClientExposeTheCompleteCatalog() async throws {
var config = makeHTTPConfig(requestTimeout: 5)
var config = makeHTTPConfig(requestTimeout: .seconds(5))
config.prewarmToolsList = false
let runtime = try HTTPTestRuntime(config: config)
let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime)
Expand Down Expand Up @@ -111,7 +111,7 @@ struct HTTPConcurrencyTests {

@Test(arguments: ["DocumentationSearch", "XcodeListWorkspaces"])
func httpCancellationDoesNotWaitBehindTheRequest(toolName: String) async throws {
let config = makeHTTPConfig(requestTimeout: 60)
let config = makeHTTPConfig(requestTimeout: .seconds(60))
let runtime = try HTTPTestRuntime(config: config) { _, _ in .hold }
let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime)
do {
Expand Down Expand Up @@ -153,7 +153,7 @@ struct HTTPConcurrencyTests {
/// A request's progress opens its own POST response as an event stream that ends with the
/// reply; a request that reports no progress still gets JSON.
@Test func progressStreamsOnlyOnItsRequestsResponse() async throws {
let config = makeHTTPConfig(requestTimeout: 60)
let config = makeHTTPConfig(requestTimeout: .seconds(60))
let runtime = try HTTPTestRuntime(config: config) { _, _ in .hold }
let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime)
do {
Expand Down Expand Up @@ -209,7 +209,7 @@ struct HTTPConcurrencyTests {
}

@Test func multiplexedCancellationPreservesOtherSessionsAndIDScalarTypes() async throws {
let config = makeHTTPConfig(requestTimeout: 60)
let config = makeHTTPConfig(requestTimeout: .seconds(60))
let runtime = try HTTPTestRuntime(config: config) { _, _ in .hold }
let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime)
do {
Expand Down Expand Up @@ -269,7 +269,7 @@ struct HTTPConcurrencyTests {
}

@Test func httpConcurrentInitializeRequests() async throws {
let config = makeHTTPConfig(requestTimeout: 5)
let config = makeHTTPConfig(requestTimeout: .seconds(5))
let runtime = try HTTPTestRuntime(config: config)
let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime)
let url = server.url
Expand All @@ -289,7 +289,7 @@ struct HTTPConcurrencyTests {

@Test func httpConcurrentInitializeStress() async throws {
let count = 10
let config = makeHTTPConfig(requestTimeout: 5)
let config = makeHTTPConfig(requestTimeout: .seconds(5))
let runtime = try HTTPTestRuntime(config: config)
let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime)
let url = server.url
Expand All @@ -307,7 +307,7 @@ struct HTTPConcurrencyTests {
}

@Test func httpConcurrentRequestsShareSession() async throws {
var config = makeHTTPConfig(requestTimeout: 5)
var config = makeHTTPConfig(requestTimeout: .seconds(5))
config.prewarmToolsList = false
let runtime = try HTTPTestRuntime(config: config)
let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime)
Expand Down Expand Up @@ -354,7 +354,7 @@ struct HTTPConcurrencyTests {
}

@Test func httpConcurrentRequestsCanOverlapAcrossSessions() async throws {
var config = makeHTTPConfig(requestTimeout: 5)
var config = makeHTTPConfig(requestTimeout: .seconds(5))
config.prewarmToolsList = false
let runtime = try HTTPTestRuntime(config: config)
let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime)
Expand Down Expand Up @@ -403,7 +403,7 @@ struct HTTPConcurrencyTests {
}

@Test func httpRequestTimeoutDoesNotCancelAnotherRequestOnTheSameNativeConnection() async throws {
let config = makeHTTPConfig(requestTimeout: 10)
let config = makeHTTPConfig(requestTimeout: .seconds(10))
let clock = TestClock()
let runtime = try HTTPTestRuntime(config: config, clock: makeHTTPTestClock(clock)) { _, _ in .hold }
let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime)
Expand Down Expand Up @@ -453,7 +453,7 @@ struct HTTPConcurrencyTests {
}

@Test func httpNotificationIsAcceptedWithoutWaitingForAnotherRequestResult() async throws {
let config = makeHTTPConfig(requestTimeout: 10)
let config = makeHTTPConfig(requestTimeout: .seconds(10))
let runtime = try HTTPTestRuntime(config: config) { _, _ in .hold }
let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime)
let url = server.url
Expand Down Expand Up @@ -491,7 +491,7 @@ struct HTTPConcurrencyTests {
}

@Test func httpToolCallNotificationIsAcceptedWithoutReachingTheHost() async throws {
let config = makeHTTPConfig(requestTimeout: 5)
let config = makeHTTPConfig(requestTimeout: .seconds(5))
let runtime = try HTTPTestRuntime(config: config)
let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime)
let url = server.url
Expand Down Expand Up @@ -521,7 +521,7 @@ struct HTTPConcurrencyTests {

/// Host notifications reach the session's GET stream; progress reaches only its request's response.
@Test func httpServerNotificationsReachActiveSSESessions() async throws {
let config = makeHTTPConfig(requestTimeout: 10)
let config = makeHTTPConfig(requestTimeout: .seconds(10))
let runtime = try HTTPTestRuntime(config: config) { _, _ in .hold }
let server = try TestHTTPHandlerServer.start(config: config, runtime: runtime)
let url = server.url
Expand Down
4 changes: 2 additions & 2 deletions Tests/ProxyIntegrationTests/HTTPHandlerTestSupport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ struct HTTPTestConfiguration: Sendable {
var maxBodyBytes: Int
var enablesDebugEndpoints = false

var requestTimeout: TimeInterval {
var requestTimeout: Duration? {
get { runtime.requestTimeout }
set { runtime.requestTimeout = newValue }
}
Expand Down Expand Up @@ -126,7 +126,7 @@ final class HTTPTestRuntime: Sendable {

func makeHTTPConfig(
maxBodyBytes: Int = 1024,
requestTimeout: TimeInterval = 1
requestTimeout: Duration? = .seconds(1)
) -> HTTPTestConfiguration {
HTTPTestConfiguration(
runtime: ProxyRuntimeConfiguration(
Expand Down
Loading